/******/ var __webpack_modules__ = ({

/***/ 410:
/***/ ((module, exports, __webpack_require__) => {

var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
 * Backbone.Undo.js v0.2
 * 
 * Copyright (c)2013 Oliver Sartun
 * Released under the MIT License
 *
 * Documentation and full license available at
 * https://github.com/osartun/Backbone.Undo.js
 */


(function (factory) {
	if (true) {
		// AMD support
		!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(50), __webpack_require__(316)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
		__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
		(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
		__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
	} else {}
})(function (_, Backbone) {

	var core_slice = Array.prototype.slice;

	/**
	 * As call is faster than apply, this is a faster version of apply as it uses call.
	 * 
	 * @param  {Function} fn 	The function to execute 
	 * @param  {Object}   ctx 	The context the function should be called in
	 * @param  {Array}    args 	The array of arguments that should be applied to the function
	 * @return Forwards whatever the called function returns
	 */
	function apply (fn, ctx, args) {
		return args.length <= 4 ?
			fn.call(ctx, args[0], args[1], args[2], args[3]) :
			fn.apply(ctx, args);
	}

	/**
	 * Uses slice on an array or an array-like object.
	 * 
	 * @param  {Array|Object} 	arr 	The array or array-like object.
	 * @param  {Number} 		[index]	The index from where the array should be sliced. Default is 0.
	 * @return {Array} The sliced array
	 */
	function slice (arr, index) {
		return core_slice.call(arr, index);
	}

	/**
	 * Checks if an object has one or more specific keys. The keys 
	 * don't have to be an owned property.
	 * You can call this function either this way:
	 * hasKeys(obj, ["a", "b", "c"])
	 * or this way:
	 * hasKeys(obj, "a", "b", "c")
	 * 
	 * @param  {Object}  	obj 	The object to check on
	 * @param  {Array}  	keys 	The keys to check for
	 * @return {Boolean} True, if the object has all those keys
	 */
	function hasKeys (obj, keys) {
		if (obj == null) return false;
		if (!_.isArray(keys)) {
			keys = slice(arguments, 1);
		}
		return _.all(keys, function (key) {
			return key in obj;
		});
	}

	/**
	 * Returns a number that is unique per call stack. The number gets 
	 * changed after the call stack has been completely processed.
	 * 
	 * @return {number} MagicFusionIndex
	 */
	var getMagicFusionIndex = (function () {
		// If you add several models to a collection or set several
		// attributes on a model all in sequence and yet all for
		// example in one function, then several Undo-Actions are
		// generated.
		// If you want to undo your last action only the last model
		// would be removed from the collection or the last set
		// attribute would be changed back to its previous value.
		// To prevent that we have to figure out a way to combine
		// all those actions that happened "at the same time". 
		// Timestamps aren't exact enough. A complex routine could 
		// run several milliseconds and in that time produce a lot 
		// of actions with different timestamps.
		// Instead we take advantage of the single-threadedness of
		// JavaScript:

		var callstackWasIndexed = false, magicFusionIndex = -1;
		function indexCycle() {
			magicFusionIndex++;
			callstackWasIndexed = true;
			_.defer(function () {
				// Here comes the magic. With a Timeout of 0 
				// milliseconds this function gets called whenever
				// the current callstack is completed
				callstackWasIndexed = false;
			})
		}
		return function () {
			if (!callstackWasIndexed) {
				indexCycle();
			}
			return magicFusionIndex;
		}
	})();

	/**
	 * To prevent binding a listener several times to one 
	 * object, we register the objects in an ObjectRegistry
	 *
	 * @constructor
	 */
	function ObjectRegistry () {
		// This uses two different ways of storing
		// objects: In case the object has a cid
		// (which Backbone objects typically have)
		// it uses this cid as an index. That way
		// the Array's length attribute doesn't 
		// change and the object isn't an item 
		// in the array, but an object-property.
		// Otherwise it's added to the Array as an
		// item.
		// That way we can use the fast property-
		// lookup and only have to fall back to 
		// iterating over the array in case 
		// non-Backbone-objects are registered.
		this.registeredObjects = [];
		// To return a list of all registered 
		// objects in the 'get' method we have to
		// store the objects that have a cid in
		// an additional array. 
		this.cidIndexes = [];
	}
	ObjectRegistry.prototype = {
		/**
		 * Returns whether the object is already registered in this ObjectRegistry or not.
		 * 
		 * @this 	{ObjectRegistry}
		 * @param  	{Object} 		 obj 	The object to check
		 * @return 	{Boolean} True if the object is already registered
		 */
		isRegistered: function (obj) {
			// This is where we get a performance boost 
			// by using the two different ways of storing 
			// objects.
			return obj && obj.cid ? this.registeredObjects[obj.cid] : _.contains(this.registeredObjects, obj);
		},
		/**
		 * Registers an object in this ObjectRegistry.
		 * 
		 * @this 	{ObjectRegistry}
		 * @param  	{Object} 		 obj 	The object to register
		 * @return 	{undefined}
		 */
		register: function (obj) {
			if (!this.isRegistered(obj)) {
				if (obj && obj.cid) {
					this.registeredObjects[obj.cid] = obj;
					this.cidIndexes.push(obj.cid);
				} else {
					this.registeredObjects.push(obj);
				}
				return true;
			}
			return false;
		},
		/**
		 * Unregisters an object from this ObjectRegistry.
		 * 
		 * @this {ObjectRegistry}
		 * @param  {Object} obj The object to unregister
		 * @return {undefined}
		 */
		unregister: function (obj) {
			if (this.isRegistered(obj)) {
				if (obj && obj.cid) {
					delete this.registeredObjects[obj.cid];
					this.cidIndexes.splice(_.indexOf(this.cidIndexes, obj.cid), 1);
				} else {
					var i = _.indexOf(this.registeredObjects, obj);
					this.registeredObjects.splice(i, 1);
				}
				return true;
			}
			return false;
		},
		/**
		 * Returns an array of all objects that are currently in this ObjectRegistry.
		 * 
		 * @return {Array} An array of all the objects which are currently in the ObjectRegistry
		 */
		get: function () {
			return (_.map(this.cidIndexes, function (cid) {return this.registeredObjects[cid];}, this)).concat(this.registeredObjects);
		}
	}

	/**
	 * Binds or unbinds the "all"-listener for one or more objects.
	 * 
	 * @param  {String}   which 	Either "on" or "off"
	 * @param  {Object[]} objects 	Array of the objects on which the "all"-listener should be bound / unbound to
	 * @param  {Function} [fn] 		The function that should be bound / unbound. Optional in case of "off"
	 * @param  {Object}   [ctx] 	The context the function should be called in
	 * @return {undefined}
	 */
	function onoff(which, objects, fn, ctx) {
		for (var i = 0, l = objects.length, obj; i < l; i++) {
			obj = objects[i];
			if (!obj) continue;
			if (which === "on") {
				if (!ctx.objectRegistry.register(obj)) {
					// register returned false, so obj was already registered
					continue;
				}
			} else {
				if (!ctx.objectRegistry.unregister(obj)) {
					// unregister returned false, so obj wasn't registered
					continue;
				}
			}
			if (_.isFunction(obj[which])) {
				obj[which]("all", fn, ctx);
			}
		}
	}

	/**
	 * Calls the undo/redo-function for a specific action.
	 * 
	 * @param  {String} which 	Either "undo" or "redo"
	 * @param  {Object} action 	The Action's attributes
	 * @return {undefined}
	 */
	function actionUndoRedo (which, action) {
		var type = action.type, undoTypes = action.undoTypes, fn = !undoTypes[type] || undoTypes[type][which];
		if (_.isFunction(fn)) {
			fn(action.object, action.before, action.after, action.options);
		}
	}

	/**
	 * The main undo/redo function.
	 *
	 * @param  {String} 		which 	    Either "undo" or "redo"
	 * @param  {UndoManager} 	manager	    The UndoManager-instance on which an "undo"/"redo"-Event is triggered afterwards
	 * @param  {UndoStack} 		stack 	    The UndoStack on which we perform
	 * @param  {Boolean} 		magic 	    If true, undoes / redoes all actions with the same magicFusionIndex
	 * @param  {Boolean} 		everything  If true, undoes / redoes every action that had been tracked
	 * @return {undefined}
	 */
	function managerUndoRedo (which, manager, stack, magic, everything) {
		if (stack.isCurrentlyUndoRedoing || 
			(which === "undo" && stack.pointer === -1) ||
			(which === "redo" && stack.pointer === stack.length - 1)) {
			// We're either currently in an undo- / redo-process or 
			// we reached the end of the stack
			return;
		}
		stack.isCurrentlyUndoRedoing = true;
		var action, actions, isUndo = which === "undo";
		if (everything) {
			// Undo / Redo all steps until you reach the stack's beginning / end
			actions = isUndo && stack.pointer === stack.length - 1 || // If at the stack's end calling undo
					  !isUndo && stack.pointer === -1 ? // or at the stack's beginning calling redo
					  _.clone(stack.models) : // => Take all the models. Otherwise:
					  core_slice.apply(stack.models, isUndo ? [0, stack.pointer] : [stack.pointer, stack.length - 1]);
		} else {
			// Undo / Redo only one step
			action = stack.at(isUndo ? stack.pointer : stack.pointer + 1);
			actions = magic ? stack.where({"magicFusionIndex": action.get("magicFusionIndex")}) : [action];
		}
		
		stack.pointer += (isUndo ? -1 : 1) * actions.length;
		while (action = isUndo ? actions.pop() : actions.shift()) {
			// Here we're calling the Action's undo / redo method
			action[which]();
		}
		stack.isCurrentlyUndoRedoing = false;

		manager.trigger(which, manager);
	}

	/**
	 * Checks whether an UndoAction should be created or not. Therefore it checks
	 * whether a "condition" property is set in the undoTypes-object of the specific
	 * event type. If not, it returns true. If it's set and a boolean, it returns it.
	 * If it's a function, it returns its result, converting it into a boolean. 
	 * Otherwise it returns true.
	 * 
	 * @param  {Object} 	undoTypesType 	The object within the UndoTypes that holds the function for this event type (i.e. "change")
	 * @param  {Arguments} 	args       		The arguments the "condition" function is called with
	 * @return {Boolean} 	True, if an UndoAction should be created
	 */
	function validateUndoActionCreation (undoTypesType, args) {
		var condition = undoTypesType.condition, type = typeof condition;
		return type === "function" ? !!apply(condition, undoTypesType, args) :
			type === "boolean" ? condition : true;
	}

	/**
	 * Adds an Undo-Action to the stack.
	 * 
	 * @param {UndoStack} 		stack 		The undostack the action should be added to.
	 * @param {String} 			type 		The event type (i.e. "change")
	 * @param {Arguments} 		args 		The arguments passed to the undoTypes' "on"-handler
	 * @param {OwnedUndoTypes} 	undoTypes 	The undoTypes-object which has the "on"-handler
	 * @return {undefined}
	 */
	function addToStack(stack, type, args, undoTypes) {
		if (stack.track && !stack.isCurrentlyUndoRedoing && type in undoTypes &&
			validateUndoActionCreation(undoTypes[type], args)) {
			// An UndoAction should be created
			var res = apply(undoTypes[type]["on"], undoTypes[type], args), diff;
			if (hasKeys(res, "object", "before", "after")) {
				res.type = type;
				res.magicFusionIndex = getMagicFusionIndex();
				res.undoTypes = undoTypes;
				if (stack.pointer < stack.length - 1) {
					// New Actions must always be added to the end of the stack.
					// If the pointer is not pointed to the last action in the
					// stack, presumably because actions were undone before, then
					// all following actions must be discarded
					var diff = stack.length - stack.pointer - 1;
					while (diff--) {
						stack.pop();
					}
				}
				stack.pointer = stack.length;
				stack.add(res);
				if (stack.length > stack.maximumStackLength) {
					stack.shift();
					stack.pointer--;
				}
			}
		}
	}


	/**
	 * Predefined UndoTypes object with default handlers for the most common events.
	 * @type {Object}
	 */
	var UndoTypes = {
		"add": {
			"undo": function (collection, ignore, model, options) {
				// Undo add = remove
				collection.remove(model, options);
			},
			"redo": function (collection, ignore, model, options) {
				// Redo add = add
				if (options.index) {
					options.at = options.index;
				}
				collection.add(model, options);
			},
			"on": function (model, collection, options) {
				return {
					object: collection,
					before: undefined,
					after: model,
					options: _.clone(options)
				};
			}
		},
		"remove": {
			"undo": function (collection, model, ignore, options) {
				if ("index" in options) {
					options.at = options.index;
				}
				collection.add(model, options);
			},
			"redo": function (collection, model, ignore, options) {
				collection.remove(model, options);
			},
			"on": function (model, collection, options) {
				return {
					object: collection,
					before: model,
					after: undefined,
					options: _.clone(options)
				};
			}
		},
		"change": {
			"undo": function (model, before, after, options) {
				if (_.isEmpty(before)) {
					_.each(_.keys(after), model.unset, model);
				} else {
					model.set(before);
					if (options && options.unsetData && options.unsetData.before && options.unsetData.before.length) {
						_.each(options.unsetData.before, model.unset, model);
					}
				}
			},
			"redo": function (model, before, after, options) {
				if (_.isEmpty(after)) {
					_.each(_.keys(before), model.unset, model);
				} else {
					model.set(after);
					if (options && options.unsetData && options.unsetData.after && options.unsetData.after.length) {
						_.each(options.unsetData.after, model.unset, model);
					}
				}
			},
			"on": function (model, options) {
				var
				afterAttributes = model.changedAttributes(),
				keysAfter = _.keys(afterAttributes),
				previousAttributes = _.pick(model.previousAttributes(), keysAfter),
				keysPrevious = _.keys(previousAttributes),
				unsetData = (options || (options = {})).unsetData = {
					after: [],
					before: []
				};

				if (keysAfter.length != keysPrevious.length) {
					// There are new attributes or old attributes have been unset
					if (keysAfter.length > keysPrevious.length) {
						// New attributes have been added
						_.each(keysAfter, function (val) {
							if (!(val in previousAttributes)) {
								unsetData.before.push(val);
							}
						}, this);
					} else {
						// Old attributes have been unset
						_.each(keysPrevious, function (val) {
							if (!(val in afterAttributes)) {
								unsetData.after.push(val);
							}
						})
					}
				}
				return {
					object: model,
					before: previousAttributes,
					after: afterAttributes,
					options: _.clone(options)
				};
			}
		},
		"reset": {
			"undo": function (collection, before, after) {
				collection.reset(before);
			},
			"redo": function (collection, before, after) {
				collection.reset(after);
			},
			"on": function (collection, options) {
				return {
					object: collection,
					before: options.previousModels,
					after: _.clone(collection.models)
				};
			}
		}
	};

	/**
	 * Every UndoManager instance has an own undoTypes object
	 * which is an instance of OwnedUndoTypes. OwnedUndoTypes' 
	 * prototype is the global UndoTypes object. Changes to the 
	 * global UndoTypes object take effect on every instance of
	 * UndoManager as the object is its prototype. And yet every 
	 * local UndoTypes object can be changed individually.
	 *
	 * @constructor
	 */
	function OwnedUndoTypes () {}
	OwnedUndoTypes.prototype = UndoTypes;

	/**
	 * Adds, changes or removes an undo-type from an UndoTypes-object.
	 * You can call it this way:
	 * manipulateUndoType (1, "reset", {"on": function () {}}, undoTypes)
	 * or this way to perform bulk actions:
	 * manipulateUndoType (1, {"reset": {"on": function () {}}}, undoTypes)
	 * In case of removing undo-types you can pass an Array for performing
	 * bulk actions:
	 * manipulateUndoType(2, ["reset", "change"], undoTypes)
	 * 
	 * @param  {Number} 				  manipType 		Indicates the kind of action to execute: 0 for add, 1 for change, 2 for remove
	 * @param  {String|Object|Array} 	  undoType 			The type of undoType that should be added/changed/removed. Can be an object / array to perform bulk actions
	 * @param  {Object} 				  [fns] 			Object with the functions to add / change. Is optional in case you passed an object as undoType that contains these functions
	 * @param  {OwnedUndoTypes|UndoTypes} undoTypesInstance The undoTypes object to act on
	 * @return {undefined}
	 */
	function manipulateUndoType (manipType, undoType, fns, undoTypesInstance) {
		// manipType, passed by the calling function
		// 0: add
		// 1: change
		// 2: remove
		if (typeof undoType === "object") {
			// bulk action. Iterate over this data.
			return _.each(undoType, function (val, key) {
					if (manipType === 2) { // remove
						// undoType is an array
						manipulateUndoType (manipType, val, fns, undoTypesInstance);
					} else {
						// undoType is an object
						manipulateUndoType (manipType, key, val, fns);
					}
				})
		}

		switch (manipType) {
			case 0: // add
				if (hasKeys(fns, "undo", "redo", "on") && _.all(_.pick(fns, "undo", "redo", "on"), _.isFunction)) {
					undoTypesInstance[undoType] = fns;
				} 
			break;
			case 1: // change
				if (undoTypesInstance[undoType] && _.isObject(fns)) {
					// undoTypeInstance[undoType] may be a prototype's property
					// So, if we did this _.extend(undoTypeInstance[undoType], fns)
					// we would extend the object on the prototype which means
					// that this change would have a global effect
					// Instead we just want to manipulate this instance. That's why
					// we're doing this:
					undoTypesInstance[undoType] = _.extend({}, undoTypesInstance[undoType], fns);
				} 
			break;
			case 2: // remove
				delete undoTypesInstance[undoType]; 
			break;
		}
		return this;
	}

	/**
	 * Instantiating "Action" creates the UndoActions that 
	 * are collected in an UndoStack. It holds all relevant 
	 * data to undo / redo an action and has an undo / redo 
	 * method.
	 */
	var Action = Backbone.Model.extend({
		defaults: {
			type: null, // "add", "change", "reset", etc.
			object: null, // The object on which the action occurred
			before: null, // The previous values which were changed with this action
			after: null, // The values after this action
			magicFusionIndex: null // The magicFusionIndex helps to combine 
			// all actions that occurred "at the same time" to undo/redo them altogether
		},
		/**
		 * Undoes this action.
		 * @param  {OwnedUndoTypes|UndoTypes} undoTypes The undoTypes object which contains the "undo"-handler that should be used
		 * @return {undefined}
		 */
		undo: function (undoTypes) {
			actionUndoRedo("undo", this.attributes);
		},
		/**
		 * Redoes this action.
		 * @param  {OwnedUndoTypes|UndoTypes} undoTypes The undoTypes object which contains the "redo"-handler that should be used
		 * @return {undefined}
		 */
		redo: function (undoTypes) {
			actionUndoRedo("redo", this.attributes);
		}
	}),
	/**
	 * An UndoStack is a collection of UndoActions in 
	 * chronological order.
	 */
	UndoStack = Backbone.Collection.extend({
		model: Action,
		pointer: -1, // The pointer indicates the index where we are located within the stack. We start at -1
		track: false,
		isCurrentlyUndoRedoing: false,
		maximumStackLength: Infinity,
		setMaxLength: function (val) {
			this.maximumStackLength = val;
		}
	}),
	/**
	 * An instance of UndoManager can keep track of 
	 * changes to objects and helps to undo them.
	 */
	UndoManager = Backbone.Model.extend({
		defaults: {
			maximumStackLength: Infinity,
			track: false
		},
		/**
		 * The constructor function.
		 * @param  {attr} 		[attr] Object with parameters. The available parameters are:
		 *                         	   - maximumStackLength {number} 	Set the undo-stack's maximum size
		 *                             - track 				{boolean}	Start tracking changes right away
		 * @return {undefined}
		 */
		initialize: function (attr) {
			this.stack = new UndoStack;
			this.objectRegistry = new ObjectRegistry();
			this.undoTypes = new OwnedUndoTypes();

			// sync the maximumStackLength attribute with our stack
			this.stack.setMaxLength(this.get("maximumStackLength"));
			this.on("change:maximumStackLength", function (model, value) {
				this.stack.setMaxLength(value);
			}, this);

			// Start tracking, if attr.track == true
			if (attr && attr.track) {
				this.startTracking();
			}

			// Register objects passed in the "register" attribute
			if (attr && attr.register) {
				if (_.isArray(attr.register) || _.isArguments(attr.register)) {
					apply(this.register, this, attr.register);
				} else {
					this.register(attr.register);
				}
			}
		},
		/**
		 * Starts tracking. Changes of registered objects won't be processed until you've called this function
		 * @return {undefined}
		 */
		startTracking: function () {
			this.set("track", true);
			this.stack.track = true;
		},
		/**
		 * Stops tracking. Afterwards changes of registered objects won't be processed.
		 * @return {undefined}
		 */
		stopTracking: function () {
			this.set("track", false);
			this.stack.track = false;
		},
		/**
		 * Return the state of the tracking
		 * @return {boolean}
		 */
		isTracking: function () {
			return this.get("track");
		},
		/**
		 * This is the "all"-handler which is bound to registered 
		 * objects. It creates an UndoAction from the event and adds 
		 * it to the stack.
		 * 
		 * @param  {String} 	type 	The event type
		 * @return {undefined}
		 */
		_addToStack: function (type) {
			addToStack(this.stack, type, slice(arguments, 1), this.undoTypes);
		},
		/**
		 * Registers one or more objects to track their changes.
		 * @param {...Object} 	obj 	The object or objects of which changes should be tracked
		 * @return {undefined}
		 */
		register: function () {
			onoff("on", arguments, this._addToStack, this);
		},
		/**
		 * Unregisters one or more objects.
		 * @param {...Object} 	obj 	The object or objects of which changes shouldn't be tracked any longer
		 * @return {undefined}
		 */
		unregister: function () {
			onoff("off", arguments, this._addToStack, this);
		},
		/**
		 * Unregisters all previously registered objects.
		 * @return {undefined}
		 */
		unregisterAll: function () {
			apply(this.unregister, this, this.objectRegistry.get());
		},
		/**
		 * Undoes the last action or the last set of actions in case 'magic' is true.
		 * @param {Boolean} 	[magic] 	If true, all actions that happened basically at the same time are undone together
		 * @return {undefined}
		 */
		undo: function (magic) {
			managerUndoRedo("undo", this, this.stack, magic);
		},

		/**
		 * Undoes all actions ever tracked by the undo manager
		 * @return {undefined}
		 */
		undoAll: function () {
			managerUndoRedo("undo", this, this.stack, false, true);
		},

		/**
		 * Redoes a previously undone action or a set of actions.
		 * @param {Boolean} 	[magic] 	If true, all actions that happened basically at the same time are redone together
		 * @return {undefined}
		 */
		redo: function (magic) {
			managerUndoRedo("redo", this, this.stack, magic);
		},

		/**
		 * Redoes all actions ever tracked by the undo manager
		 * @return {undefined}
		 */
		redoAll: function () {
			managerUndoRedo("redo", this, this.stack, false, true);
		},
		/**
		 * Checks if there's an action in the stack that can be undone / redone
		 * @param  {String} 	type 	Either "undo" or "redo"
		 * @return {Boolean} True if there is a set of actions which can be undone / redone
		 */
		isAvailable: function (type) {
			var s = this.stack, l = s.length;

			switch (type) {
				case "undo": return l > 0 && s.pointer > -1;
				case "redo": return l > 0 && s.pointer < l - 1;
				default: return false;
			}
		},
		/**
		 * Sets the stack-reference to the stack of another undoManager.
		 * @param  {UndoManager} 	undoManager 	The undoManager whose stack-reference is set to this stack
		 * @return {undefined}
		 */
		merge: function (undoManager) {
			// This sets the stack-reference to the stack of another 
			// undoManager so that the stack of this other undoManager 
			// is used by two different managers.
			// This enables to set up a main-undoManager and besides it
			// several others for special, exceptional cases (by using
			// instance-based custom UndoTypes). Models / collections 
			// which need this special treatment are only registered at 
			// those special undoManagers. Those special ones are then 
			// merged into the main-undoManager to write on its stack. 
			// That way it's easier to manage exceptional cases.
			var args = _.isArray(undoManager) ? undoManager : slice(arguments), manager;
			while (manager = args.pop()) {
				if (manager instanceof UndoManager &&
					manager.stack instanceof UndoStack) {
					// set the stack reference to our stack
					manager.stack = this.stack;
				}
			}
		},
		/**
		 * Add an UndoType to this specific UndoManager-instance.
		 * @param {String} type The event this UndoType is made for
		 * @param {Object} fns  An object of functions that are called to generate the data for an UndoAction or to process it. Must have the properties "undo", "redo" and "on". Can have the property "condition".
		 * @return {undefined}
		 */
		addUndoType: function (type, fns) {
			manipulateUndoType(0, type, fns, this.undoTypes);
		},
		/**
		 * Overwrite properties of an existing UndoType for this specific UndoManager-instance.
		 * @param  {String} type The event the UndoType is made for
		 * @param  {Object} fns  An object of functions that are called to generate the data for an UndoAction or to process it. It extends the existing object.
		 * @return {undefined}
		 */
		changeUndoType: function (type, fns) {
			manipulateUndoType(1, type, fns, this.undoTypes);
		},
		/**
		 * Remove one or more UndoTypes of this specific UndoManager-instance to fall back to the global UndoTypes.
		 * @param  {String|Array} type The event the UndoType that should be removed is made for. You can also pass an array of events.
		 * @return {undefined}
		 */
		removeUndoType: function (type) {
			manipulateUndoType(2, type, undefined, this.undoTypes);
		},

		/**
		 * Removes all actions from the stack.
		 * @return {undefined}
		 */
		clear: function() {
			this.stack.reset();
			this.stack.pointer = -1;
		}
	});

	_.extend(UndoManager, {
		/**
		 * Change the UndoManager's default attributes
		 * @param  {Object} defaultAttributes An object with the new default values.
		 * @return {undefined}
		 */
		defaults: function (defaultAttributes) {
			_.extend(UndoManager.prototype.defaults, defaultAttributes);
		},
		/**
		 * Add an UndoType to the global UndoTypes-object.
		 * @param  {String} type The event this UndoType is made for
		 * @param  {Object} fns  An object of functions that are called to generate the data for an UndoAction or to process it. Must have the properties "undo", "redo" and "on". Can have the property "condition".
		 * @return {undefined}
		 */
		"addUndoType": function (type, fns) {
			manipulateUndoType(0, type, fns, UndoTypes);
		},
		/**
		 * Overwrite properties of an existing UndoType in the global UndoTypes-object.
		 * @param  {String} type The event the UndoType is made for
		 * @param  {Object} fns  An object of functions that are called to generate the data for an UndoAction or to process it. It extends the existing object.
		 * @return {undefined}
		 */
		"changeUndoType": function (type, fns) {
			manipulateUndoType(1, type, fns, UndoTypes)
		},
		/**
		 * Remove one or more UndoTypes of this specific UndoManager-instance to fall back to the global UndoTypes.
		 * @param  {String|Array} type The event the UndoType that should be removed is made for. You can also pass an array of events.
		 * @return {undefined}
		 */
		"removeUndoType": function (type) {
			manipulateUndoType(2, type, undefined, UndoTypes);
		}
	})

	return Backbone.UndoManager = UndoManager;

});


/***/ }),

/***/ 316:
/***/ ((module, exports, __webpack_require__) => {

var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;//     Backbone.js 1.4.1

//     (c) 2010-2022 Jeremy Ashkenas and DocumentCloud
//     Backbone may be freely distributed under the MIT license.
//     For all details and documentation:
//     http://backbonejs.org

(function(factory) {

  // Establish the root object, `window` (`self`) in the browser, or `global` on the server.
  // We use `self` instead of `window` for `WebWorker` support.
  var root = typeof self == 'object' && self.self === self && self ||
            typeof __webpack_require__.g == 'object' && __webpack_require__.g.global === __webpack_require__.g && __webpack_require__.g;

  // Set up Backbone appropriately for the environment. Start with AMD.
  if (true) {
    !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(50), __webpack_require__(895), exports], __WEBPACK_AMD_DEFINE_RESULT__ = (function(_, $, exports) {
      // Export global even in AMD case in case this script is loaded with
      // others that may still expect a global Backbone.
      root.Backbone = factory(root, exports, _, $);
    }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__),
		__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));

  // Next for Node.js or CommonJS. jQuery may not be needed as a module.
  } else { var _, $; }

})(function(root, Backbone, _, $) {

  // Initial Setup
  // -------------

  // Save the previous value of the `Backbone` variable, so that it can be
  // restored later on, if `noConflict` is used.
  var previousBackbone = root.Backbone;

  // Create a local reference to a common array method we'll want to use later.
  var slice = Array.prototype.slice;

  // Current version of the library. Keep in sync with `package.json`.
  Backbone.VERSION = '1.4.1';

  // For Backbone's purposes, jQuery, Zepto, Ender, or My Library (kidding) owns
  // the `$` variable.
  Backbone.$ = $;

  // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable
  // to its previous owner. Returns a reference to this Backbone object.
  Backbone.noConflict = function() {
    root.Backbone = previousBackbone;
    return this;
  };

  // Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option
  // will fake `"PATCH"`, `"PUT"` and `"DELETE"` requests via the `_method` parameter and
  // set a `X-Http-Method-Override` header.
  Backbone.emulateHTTP = false;

  // Turn on `emulateJSON` to support legacy servers that can't deal with direct
  // `application/json` requests ... this will encode the body as
  // `application/x-www-form-urlencoded` instead and will send the model in a
  // form param named `model`.
  Backbone.emulateJSON = false;

  // Backbone.Events
  // ---------------

  // A module that can be mixed in to *any object* in order to provide it with
  // a custom event channel. You may bind a callback to an event with `on` or
  // remove with `off`; `trigger`-ing an event fires all callbacks in
  // succession.
  //
  //     var object = {};
  //     _.extend(object, Backbone.Events);
  //     object.on('expand', function(){ alert('expanded'); });
  //     object.trigger('expand');
  //
  var Events = Backbone.Events = {};

  // Regular expression used to split event strings.
  var eventSplitter = /\s+/;

  // A private global variable to share between listeners and listenees.
  var _listening;

  // Iterates over the standard `event, callback` (as well as the fancy multiple
  // space-separated events `"change blur", callback` and jQuery-style event
  // maps `{event: callback}`).
  var eventsApi = function(iteratee, events, name, callback, opts) {
    var i = 0, names;
    if (name && typeof name === 'object') {
      // Handle event maps.
      if (callback !== void 0 && 'context' in opts && opts.context === void 0) opts.context = callback;
      for (names = _.keys(name); i < names.length ; i++) {
        events = eventsApi(iteratee, events, names[i], name[names[i]], opts);
      }
    } else if (name && eventSplitter.test(name)) {
      // Handle space-separated event names by delegating them individually.
      for (names = name.split(eventSplitter); i < names.length; i++) {
        events = iteratee(events, names[i], callback, opts);
      }
    } else {
      // Finally, standard events.
      events = iteratee(events, name, callback, opts);
    }
    return events;
  };

  // Bind an event to a `callback` function. Passing `"all"` will bind
  // the callback to all events fired.
  Events.on = function(name, callback, context) {
    this._events = eventsApi(onApi, this._events || {}, name, callback, {
      context: context,
      ctx: this,
      listening: _listening
    });

    if (_listening) {
      var listeners = this._listeners || (this._listeners = {});
      listeners[_listening.id] = _listening;
      // Allow the listening to use a counter, instead of tracking
      // callbacks for library interop
      _listening.interop = false;
    }

    return this;
  };

  // Inversion-of-control versions of `on`. Tell *this* object to listen to
  // an event in another object... keeping track of what it's listening to
  // for easier unbinding later.
  Events.listenTo = function(obj, name, callback) {
    if (!obj) return this;
    var id = obj._listenId || (obj._listenId = _.uniqueId('l'));
    var listeningTo = this._listeningTo || (this._listeningTo = {});
    var listening = _listening = listeningTo[id];

    // This object is not listening to any other events on `obj` yet.
    // Setup the necessary references to track the listening callbacks.
    if (!listening) {
      this._listenId || (this._listenId = _.uniqueId('l'));
      listening = _listening = listeningTo[id] = new Listening(this, obj);
    }

    // Bind callbacks on obj.
    var error = tryCatchOn(obj, name, callback, this);
    _listening = void 0;

    if (error) throw error;
    // If the target obj is not Backbone.Events, track events manually.
    if (listening.interop) listening.on(name, callback);

    return this;
  };

  // The reducing API that adds a callback to the `events` object.
  var onApi = function(events, name, callback, options) {
    if (callback) {
      var handlers = events[name] || (events[name] = []);
      var context = options.context, ctx = options.ctx, listening = options.listening;
      if (listening) listening.count++;

      handlers.push({callback: callback, context: context, ctx: context || ctx, listening: listening});
    }
    return events;
  };

  // An try-catch guarded #on function, to prevent poisoning the global
  // `_listening` variable.
  var tryCatchOn = function(obj, name, callback, context) {
    try {
      obj.on(name, callback, context);
    } catch (e) {
      return e;
    }
  };

  // Remove one or many callbacks. If `context` is null, removes all
  // callbacks with that function. If `callback` is null, removes all
  // callbacks for the event. If `name` is null, removes all bound
  // callbacks for all events.
  Events.off = function(name, callback, context) {
    if (!this._events) return this;
    this._events = eventsApi(offApi, this._events, name, callback, {
      context: context,
      listeners: this._listeners
    });

    return this;
  };

  // Tell this object to stop listening to either specific events ... or
  // to every object it's currently listening to.
  Events.stopListening = function(obj, name, callback) {
    var listeningTo = this._listeningTo;
    if (!listeningTo) return this;

    var ids = obj ? [obj._listenId] : _.keys(listeningTo);
    for (var i = 0; i < ids.length; i++) {
      var listening = listeningTo[ids[i]];

      // If listening doesn't exist, this object is not currently
      // listening to obj. Break out early.
      if (!listening) break;

      listening.obj.off(name, callback, this);
      if (listening.interop) listening.off(name, callback);
    }
    if (_.isEmpty(listeningTo)) this._listeningTo = void 0;

    return this;
  };

  // The reducing API that removes a callback from the `events` object.
  var offApi = function(events, name, callback, options) {
    if (!events) return;

    var context = options.context, listeners = options.listeners;
    var i = 0, names;

    // Delete all event listeners and "drop" events.
    if (!name && !context && !callback) {
      for (names = _.keys(listeners); i < names.length; i++) {
        listeners[names[i]].cleanup();
      }
      return;
    }

    names = name ? [name] : _.keys(events);
    for (; i < names.length; i++) {
      name = names[i];
      var handlers = events[name];

      // Bail out if there are no events stored.
      if (!handlers) break;

      // Find any remaining events.
      var remaining = [];
      for (var j = 0; j < handlers.length; j++) {
        var handler = handlers[j];
        if (
          callback && callback !== handler.callback &&
            callback !== handler.callback._callback ||
              context && context !== handler.context
        ) {
          remaining.push(handler);
        } else {
          var listening = handler.listening;
          if (listening) listening.off(name, callback);
        }
      }

      // Replace events if there are any remaining.  Otherwise, clean up.
      if (remaining.length) {
        events[name] = remaining;
      } else {
        delete events[name];
      }
    }

    return events;
  };

  // Bind an event to only be triggered a single time. After the first time
  // the callback is invoked, its listener will be removed. If multiple events
  // are passed in using the space-separated syntax, the handler will fire
  // once for each event, not once for a combination of all events.
  Events.once = function(name, callback, context) {
    // Map the event into a `{event: once}` object.
    var events = eventsApi(onceMap, {}, name, callback, this.off.bind(this));
    if (typeof name === 'string' && context == null) callback = void 0;
    return this.on(events, callback, context);
  };

  // Inversion-of-control versions of `once`.
  Events.listenToOnce = function(obj, name, callback) {
    // Map the event into a `{event: once}` object.
    var events = eventsApi(onceMap, {}, name, callback, this.stopListening.bind(this, obj));
    return this.listenTo(obj, events);
  };

  // Reduces the event callbacks into a map of `{event: onceWrapper}`.
  // `offer` unbinds the `onceWrapper` after it has been called.
  var onceMap = function(map, name, callback, offer) {
    if (callback) {
      var once = map[name] = _.once(function() {
        offer(name, once);
        callback.apply(this, arguments);
      });
      once._callback = callback;
    }
    return map;
  };

  // Trigger one or many events, firing all bound callbacks. Callbacks are
  // passed the same arguments as `trigger` is, apart from the event name
  // (unless you're listening on `"all"`, which will cause your callback to
  // receive the true name of the event as the first argument).
  Events.trigger = function(name) {
    if (!this._events) return this;

    var length = Math.max(0, arguments.length - 1);
    var args = Array(length);
    for (var i = 0; i < length; i++) args[i] = arguments[i + 1];

    eventsApi(triggerApi, this._events, name, void 0, args);
    return this;
  };

  // Handles triggering the appropriate event callbacks.
  var triggerApi = function(objEvents, name, callback, args) {
    if (objEvents) {
      var events = objEvents[name];
      var allEvents = objEvents.all;
      if (events && allEvents) allEvents = allEvents.slice();
      if (events) triggerEvents(events, args);
      if (allEvents) triggerEvents(allEvents, [name].concat(args));
    }
    return objEvents;
  };

  // A difficult-to-believe, but optimized internal dispatch function for
  // triggering events. Tries to keep the usual cases speedy (most internal
  // Backbone events have 3 arguments).
  var triggerEvents = function(events, args) {
    var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2];
    switch (args.length) {
      case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx); return;
      case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1); return;
      case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2); return;
      case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2, a3); return;
      default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args); return;
    }
  };

  // A listening class that tracks and cleans up memory bindings
  // when all callbacks have been offed.
  var Listening = function(listener, obj) {
    this.id = listener._listenId;
    this.listener = listener;
    this.obj = obj;
    this.interop = true;
    this.count = 0;
    this._events = void 0;
  };

  Listening.prototype.on = Events.on;

  // Offs a callback (or several).
  // Uses an optimized counter if the listenee uses Backbone.Events.
  // Otherwise, falls back to manual tracking to support events
  // library interop.
  Listening.prototype.off = function(name, callback) {
    var cleanup;
    if (this.interop) {
      this._events = eventsApi(offApi, this._events, name, callback, {
        context: void 0,
        listeners: void 0
      });
      cleanup = !this._events;
    } else {
      this.count--;
      cleanup = this.count === 0;
    }
    if (cleanup) this.cleanup();
  };

  // Cleans up memory bindings between the listener and the listenee.
  Listening.prototype.cleanup = function() {
    delete this.listener._listeningTo[this.obj._listenId];
    if (!this.interop) delete this.obj._listeners[this.id];
  };

  // Aliases for backwards compatibility.
  Events.bind   = Events.on;
  Events.unbind = Events.off;

  // Allow the `Backbone` object to serve as a global event bus, for folks who
  // want global "pubsub" in a convenient place.
  _.extend(Backbone, Events);

  // Backbone.Model
  // --------------

  // Backbone **Models** are the basic data object in the framework --
  // frequently representing a row in a table in a database on your server.
  // A discrete chunk of data and a bunch of useful, related methods for
  // performing computations and transformations on that data.

  // Create a new model with the specified attributes. A client id (`cid`)
  // is automatically generated and assigned for you.
  var Model = Backbone.Model = function(attributes, options) {
    var attrs = attributes || {};
    options || (options = {});
    this.preinitialize.apply(this, arguments);
    this.cid = _.uniqueId(this.cidPrefix);
    this.attributes = {};
    if (options.collection) this.collection = options.collection;
    if (options.parse) attrs = this.parse(attrs, options) || {};
    var defaults = _.result(this, 'defaults');
    attrs = _.defaults(_.extend({}, defaults, attrs), defaults);
    this.set(attrs, options);
    this.changed = {};
    this.initialize.apply(this, arguments);
  };

  // Attach all inheritable methods to the Model prototype.
  _.extend(Model.prototype, Events, {

    // A hash of attributes whose current and previous value differ.
    changed: null,

    // The value returned during the last failed validation.
    validationError: null,

    // The default name for the JSON `id` attribute is `"id"`. MongoDB and
    // CouchDB users may want to set this to `"_id"`.
    idAttribute: 'id',

    // The prefix is used to create the client id which is used to identify models locally.
    // You may want to override this if you're experiencing name clashes with model ids.
    cidPrefix: 'c',

    // preinitialize is an empty function by default. You can override it with a function
    // or object.  preinitialize will run before any instantiation logic is run in the Model.
    preinitialize: function(){},

    // Initialize is an empty function by default. Override it with your own
    // initialization logic.
    initialize: function(){},

    // Return a copy of the model's `attributes` object.
    toJSON: function(options) {
      return _.clone(this.attributes);
    },

    // Proxy `Backbone.sync` by default -- but override this if you need
    // custom syncing semantics for *this* particular model.
    sync: function() {
      return Backbone.sync.apply(this, arguments);
    },

    // Get the value of an attribute.
    get: function(attr) {
      return this.attributes[attr];
    },

    // Get the HTML-escaped value of an attribute.
    escape: function(attr) {
      return _.escape(this.get(attr));
    },

    // Returns `true` if the attribute contains a value that is not null
    // or undefined.
    has: function(attr) {
      return this.get(attr) != null;
    },

    // Special-cased proxy to underscore's `_.matches` method.
    matches: function(attrs) {
      return !!_.iteratee(attrs, this)(this.attributes);
    },

    // Set a hash of model attributes on the object, firing `"change"`. This is
    // the core primitive operation of a model, updating the data and notifying
    // anyone who needs to know about the change in state. The heart of the beast.
    set: function(key, val, options) {
      if (key == null) return this;

      // Handle both `"key", value` and `{key: value}` -style arguments.
      var attrs;
      if (typeof key === 'object') {
        attrs = key;
        options = val;
      } else {
        (attrs = {})[key] = val;
      }

      options || (options = {});

      // Run validation.
      if (!this._validate(attrs, options)) return false;

      // Extract attributes and options.
      var unset      = options.unset;
      var silent     = options.silent;
      var changes    = [];
      var changing   = this._changing;
      this._changing = true;

      if (!changing) {
        this._previousAttributes = _.clone(this.attributes);
        this.changed = {};
      }

      var current = this.attributes;
      var changed = this.changed;
      var prev    = this._previousAttributes;

      // For each `set` attribute, update or delete the current value.
      for (var attr in attrs) {
        val = attrs[attr];
        if (!_.isEqual(current[attr], val)) changes.push(attr);
        if (!_.isEqual(prev[attr], val)) {
          changed[attr] = val;
        } else {
          delete changed[attr];
        }
        unset ? delete current[attr] : current[attr] = val;
      }

      // Update the `id`.
      if (this.idAttribute in attrs) {
        var prevId = this.id;
        this.id = this.get(this.idAttribute);
        this.trigger('changeId', this, prevId, options);
      }

      // Trigger all relevant attribute changes.
      if (!silent) {
        if (changes.length) this._pending = options;
        for (var i = 0; i < changes.length; i++) {
          this.trigger('change:' + changes[i], this, current[changes[i]], options);
        }
      }

      // You might be wondering why there's a `while` loop here. Changes can
      // be recursively nested within `"change"` events.
      if (changing) return this;
      if (!silent) {
        while (this._pending) {
          options = this._pending;
          this._pending = false;
          this.trigger('change', this, options);
        }
      }
      this._pending = false;
      this._changing = false;
      return this;
    },

    // Remove an attribute from the model, firing `"change"`. `unset` is a noop
    // if the attribute doesn't exist.
    unset: function(attr, options) {
      return this.set(attr, void 0, _.extend({}, options, {unset: true}));
    },

    // Clear all attributes on the model, firing `"change"`.
    clear: function(options) {
      var attrs = {};
      for (var key in this.attributes) attrs[key] = void 0;
      return this.set(attrs, _.extend({}, options, {unset: true}));
    },

    // Determine if the model has changed since the last `"change"` event.
    // If you specify an attribute name, determine if that attribute has changed.
    hasChanged: function(attr) {
      if (attr == null) return !_.isEmpty(this.changed);
      return _.has(this.changed, attr);
    },

    // Return an object containing all the attributes that have changed, or
    // false if there are no changed attributes. Useful for determining what
    // parts of a view need to be updated and/or what attributes need to be
    // persisted to the server. Unset attributes will be set to undefined.
    // You can also pass an attributes object to diff against the model,
    // determining if there *would be* a change.
    changedAttributes: function(diff) {
      if (!diff) return this.hasChanged() ? _.clone(this.changed) : false;
      var old = this._changing ? this._previousAttributes : this.attributes;
      var changed = {};
      var hasChanged;
      for (var attr in diff) {
        var val = diff[attr];
        if (_.isEqual(old[attr], val)) continue;
        changed[attr] = val;
        hasChanged = true;
      }
      return hasChanged ? changed : false;
    },

    // Get the previous value of an attribute, recorded at the time the last
    // `"change"` event was fired.
    previous: function(attr) {
      if (attr == null || !this._previousAttributes) return null;
      return this._previousAttributes[attr];
    },

    // Get all of the attributes of the model at the time of the previous
    // `"change"` event.
    previousAttributes: function() {
      return _.clone(this._previousAttributes);
    },

    // Fetch the model from the server, merging the response with the model's
    // local attributes. Any changed attributes will trigger a "change" event.
    fetch: function(options) {
      options = _.extend({parse: true}, options);
      var model = this;
      var success = options.success;
      options.success = function(resp) {
        var serverAttrs = options.parse ? model.parse(resp, options) : resp;
        if (!model.set(serverAttrs, options)) return false;
        if (success) success.call(options.context, model, resp, options);
        model.trigger('sync', model, resp, options);
      };
      wrapError(this, options);
      return this.sync('read', this, options);
    },

    // Set a hash of model attributes, and sync the model to the server.
    // If the server returns an attributes hash that differs, the model's
    // state will be `set` again.
    save: function(key, val, options) {
      // Handle both `"key", value` and `{key: value}` -style arguments.
      var attrs;
      if (key == null || typeof key === 'object') {
        attrs = key;
        options = val;
      } else {
        (attrs = {})[key] = val;
      }

      options = _.extend({validate: true, parse: true}, options);
      var wait = options.wait;

      // If we're not waiting and attributes exist, save acts as
      // `set(attr).save(null, opts)` with validation. Otherwise, check if
      // the model will be valid when the attributes, if any, are set.
      if (attrs && !wait) {
        if (!this.set(attrs, options)) return false;
      } else if (!this._validate(attrs, options)) {
        return false;
      }

      // After a successful server-side save, the client is (optionally)
      // updated with the server-side state.
      var model = this;
      var success = options.success;
      var attributes = this.attributes;
      options.success = function(resp) {
        // Ensure attributes are restored during synchronous saves.
        model.attributes = attributes;
        var serverAttrs = options.parse ? model.parse(resp, options) : resp;
        if (wait) serverAttrs = _.extend({}, attrs, serverAttrs);
        if (serverAttrs && !model.set(serverAttrs, options)) return false;
        if (success) success.call(options.context, model, resp, options);
        model.trigger('sync', model, resp, options);
      };
      wrapError(this, options);

      // Set temporary attributes if `{wait: true}` to properly find new ids.
      if (attrs && wait) this.attributes = _.extend({}, attributes, attrs);

      var method = this.isNew() ? 'create' : options.patch ? 'patch' : 'update';
      if (method === 'patch' && !options.attrs) options.attrs = attrs;
      var xhr = this.sync(method, this, options);

      // Restore attributes.
      this.attributes = attributes;

      return xhr;
    },

    // Destroy this model on the server if it was already persisted.
    // Optimistically removes the model from its collection, if it has one.
    // If `wait: true` is passed, waits for the server to respond before removal.
    destroy: function(options) {
      options = options ? _.clone(options) : {};
      var model = this;
      var success = options.success;
      var wait = options.wait;

      var destroy = function() {
        model.stopListening();
        model.trigger('destroy', model, model.collection, options);
      };

      options.success = function(resp) {
        if (wait) destroy();
        if (success) success.call(options.context, model, resp, options);
        if (!model.isNew()) model.trigger('sync', model, resp, options);
      };

      var xhr = false;
      if (this.isNew()) {
        _.defer(options.success);
      } else {
        wrapError(this, options);
        xhr = this.sync('delete', this, options);
      }
      if (!wait) destroy();
      return xhr;
    },

    // Default URL for the model's representation on the server -- if you're
    // using Backbone's restful methods, override this to change the endpoint
    // that will be called.
    url: function() {
      var base =
        _.result(this, 'urlRoot') ||
        _.result(this.collection, 'url') ||
        urlError();
      if (this.isNew()) return base;
      var id = this.get(this.idAttribute);
      return base.replace(/[^\/]$/, '$&/') + encodeURIComponent(id);
    },

    // **parse** converts a response into the hash of attributes to be `set` on
    // the model. The default implementation is just to pass the response along.
    parse: function(resp, options) {
      return resp;
    },

    // Create a new model with identical attributes to this one.
    clone: function() {
      return new this.constructor(this.attributes);
    },

    // A model is new if it has never been saved to the server, and lacks an id.
    isNew: function() {
      return !this.has(this.idAttribute);
    },

    // Check if the model is currently in a valid state.
    isValid: function(options) {
      return this._validate({}, _.extend({}, options, {validate: true}));
    },

    // Run validation against the next complete set of model attributes,
    // returning `true` if all is well. Otherwise, fire an `"invalid"` event.
    _validate: function(attrs, options) {
      if (!options.validate || !this.validate) return true;
      attrs = _.extend({}, this.attributes, attrs);
      var error = this.validationError = this.validate(attrs, options) || null;
      if (!error) return true;
      this.trigger('invalid', this, error, _.extend(options, {validationError: error}));
      return false;
    }

  });

  // Backbone.Collection
  // -------------------

  // If models tend to represent a single row of data, a Backbone Collection is
  // more analogous to a table full of data ... or a small slice or page of that
  // table, or a collection of rows that belong together for a particular reason
  // -- all of the messages in this particular folder, all of the documents
  // belonging to this particular author, and so on. Collections maintain
  // indexes of their models, both in order, and for lookup by `id`.

  // Create a new **Collection**, perhaps to contain a specific type of `model`.
  // If a `comparator` is specified, the Collection will maintain
  // its models in sort order, as they're added and removed.
  var Collection = Backbone.Collection = function(models, options) {
    options || (options = {});
    this.preinitialize.apply(this, arguments);
    if (options.model) this.model = options.model;
    if (options.comparator !== void 0) this.comparator = options.comparator;
    this._reset();
    this.initialize.apply(this, arguments);
    if (models) this.reset(models, _.extend({silent: true}, options));
  };

  // Default options for `Collection#set`.
  var setOptions = {add: true, remove: true, merge: true};
  var addOptions = {add: true, remove: false};

  // Splices `insert` into `array` at index `at`.
  var splice = function(array, insert, at) {
    at = Math.min(Math.max(at, 0), array.length);
    var tail = Array(array.length - at);
    var length = insert.length;
    var i;
    for (i = 0; i < tail.length; i++) tail[i] = array[i + at];
    for (i = 0; i < length; i++) array[i + at] = insert[i];
    for (i = 0; i < tail.length; i++) array[i + length + at] = tail[i];
  };

  // Define the Collection's inheritable methods.
  _.extend(Collection.prototype, Events, {

    // The default model for a collection is just a **Backbone.Model**.
    // This should be overridden in most cases.
    model: Model,


    // preinitialize is an empty function by default. You can override it with a function
    // or object.  preinitialize will run before any instantiation logic is run in the Collection.
    preinitialize: function(){},

    // Initialize is an empty function by default. Override it with your own
    // initialization logic.
    initialize: function(){},

    // The JSON representation of a Collection is an array of the
    // models' attributes.
    toJSON: function(options) {
      return this.map(function(model) { return model.toJSON(options); });
    },

    // Proxy `Backbone.sync` by default.
    sync: function() {
      return Backbone.sync.apply(this, arguments);
    },

    // Add a model, or list of models to the set. `models` may be Backbone
    // Models or raw JavaScript objects to be converted to Models, or any
    // combination of the two.
    add: function(models, options) {
      return this.set(models, _.extend({merge: false}, options, addOptions));
    },

    // Remove a model, or a list of models from the set.
    remove: function(models, options) {
      options = _.extend({}, options);
      var singular = !_.isArray(models);
      models = singular ? [models] : models.slice();
      var removed = this._removeModels(models, options);
      if (!options.silent && removed.length) {
        options.changes = {added: [], merged: [], removed: removed};
        this.trigger('update', this, options);
      }
      return singular ? removed[0] : removed;
    },

    // Update a collection by `set`-ing a new list of models, adding new ones,
    // removing models that are no longer present, and merging models that
    // already exist in the collection, as necessary. Similar to **Model#set**,
    // the core operation for updating the data contained by the collection.
    set: function(models, options) {
      if (models == null) return;

      options = _.extend({}, setOptions, options);
      if (options.parse && !this._isModel(models)) {
        models = this.parse(models, options) || [];
      }

      var singular = !_.isArray(models);
      models = singular ? [models] : models.slice();

      var at = options.at;
      if (at != null) at = +at;
      if (at > this.length) at = this.length;
      if (at < 0) at += this.length + 1;

      var set = [];
      var toAdd = [];
      var toMerge = [];
      var toRemove = [];
      var modelMap = {};

      var add = options.add;
      var merge = options.merge;
      var remove = options.remove;

      var sort = false;
      var sortable = this.comparator && at == null && options.sort !== false;
      var sortAttr = _.isString(this.comparator) ? this.comparator : null;

      // Turn bare objects into model references, and prevent invalid models
      // from being added.
      var model, i;
      for (i = 0; i < models.length; i++) {
        model = models[i];

        // If a duplicate is found, prevent it from being added and
        // optionally merge it into the existing model.
        var existing = this.get(model);
        if (existing) {
          if (merge && model !== existing) {
            var attrs = this._isModel(model) ? model.attributes : model;
            if (options.parse) attrs = existing.parse(attrs, options);
            existing.set(attrs, options);
            toMerge.push(existing);
            if (sortable && !sort) sort = existing.hasChanged(sortAttr);
          }
          if (!modelMap[existing.cid]) {
            modelMap[existing.cid] = true;
            set.push(existing);
          }
          models[i] = existing;

        // If this is a new, valid model, push it to the `toAdd` list.
        } else if (add) {
          model = models[i] = this._prepareModel(model, options);
          if (model) {
            toAdd.push(model);
            this._addReference(model, options);
            modelMap[model.cid] = true;
            set.push(model);
          }
        }
      }

      // Remove stale models.
      if (remove) {
        for (i = 0; i < this.length; i++) {
          model = this.models[i];
          if (!modelMap[model.cid]) toRemove.push(model);
        }
        if (toRemove.length) this._removeModels(toRemove, options);
      }

      // See if sorting is needed, update `length` and splice in new models.
      var orderChanged = false;
      var replace = !sortable && add && remove;
      if (set.length && replace) {
        orderChanged = this.length !== set.length || _.some(this.models, function(m, index) {
          return m !== set[index];
        });
        this.models.length = 0;
        splice(this.models, set, 0);
        this.length = this.models.length;
      } else if (toAdd.length) {
        if (sortable) sort = true;
        splice(this.models, toAdd, at == null ? this.length : at);
        this.length = this.models.length;
      }

      // Silently sort the collection if appropriate.
      if (sort) this.sort({silent: true});

      // Unless silenced, it's time to fire all appropriate add/sort/update events.
      if (!options.silent) {
        for (i = 0; i < toAdd.length; i++) {
          if (at != null) options.index = at + i;
          model = toAdd[i];
          model.trigger('add', model, this, options);
        }
        if (sort || orderChanged) this.trigger('sort', this, options);
        if (toAdd.length || toRemove.length || toMerge.length) {
          options.changes = {
            added: toAdd,
            removed: toRemove,
            merged: toMerge
          };
          this.trigger('update', this, options);
        }
      }

      // Return the added (or merged) model (or models).
      return singular ? models[0] : models;
    },

    // When you have more items than you want to add or remove individually,
    // you can reset the entire set with a new list of models, without firing
    // any granular `add` or `remove` events. Fires `reset` when finished.
    // Useful for bulk operations and optimizations.
    reset: function(models, options) {
      options = options ? _.clone(options) : {};
      for (var i = 0; i < this.models.length; i++) {
        this._removeReference(this.models[i], options);
      }
      options.previousModels = this.models;
      this._reset();
      models = this.add(models, _.extend({silent: true}, options));
      if (!options.silent) this.trigger('reset', this, options);
      return models;
    },

    // Add a model to the end of the collection.
    push: function(model, options) {
      return this.add(model, _.extend({at: this.length}, options));
    },

    // Remove a model from the end of the collection.
    pop: function(options) {
      var model = this.at(this.length - 1);
      return this.remove(model, options);
    },

    // Add a model to the beginning of the collection.
    unshift: function(model, options) {
      return this.add(model, _.extend({at: 0}, options));
    },

    // Remove a model from the beginning of the collection.
    shift: function(options) {
      var model = this.at(0);
      return this.remove(model, options);
    },

    // Slice out a sub-array of models from the collection.
    slice: function() {
      return slice.apply(this.models, arguments);
    },

    // Get a model from the set by id, cid, model object with id or cid
    // properties, or an attributes object that is transformed through modelId.
    get: function(obj) {
      if (obj == null) return void 0;
      return this._byId[obj] ||
        this._byId[this.modelId(this._isModel(obj) ? obj.attributes : obj, obj.idAttribute)] ||
        obj.cid && this._byId[obj.cid];
    },

    // Returns `true` if the model is in the collection.
    has: function(obj) {
      return this.get(obj) != null;
    },

    // Get the model at the given index.
    at: function(index) {
      if (index < 0) index += this.length;
      return this.models[index];
    },

    // Return models with matching attributes. Useful for simple cases of
    // `filter`.
    where: function(attrs, first) {
      return this[first ? 'find' : 'filter'](attrs);
    },

    // Return the first model with matching attributes. Useful for simple cases
    // of `find`.
    findWhere: function(attrs) {
      return this.where(attrs, true);
    },

    // Force the collection to re-sort itself. You don't need to call this under
    // normal circumstances, as the set will maintain sort order as each item
    // is added.
    sort: function(options) {
      var comparator = this.comparator;
      if (!comparator) throw new Error('Cannot sort a set without a comparator');
      options || (options = {});

      var length = comparator.length;
      if (_.isFunction(comparator)) comparator = comparator.bind(this);

      // Run sort based on type of `comparator`.
      if (length === 1 || _.isString(comparator)) {
        this.models = this.sortBy(comparator);
      } else {
        this.models.sort(comparator);
      }
      if (!options.silent) this.trigger('sort', this, options);
      return this;
    },

    // Pluck an attribute from each model in the collection.
    pluck: function(attr) {
      return this.map(attr + '');
    },

    // Fetch the default set of models for this collection, resetting the
    // collection when they arrive. If `reset: true` is passed, the response
    // data will be passed through the `reset` method instead of `set`.
    fetch: function(options) {
      options = _.extend({parse: true}, options);
      var success = options.success;
      var collection = this;
      options.success = function(resp) {
        var method = options.reset ? 'reset' : 'set';
        collection[method](resp, options);
        if (success) success.call(options.context, collection, resp, options);
        collection.trigger('sync', collection, resp, options);
      };
      wrapError(this, options);
      return this.sync('read', this, options);
    },

    // Create a new instance of a model in this collection. Add the model to the
    // collection immediately, unless `wait: true` is passed, in which case we
    // wait for the server to agree.
    create: function(model, options) {
      options = options ? _.clone(options) : {};
      var wait = options.wait;
      model = this._prepareModel(model, options);
      if (!model) return false;
      if (!wait) this.add(model, options);
      var collection = this;
      var success = options.success;
      options.success = function(m, resp, callbackOpts) {
        if (wait) collection.add(m, callbackOpts);
        if (success) success.call(callbackOpts.context, m, resp, callbackOpts);
      };
      model.save(null, options);
      return model;
    },

    // **parse** converts a response into a list of models to be added to the
    // collection. The default implementation is just to pass it through.
    parse: function(resp, options) {
      return resp;
    },

    // Create a new collection with an identical list of models as this one.
    clone: function() {
      return new this.constructor(this.models, {
        model: this.model,
        comparator: this.comparator
      });
    },

    // Define how to uniquely identify models in the collection.
    modelId: function(attrs, idAttribute) {
      return attrs[idAttribute || this.model.prototype.idAttribute || 'id'];
    },

    // Get an iterator of all models in this collection.
    values: function() {
      return new CollectionIterator(this, ITERATOR_VALUES);
    },

    // Get an iterator of all model IDs in this collection.
    keys: function() {
      return new CollectionIterator(this, ITERATOR_KEYS);
    },

    // Get an iterator of all [ID, model] tuples in this collection.
    entries: function() {
      return new CollectionIterator(this, ITERATOR_KEYSVALUES);
    },

    // Private method to reset all internal state. Called when the collection
    // is first initialized or reset.
    _reset: function() {
      this.length = 0;
      this.models = [];
      this._byId  = {};
    },

    // Prepare a hash of attributes (or other model) to be added to this
    // collection.
    _prepareModel: function(attrs, options) {
      if (this._isModel(attrs)) {
        if (!attrs.collection) attrs.collection = this;
        return attrs;
      }
      options = options ? _.clone(options) : {};
      options.collection = this;

      var model;
      if (this.model.prototype) {
        model = new this.model(attrs, options);
      } else {
        // ES class methods didn't have prototype
        model = this.model(attrs, options);
      }

      if (!model.validationError) return model;
      this.trigger('invalid', this, model.validationError, options);
      return false;
    },

    // Internal method called by both remove and set.
    _removeModels: function(models, options) {
      var removed = [];
      for (var i = 0; i < models.length; i++) {
        var model = this.get(models[i]);
        if (!model) continue;

        var index = this.indexOf(model);
        this.models.splice(index, 1);
        this.length--;

        // Remove references before triggering 'remove' event to prevent an
        // infinite loop. #3693
        delete this._byId[model.cid];
        var id = this.modelId(model.attributes, model.idAttribute);
        if (id != null) delete this._byId[id];

        if (!options.silent) {
          options.index = index;
          model.trigger('remove', model, this, options);
        }

        removed.push(model);
        this._removeReference(model, options);
      }
      return removed;
    },

    // Method for checking whether an object should be considered a model for
    // the purposes of adding to the collection.
    _isModel: function(model) {
      return model instanceof Model;
    },

    // Internal method to create a model's ties to a collection.
    _addReference: function(model, options) {
      this._byId[model.cid] = model;
      var id = this.modelId(model.attributes, model.idAttribute);
      if (id != null) this._byId[id] = model;
      model.on('all', this._onModelEvent, this);
    },

    // Internal method to sever a model's ties to a collection.
    _removeReference: function(model, options) {
      delete this._byId[model.cid];
      var id = this.modelId(model.attributes, model.idAttribute);
      if (id != null) delete this._byId[id];
      if (this === model.collection) delete model.collection;
      model.off('all', this._onModelEvent, this);
    },

    // Internal method called every time a model in the set fires an event.
    // Sets need to update their indexes when models change ids. All other
    // events simply proxy through. "add" and "remove" events that originate
    // in other collections are ignored.
    _onModelEvent: function(event, model, collection, options) {
      if (model) {
        if ((event === 'add' || event === 'remove') && collection !== this) return;
        if (event === 'destroy') this.remove(model, options);
        if (event === 'changeId') {
          var prevId = this.modelId(model.previousAttributes(), model.idAttribute);
          var id = this.modelId(model.attributes, model.idAttribute);
          if (prevId != null) delete this._byId[prevId];
          if (id != null) this._byId[id] = model;
        }
      }
      this.trigger.apply(this, arguments);
    }

  });

  // Defining an @@iterator method implements JavaScript's Iterable protocol.
  // In modern ES2015 browsers, this value is found at Symbol.iterator.
  /* global Symbol */
  var $$iterator = typeof Symbol === 'function' && Symbol.iterator;
  if ($$iterator) {
    Collection.prototype[$$iterator] = Collection.prototype.values;
  }

  // CollectionIterator
  // ------------------

  // A CollectionIterator implements JavaScript's Iterator protocol, allowing the
  // use of `for of` loops in modern browsers and interoperation between
  // Backbone.Collection and other JavaScript functions and third-party libraries
  // which can operate on Iterables.
  var CollectionIterator = function(collection, kind) {
    this._collection = collection;
    this._kind = kind;
    this._index = 0;
  };

  // This "enum" defines the three possible kinds of values which can be emitted
  // by a CollectionIterator that correspond to the values(), keys() and entries()
  // methods on Collection, respectively.
  var ITERATOR_VALUES = 1;
  var ITERATOR_KEYS = 2;
  var ITERATOR_KEYSVALUES = 3;

  // All Iterators should themselves be Iterable.
  if ($$iterator) {
    CollectionIterator.prototype[$$iterator] = function() {
      return this;
    };
  }

  CollectionIterator.prototype.next = function() {
    if (this._collection) {

      // Only continue iterating if the iterated collection is long enough.
      if (this._index < this._collection.length) {
        var model = this._collection.at(this._index);
        this._index++;

        // Construct a value depending on what kind of values should be iterated.
        var value;
        if (this._kind === ITERATOR_VALUES) {
          value = model;
        } else {
          var id = this._collection.modelId(model.attributes, model.idAttribute);
          if (this._kind === ITERATOR_KEYS) {
            value = id;
          } else { // ITERATOR_KEYSVALUES
            value = [id, model];
          }
        }
        return {value: value, done: false};
      }

      // Once exhausted, remove the reference to the collection so future
      // calls to the next method always return done.
      this._collection = void 0;
    }

    return {value: void 0, done: true};
  };

  // Backbone.View
  // -------------

  // Backbone Views are almost more convention than they are actual code. A View
  // is simply a JavaScript object that represents a logical chunk of UI in the
  // DOM. This might be a single item, an entire list, a sidebar or panel, or
  // even the surrounding frame which wraps your whole app. Defining a chunk of
  // UI as a **View** allows you to define your DOM events declaratively, without
  // having to worry about render order ... and makes it easy for the view to
  // react to specific changes in the state of your models.

  // Creating a Backbone.View creates its initial element outside of the DOM,
  // if an existing element is not provided...
  var View = Backbone.View = function(options) {
    this.cid = _.uniqueId('view');
    this.preinitialize.apply(this, arguments);
    _.extend(this, _.pick(options, viewOptions));
    this._ensureElement();
    this.initialize.apply(this, arguments);
  };

  // Cached regex to split keys for `delegate`.
  var delegateEventSplitter = /^(\S+)\s*(.*)$/;

  // List of view options to be set as properties.
  var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events'];

  // Set up all inheritable **Backbone.View** properties and methods.
  _.extend(View.prototype, Events, {

    // The default `tagName` of a View's element is `"div"`.
    tagName: 'div',

    // jQuery delegate for element lookup, scoped to DOM elements within the
    // current view. This should be preferred to global lookups where possible.
    $: function(selector) {
      return this.$el.find(selector);
    },

    // preinitialize is an empty function by default. You can override it with a function
    // or object.  preinitialize will run before any instantiation logic is run in the View
    preinitialize: function(){},

    // Initialize is an empty function by default. Override it with your own
    // initialization logic.
    initialize: function(){},

    // **render** is the core function that your view should override, in order
    // to populate its element (`this.el`), with the appropriate HTML. The
    // convention is for **render** to always return `this`.
    render: function() {
      return this;
    },

    // Remove this view by taking the element out of the DOM, and removing any
    // applicable Backbone.Events listeners.
    remove: function() {
      this._removeElement();
      this.stopListening();
      return this;
    },

    // Remove this view's element from the document and all event listeners
    // attached to it. Exposed for subclasses using an alternative DOM
    // manipulation API.
    _removeElement: function() {
      this.$el.remove();
    },

    // Change the view's element (`this.el` property) and re-delegate the
    // view's events on the new element.
    setElement: function(element) {
      this.undelegateEvents();
      this._setElement(element);
      this.delegateEvents();
      return this;
    },

    // Creates the `this.el` and `this.$el` references for this view using the
    // given `el`. `el` can be a CSS selector or an HTML string, a jQuery
    // context or an element. Subclasses can override this to utilize an
    // alternative DOM manipulation API and are only required to set the
    // `this.el` property.
    _setElement: function(el) {
      this.$el = el instanceof Backbone.$ ? el : Backbone.$(el);
      this.el = this.$el[0];
    },

    // Set callbacks, where `this.events` is a hash of
    //
    // *{"event selector": "callback"}*
    //
    //     {
    //       'mousedown .title':  'edit',
    //       'click .button':     'save',
    //       'click .open':       function(e) { ... }
    //     }
    //
    // pairs. Callbacks will be bound to the view, with `this` set properly.
    // Uses event delegation for efficiency.
    // Omitting the selector binds the event to `this.el`.
    delegateEvents: function(events) {
      events || (events = _.result(this, 'events'));
      if (!events) return this;
      this.undelegateEvents();
      for (var key in events) {
        var method = events[key];
        if (!_.isFunction(method)) method = this[method];
        if (!method) continue;
        var match = key.match(delegateEventSplitter);
        this.delegate(match[1], match[2], method.bind(this));
      }
      return this;
    },

    // Add a single event listener to the view's element (or a child element
    // using `selector`). This only works for delegate-able events: not `focus`,
    // `blur`, and not `change`, `submit`, and `reset` in Internet Explorer.
    delegate: function(eventName, selector, listener) {
      this.$el.on(eventName + '.delegateEvents' + this.cid, selector, listener);
      return this;
    },

    // Clears all callbacks previously bound to the view by `delegateEvents`.
    // You usually don't need to use this, but may wish to if you have multiple
    // Backbone views attached to the same DOM element.
    undelegateEvents: function() {
      if (this.$el) this.$el.off('.delegateEvents' + this.cid);
      return this;
    },

    // A finer-grained `undelegateEvents` for removing a single delegated event.
    // `selector` and `listener` are both optional.
    undelegate: function(eventName, selector, listener) {
      this.$el.off(eventName + '.delegateEvents' + this.cid, selector, listener);
      return this;
    },

    // Produces a DOM element to be assigned to your view. Exposed for
    // subclasses using an alternative DOM manipulation API.
    _createElement: function(tagName) {
      return document.createElement(tagName);
    },

    // Ensure that the View has a DOM element to render into.
    // If `this.el` is a string, pass it through `$()`, take the first
    // matching element, and re-assign it to `el`. Otherwise, create
    // an element from the `id`, `className` and `tagName` properties.
    _ensureElement: function() {
      if (!this.el) {
        var attrs = _.extend({}, _.result(this, 'attributes'));
        if (this.id) attrs.id = _.result(this, 'id');
        if (this.className) attrs['class'] = _.result(this, 'className');
        this.setElement(this._createElement(_.result(this, 'tagName')));
        this._setAttributes(attrs);
      } else {
        this.setElement(_.result(this, 'el'));
      }
    },

    // Set attributes from a hash on this view's element.  Exposed for
    // subclasses using an alternative DOM manipulation API.
    _setAttributes: function(attributes) {
      this.$el.attr(attributes);
    }

  });

  // Proxy Backbone class methods to Underscore functions, wrapping the model's
  // `attributes` object or collection's `models` array behind the scenes.
  //
  // collection.filter(function(model) { return model.get('age') > 10 });
  // collection.each(this.addView);
  //
  // `Function#apply` can be slow so we use the method's arg count, if we know it.
  var addMethod = function(base, length, method, attribute) {
    switch (length) {
      case 1: return function() {
        return base[method](this[attribute]);
      };
      case 2: return function(value) {
        return base[method](this[attribute], value);
      };
      case 3: return function(iteratee, context) {
        return base[method](this[attribute], cb(iteratee, this), context);
      };
      case 4: return function(iteratee, defaultVal, context) {
        return base[method](this[attribute], cb(iteratee, this), defaultVal, context);
      };
      default: return function() {
        var args = slice.call(arguments);
        args.unshift(this[attribute]);
        return base[method].apply(base, args);
      };
    }
  };

  var addUnderscoreMethods = function(Class, base, methods, attribute) {
    _.each(methods, function(length, method) {
      if (base[method]) Class.prototype[method] = addMethod(base, length, method, attribute);
    });
  };

  // Support `collection.sortBy('attr')` and `collection.findWhere({id: 1})`.
  var cb = function(iteratee, instance) {
    if (_.isFunction(iteratee)) return iteratee;
    if (_.isObject(iteratee) && !instance._isModel(iteratee)) return modelMatcher(iteratee);
    if (_.isString(iteratee)) return function(model) { return model.get(iteratee); };
    return iteratee;
  };
  var modelMatcher = function(attrs) {
    var matcher = _.matches(attrs);
    return function(model) {
      return matcher(model.attributes);
    };
  };

  // Underscore methods that we want to implement on the Collection.
  // 90% of the core usefulness of Backbone Collections is actually implemented
  // right here:
  var collectionMethods = {forEach: 3, each: 3, map: 3, collect: 3, reduce: 0,
    foldl: 0, inject: 0, reduceRight: 0, foldr: 0, find: 3, detect: 3, filter: 3,
    select: 3, reject: 3, every: 3, all: 3, some: 3, any: 3, include: 3, includes: 3,
    contains: 3, invoke: 0, max: 3, min: 3, toArray: 1, size: 1, first: 3,
    head: 3, take: 3, initial: 3, rest: 3, tail: 3, drop: 3, last: 3,
    without: 0, difference: 0, indexOf: 3, shuffle: 1, lastIndexOf: 3,
    isEmpty: 1, chain: 1, sample: 3, partition: 3, groupBy: 3, countBy: 3,
    sortBy: 3, indexBy: 3, findIndex: 3, findLastIndex: 3};


  // Underscore methods that we want to implement on the Model, mapped to the
  // number of arguments they take.
  var modelMethods = {keys: 1, values: 1, pairs: 1, invert: 1, pick: 0,
    omit: 0, chain: 1, isEmpty: 1};

  // Mix in each Underscore method as a proxy to `Collection#models`.

  _.each([
    [Collection, collectionMethods, 'models'],
    [Model, modelMethods, 'attributes']
  ], function(config) {
    var Base = config[0],
        methods = config[1],
        attribute = config[2];

    Base.mixin = function(obj) {
      var mappings = _.reduce(_.functions(obj), function(memo, name) {
        memo[name] = 0;
        return memo;
      }, {});
      addUnderscoreMethods(Base, obj, mappings, attribute);
    };

    addUnderscoreMethods(Base, _, methods, attribute);
  });

  // Backbone.sync
  // -------------

  // Override this function to change the manner in which Backbone persists
  // models to the server. You will be passed the type of request, and the
  // model in question. By default, makes a RESTful Ajax request
  // to the model's `url()`. Some possible customizations could be:
  //
  // * Use `setTimeout` to batch rapid-fire updates into a single request.
  // * Send up the models as XML instead of JSON.
  // * Persist models via WebSockets instead of Ajax.
  //
  // Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests
  // as `POST`, with a `_method` parameter containing the true HTTP method,
  // as well as all requests with the body as `application/x-www-form-urlencoded`
  // instead of `application/json` with the model in a param named `model`.
  // Useful when interfacing with server-side languages like **PHP** that make
  // it difficult to read the body of `PUT` requests.
  Backbone.sync = function(method, model, options) {
    var type = methodMap[method];

    // Default options, unless specified.
    _.defaults(options || (options = {}), {
      emulateHTTP: Backbone.emulateHTTP,
      emulateJSON: Backbone.emulateJSON
    });

    // Default JSON-request options.
    var params = {type: type, dataType: 'json'};

    // Ensure that we have a URL.
    if (!options.url) {
      params.url = _.result(model, 'url') || urlError();
    }

    // Ensure that we have the appropriate request data.
    if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) {
      params.contentType = 'application/json';
      params.data = JSON.stringify(options.attrs || model.toJSON(options));
    }

    // For older servers, emulate JSON by encoding the request into an HTML-form.
    if (options.emulateJSON) {
      params.contentType = 'application/x-www-form-urlencoded';
      params.data = params.data ? {model: params.data} : {};
    }

    // For older servers, emulate HTTP by mimicking the HTTP method with `_method`
    // And an `X-HTTP-Method-Override` header.
    if (options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH')) {
      params.type = 'POST';
      if (options.emulateJSON) params.data._method = type;
      var beforeSend = options.beforeSend;
      options.beforeSend = function(xhr) {
        xhr.setRequestHeader('X-HTTP-Method-Override', type);
        if (beforeSend) return beforeSend.apply(this, arguments);
      };
    }

    // Don't process data on a non-GET request.
    if (params.type !== 'GET' && !options.emulateJSON) {
      params.processData = false;
    }

    // Pass along `textStatus` and `errorThrown` from jQuery.
    var error = options.error;
    options.error = function(xhr, textStatus, errorThrown) {
      options.textStatus = textStatus;
      options.errorThrown = errorThrown;
      if (error) error.call(options.context, xhr, textStatus, errorThrown);
    };

    // Make the request, allowing the user to override any Ajax options.
    var xhr = options.xhr = Backbone.ajax(_.extend(params, options));
    model.trigger('request', model, xhr, options);
    return xhr;
  };

  // Map from CRUD to HTTP for our default `Backbone.sync` implementation.
  var methodMap = {
    'create': 'POST',
    'update': 'PUT',
    'patch': 'PATCH',
    'delete': 'DELETE',
    'read': 'GET'
  };

  // Set the default implementation of `Backbone.ajax` to proxy through to `$`.
  // Override this if you'd like to use a different library.
  Backbone.ajax = function() {
    return Backbone.$.ajax.apply(Backbone.$, arguments);
  };

  // Backbone.Router
  // ---------------

  // Routers map faux-URLs to actions, and fire events when routes are
  // matched. Creating a new one sets its `routes` hash, if not set statically.
  var Router = Backbone.Router = function(options) {
    options || (options = {});
    this.preinitialize.apply(this, arguments);
    if (options.routes) this.routes = options.routes;
    this._bindRoutes();
    this.initialize.apply(this, arguments);
  };

  // Cached regular expressions for matching named param parts and splatted
  // parts of route strings.
  var optionalParam = /\((.*?)\)/g;
  var namedParam    = /(\(\?)?:\w+/g;
  var splatParam    = /\*\w+/g;
  var escapeRegExp  = /[\-{}\[\]+?.,\\\^$|#\s]/g;

  // Set up all inheritable **Backbone.Router** properties and methods.
  _.extend(Router.prototype, Events, {

    // preinitialize is an empty function by default. You can override it with a function
    // or object.  preinitialize will run before any instantiation logic is run in the Router.
    preinitialize: function(){},

    // Initialize is an empty function by default. Override it with your own
    // initialization logic.
    initialize: function(){},

    // Manually bind a single named route to a callback. For example:
    //
    //     this.route('search/:query/p:num', 'search', function(query, num) {
    //       ...
    //     });
    //
    route: function(route, name, callback) {
      if (!_.isRegExp(route)) route = this._routeToRegExp(route);
      if (_.isFunction(name)) {
        callback = name;
        name = '';
      }
      if (!callback) callback = this[name];
      var router = this;
      Backbone.history.route(route, function(fragment) {
        var args = router._extractParameters(route, fragment);
        if (router.execute(callback, args, name) !== false) {
          router.trigger.apply(router, ['route:' + name].concat(args));
          router.trigger('route', name, args);
          Backbone.history.trigger('route', router, name, args);
        }
      });
      return this;
    },

    // Execute a route handler with the provided parameters.  This is an
    // excellent place to do pre-route setup or post-route cleanup.
    execute: function(callback, args, name) {
      if (callback) callback.apply(this, args);
    },

    // Simple proxy to `Backbone.history` to save a fragment into the history.
    navigate: function(fragment, options) {
      Backbone.history.navigate(fragment, options);
      return this;
    },

    // Bind all defined routes to `Backbone.history`. We have to reverse the
    // order of the routes here to support behavior where the most general
    // routes can be defined at the bottom of the route map.
    _bindRoutes: function() {
      if (!this.routes) return;
      this.routes = _.result(this, 'routes');
      var route, routes = _.keys(this.routes);
      while ((route = routes.pop()) != null) {
        this.route(route, this.routes[route]);
      }
    },

    // Convert a route string into a regular expression, suitable for matching
    // against the current location hash.
    _routeToRegExp: function(route) {
      route = route.replace(escapeRegExp, '\\$&')
      .replace(optionalParam, '(?:$1)?')
      .replace(namedParam, function(match, optional) {
        return optional ? match : '([^/?]+)';
      })
      .replace(splatParam, '([^?]*?)');
      return new RegExp('^' + route + '(?:\\?([\\s\\S]*))?$');
    },

    // Given a route, and a URL fragment that it matches, return the array of
    // extracted decoded parameters. Empty or unmatched parameters will be
    // treated as `null` to normalize cross-browser behavior.
    _extractParameters: function(route, fragment) {
      var params = route.exec(fragment).slice(1);
      return _.map(params, function(param, i) {
        // Don't decode the search params.
        if (i === params.length - 1) return param || null;
        return param ? decodeURIComponent(param) : null;
      });
    }

  });

  // Backbone.History
  // ----------------

  // Handles cross-browser history management, based on either
  // [pushState](http://diveintohtml5.info/history.html) and real URLs, or
  // [onhashchange](https://developer.mozilla.org/en-US/docs/DOM/window.onhashchange)
  // and URL fragments. If the browser supports neither (old IE, natch),
  // falls back to polling.
  var History = Backbone.History = function() {
    this.handlers = [];
    this.checkUrl = this.checkUrl.bind(this);

    // Ensure that `History` can be used outside of the browser.
    if (typeof window !== 'undefined') {
      this.location = window.location;
      this.history = window.history;
    }
  };

  // Cached regex for stripping a leading hash/slash and trailing space.
  var routeStripper = /^[#\/]|\s+$/g;

  // Cached regex for stripping leading and trailing slashes.
  var rootStripper = /^\/+|\/+$/g;

  // Cached regex for stripping urls of hash.
  var pathStripper = /#.*$/;

  // Has the history handling already been started?
  History.started = false;

  // Set up all inheritable **Backbone.History** properties and methods.
  _.extend(History.prototype, Events, {

    // The default interval to poll for hash changes, if necessary, is
    // twenty times a second.
    interval: 50,

    // Are we at the app root?
    atRoot: function() {
      var path = this.location.pathname.replace(/[^\/]$/, '$&/');
      return path === this.root && !this.getSearch();
    },

    // Does the pathname match the root?
    matchRoot: function() {
      var path = this.decodeFragment(this.location.pathname);
      var rootPath = path.slice(0, this.root.length - 1) + '/';
      return rootPath === this.root;
    },

    // Unicode characters in `location.pathname` are percent encoded so they're
    // decoded for comparison. `%25` should not be decoded since it may be part
    // of an encoded parameter.
    decodeFragment: function(fragment) {
      return decodeURI(fragment.replace(/%25/g, '%2525'));
    },

    // In IE6, the hash fragment and search params are incorrect if the
    // fragment contains `?`.
    getSearch: function() {
      var match = this.location.href.replace(/#.*/, '').match(/\?.+/);
      return match ? match[0] : '';
    },

    // Gets the true hash value. Cannot use location.hash directly due to bug
    // in Firefox where location.hash will always be decoded.
    getHash: function(window) {
      var match = (window || this).location.href.match(/#(.*)$/);
      return match ? match[1] : '';
    },

    // Get the pathname and search params, without the root.
    getPath: function() {
      var path = this.decodeFragment(
        this.location.pathname + this.getSearch()
      ).slice(this.root.length - 1);
      return path.charAt(0) === '/' ? path.slice(1) : path;
    },

    // Get the cross-browser normalized URL fragment from the path or hash.
    getFragment: function(fragment) {
      if (fragment == null) {
        if (this._usePushState || !this._wantsHashChange) {
          fragment = this.getPath();
        } else {
          fragment = this.getHash();
        }
      }
      return fragment.replace(routeStripper, '');
    },

    // Start the hash change handling, returning `true` if the current URL matches
    // an existing route, and `false` otherwise.
    start: function(options) {
      if (History.started) throw new Error('Backbone.history has already been started');
      History.started = true;

      // Figure out the initial configuration. Do we need an iframe?
      // Is pushState desired ... is it available?
      this.options          = _.extend({root: '/'}, this.options, options);
      this.root             = this.options.root;
      this._wantsHashChange = this.options.hashChange !== false;
      this._hasHashChange   = 'onhashchange' in window && (document.documentMode === void 0 || document.documentMode > 7);
      this._useHashChange   = this._wantsHashChange && this._hasHashChange;
      this._wantsPushState  = !!this.options.pushState;
      this._hasPushState    = !!(this.history && this.history.pushState);
      this._usePushState    = this._wantsPushState && this._hasPushState;
      this.fragment         = this.getFragment();

      // Normalize root to always include a leading and trailing slash.
      this.root = ('/' + this.root + '/').replace(rootStripper, '/');

      // Transition from hashChange to pushState or vice versa if both are
      // requested.
      if (this._wantsHashChange && this._wantsPushState) {

        // If we've started off with a route from a `pushState`-enabled
        // browser, but we're currently in a browser that doesn't support it...
        if (!this._hasPushState && !this.atRoot()) {
          var rootPath = this.root.slice(0, -1) || '/';
          this.location.replace(rootPath + '#' + this.getPath());
          // Return immediately as browser will do redirect to new url
          return true;

        // Or if we've started out with a hash-based route, but we're currently
        // in a browser where it could be `pushState`-based instead...
        } else if (this._hasPushState && this.atRoot()) {
          this.navigate(this.getHash(), {replace: true});
        }

      }

      // Proxy an iframe to handle location events if the browser doesn't
      // support the `hashchange` event, HTML5 history, or the user wants
      // `hashChange` but not `pushState`.
      if (!this._hasHashChange && this._wantsHashChange && !this._usePushState) {
        this.iframe = document.createElement('iframe');
        this.iframe.src = 'javascript:0';
        this.iframe.style.display = 'none';
        this.iframe.tabIndex = -1;
        var body = document.body;
        // Using `appendChild` will throw on IE < 9 if the document is not ready.
        var iWindow = body.insertBefore(this.iframe, body.firstChild).contentWindow;
        iWindow.document.open();
        iWindow.document.close();
        iWindow.location.hash = '#' + this.fragment;
      }

      // Add a cross-platform `addEventListener` shim for older browsers.
      var addEventListener = window.addEventListener || function(eventName, listener) {
        return attachEvent('on' + eventName, listener);
      };

      // Depending on whether we're using pushState or hashes, and whether
      // 'onhashchange' is supported, determine how we check the URL state.
      if (this._usePushState) {
        addEventListener('popstate', this.checkUrl, false);
      } else if (this._useHashChange && !this.iframe) {
        addEventListener('hashchange', this.checkUrl, false);
      } else if (this._wantsHashChange) {
        this._checkUrlInterval = setInterval(this.checkUrl, this.interval);
      }

      if (!this.options.silent) return this.loadUrl();
    },

    // Disable Backbone.history, perhaps temporarily. Not useful in a real app,
    // but possibly useful for unit testing Routers.
    stop: function() {
      // Add a cross-platform `removeEventListener` shim for older browsers.
      var removeEventListener = window.removeEventListener || function(eventName, listener) {
        return detachEvent('on' + eventName, listener);
      };

      // Remove window listeners.
      if (this._usePushState) {
        removeEventListener('popstate', this.checkUrl, false);
      } else if (this._useHashChange && !this.iframe) {
        removeEventListener('hashchange', this.checkUrl, false);
      }

      // Clean up the iframe if necessary.
      if (this.iframe) {
        document.body.removeChild(this.iframe);
        this.iframe = null;
      }

      // Some environments will throw when clearing an undefined interval.
      if (this._checkUrlInterval) clearInterval(this._checkUrlInterval);
      History.started = false;
    },

    // Add a route to be tested when the fragment changes. Routes added later
    // may override previous routes.
    route: function(route, callback) {
      this.handlers.unshift({route: route, callback: callback});
    },

    // Checks the current URL to see if it has changed, and if it has,
    // calls `loadUrl`, normalizing across the hidden iframe.
    checkUrl: function(e) {
      var current = this.getFragment();

      // If the user pressed the back button, the iframe's hash will have
      // changed and we should use that for comparison.
      if (current === this.fragment && this.iframe) {
        current = this.getHash(this.iframe.contentWindow);
      }

      if (current === this.fragment) return false;
      if (this.iframe) this.navigate(current);
      this.loadUrl();
    },

    // Attempt to load the current URL fragment. If a route succeeds with a
    // match, returns `true`. If no defined routes matches the fragment,
    // returns `false`.
    loadUrl: function(fragment) {
      // If the root doesn't match, no routes can match either.
      if (!this.matchRoot()) return false;
      fragment = this.fragment = this.getFragment(fragment);
      return _.some(this.handlers, function(handler) {
        if (handler.route.test(fragment)) {
          handler.callback(fragment);
          return true;
        }
      });
    },

    // Save a fragment into the hash history, or replace the URL state if the
    // 'replace' option is passed. You are responsible for properly URL-encoding
    // the fragment in advance.
    //
    // The options object can contain `trigger: true` if you wish to have the
    // route callback be fired (not usually desirable), or `replace: true`, if
    // you wish to modify the current URL without adding an entry to the history.
    navigate: function(fragment, options) {
      if (!History.started) return false;
      if (!options || options === true) options = {trigger: !!options};

      // Normalize the fragment.
      fragment = this.getFragment(fragment || '');

      // Don't include a trailing slash on the root.
      var rootPath = this.root;
      if (fragment === '' || fragment.charAt(0) === '?') {
        rootPath = rootPath.slice(0, -1) || '/';
      }
      var url = rootPath + fragment;

      // Strip the fragment of the query and hash for matching.
      fragment = fragment.replace(pathStripper, '');

      // Decode for matching.
      var decodedFragment = this.decodeFragment(fragment);

      if (this.fragment === decodedFragment) return;
      this.fragment = decodedFragment;

      // If pushState is available, we use it to set the fragment as a real URL.
      if (this._usePushState) {
        this.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, url);

      // If hash changes haven't been explicitly disabled, update the hash
      // fragment to store history.
      } else if (this._wantsHashChange) {
        this._updateHash(this.location, fragment, options.replace);
        if (this.iframe && fragment !== this.getHash(this.iframe.contentWindow)) {
          var iWindow = this.iframe.contentWindow;

          // Opening and closing the iframe tricks IE7 and earlier to push a
          // history entry on hash-tag change.  When replace is true, we don't
          // want this.
          if (!options.replace) {
            iWindow.document.open();
            iWindow.document.close();
          }

          this._updateHash(iWindow.location, fragment, options.replace);
        }

      // If you've told us that you explicitly don't want fallback hashchange-
      // based history, then `navigate` becomes a page refresh.
      } else {
        return this.location.assign(url);
      }
      if (options.trigger) return this.loadUrl(fragment);
    },

    // Update the hash location, either replacing the current entry, or adding
    // a new one to the browser history.
    _updateHash: function(location, fragment, replace) {
      if (replace) {
        var href = location.href.replace(/(javascript:|#).*$/, '');
        location.replace(href + '#' + fragment);
      } else {
        // Some browsers require that `hash` contains a leading #.
        location.hash = '#' + fragment;
      }
    }

  });

  // Create the default Backbone.history.
  Backbone.history = new History;

  // Helpers
  // -------

  // Helper function to correctly set up the prototype chain for subclasses.
  // Similar to `goog.inherits`, but uses a hash of prototype properties and
  // class properties to be extended.
  var extend = function(protoProps, staticProps) {
    var parent = this;
    var child;

    // The constructor function for the new subclass is either defined by you
    // (the "constructor" property in your `extend` definition), or defaulted
    // by us to simply call the parent constructor.
    if (protoProps && _.has(protoProps, 'constructor')) {
      child = protoProps.constructor;
    } else {
      child = function(){ return parent.apply(this, arguments); };
    }

    // Add static properties to the constructor function, if supplied.
    _.extend(child, parent, staticProps);

    // Set the prototype chain to inherit from `parent`, without calling
    // `parent`'s constructor function and add the prototype properties.
    child.prototype = _.create(parent.prototype, protoProps);
    child.prototype.constructor = child;

    // Set a convenience property in case the parent's prototype is needed
    // later.
    child.__super__ = parent.prototype;

    return child;
  };

  // Set up inheritance for the model, collection, router, view and history.
  Model.extend = Collection.extend = Router.extend = View.extend = History.extend = extend;

  // Throw an error when a URL is needed, and none is supplied.
  var urlError = function() {
    throw new Error('A "url" property or function must be specified');
  };

  // Wrap an optional error callback with a fallback error event.
  var wrapError = function(model, options) {
    var error = options.error;
    options.error = function(resp) {
      if (error) error.call(options.context, model, resp, options);
      model.trigger('error', model, resp, options);
    };
  };

  return Backbone;
});


/***/ }),

/***/ 210:
/***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {

(function(mod) {
  if (true) // CommonJS
    mod(__webpack_require__(631));
  else {}
})(function(CodeMirror) {

  CodeMirror.extendMode("css", {
    commentStart: "/*",
    commentEnd: "*/",
    newlineAfterToken: function(_type, content) {
      return /^[;{}]$/.test(content);
    }
  });

  CodeMirror.extendMode("javascript", {
    commentStart: "/*",
    commentEnd: "*/",
    // FIXME semicolons inside of for
    newlineAfterToken: function(_type, content, textAfter, state) {
      if (this.jsonMode) {
        return /^[\[,{]$/.test(content) || /^}/.test(textAfter);
      } else {
        if (content == ";" && state.lexical && state.lexical.type == ")") return false;
        return /^[;{}]$/.test(content) && !/^;/.test(textAfter);
      }
    }
  });

  var inlineElements = /^(a|abbr|acronym|area|base|bdo|big|br|button|caption|cite|code|col|colgroup|dd|del|dfn|em|frame|hr|iframe|img|input|ins|kbd|label|legend|link|map|object|optgroup|option|param|q|samp|script|select|small|span|strong|sub|sup|textarea|tt|var)$/;

  CodeMirror.extendMode("xml", {
    commentStart: "<!--",
    commentEnd: "-->",
    newlineAfterToken: function(type, content, textAfter, state) {
      var inline = false;
      if (this.configuration == "html")
        inline = state.context ? inlineElements.test(state.context.tagName) : false;
      return !inline && ((type == "tag" && />$/.test(content) && state.context) ||
                         /^</.test(textAfter));
    }
  });

  // Comment/uncomment the specified range
  CodeMirror.defineExtension("commentRange", function (isComment, from, to) {
    var cm = this, curMode = CodeMirror.innerMode(cm.getMode(), cm.getTokenAt(from).state).mode;
    cm.operation(function() {
      if (isComment) { // Comment range
        cm.replaceRange(curMode.commentEnd, to);
        cm.replaceRange(curMode.commentStart, from);
        if (from.line == to.line && from.ch == to.ch) // An empty comment inserted - put cursor inside
          cm.setCursor(from.line, from.ch + curMode.commentStart.length);
      } else { // Uncomment range
        var selText = cm.getRange(from, to);
        var startIndex = selText.indexOf(curMode.commentStart);
        var endIndex = selText.lastIndexOf(curMode.commentEnd);
        if (startIndex > -1 && endIndex > -1 && endIndex > startIndex) {
          // Take string till comment start
          selText = selText.substr(0, startIndex) +
          // From comment start till comment end
             selText.substring(startIndex + curMode.commentStart.length, endIndex) +
          // From comment end till string end
             selText.substr(endIndex + curMode.commentEnd.length);
        }
        cm.replaceRange(selText, from, to);
      }
    });
  });

  // Applies automatic mode-aware indentation to the specified range
  CodeMirror.defineExtension("autoIndentRange", function (from, to) {
    var cmInstance = this;
    this.operation(function () {
      for (var i = from.line; i <= to.line; i++) {
        cmInstance.indentLine(i, "smart");
      }
    });
  });

  // Applies automatic formatting to the specified range
  CodeMirror.defineExtension("autoFormatRange", function (from, to) {
    var cm = this;
    var outer = cm.getMode(), text = cm.getRange(from, to).split("\n");
    var state = CodeMirror.copyState(outer, cm.getTokenAt(from).state);
    var tabSize = cm.getOption("tabSize");

    var out = "", lines = 0, atSol = from.ch === 0;
    function newline() {
      out += "\n";
      atSol = true;
      ++lines;
    }

    for (var i = 0; i < text.length; ++i) {
      var stream = new CodeMirror.StringStream(text[i], tabSize);
      while (!stream.eol()) {
        var inner = CodeMirror.innerMode(outer, state);
        var style = outer.token(stream, state), cur = stream.current();
        stream.start = stream.pos;
        if (!atSol || /\S/.test(cur)) {
          out += cur;
          atSol = false;
        }
        if (!atSol && inner.mode.newlineAfterToken &&
            inner.mode.newlineAfterToken(style, cur, stream.string.slice(stream.pos) || text[i+1] || "", inner.state))
          newline();
      }
      if (!stream.pos && outer.blankLine) outer.blankLine(state);
      if (!atSol && i < text.length - 1) newline();
    }

    cm.operation(function () {
      cm.replaceRange(out, from, to);
      for (var cur = from.line + 1, end = from.line + lines; cur <= end; ++cur)
        cm.indentLine(cur, "smart");
      cm.setSelection(from, cm.getCursor(false));
    });
  });
});


/***/ }),

/***/ 631:
/***/ (function(module) {

// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/5/LICENSE

// This is CodeMirror (https://codemirror.net/5), a code editor
// implemented in JavaScript on top of the browser's DOM.
//
// You can find some technical background for some of the code below
// at http://marijnhaverbeke.nl/blog/#cm-internals .

(function (global, factory) {
   true ? module.exports = factory() :
  0;
}(this, (function () { 'use strict';

  // Kludges for bugs and behavior differences that can't be feature
  // detected are enabled based on userAgent etc sniffing.
  var userAgent = navigator.userAgent;
  var platform = navigator.platform;

  var gecko = /gecko\/\d/i.test(userAgent);
  var ie_upto10 = /MSIE \d/.test(userAgent);
  var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent);
  var edge = /Edge\/(\d+)/.exec(userAgent);
  var ie = ie_upto10 || ie_11up || edge;
  var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : +(edge || ie_11up)[1]);
  var webkit = !edge && /WebKit\//.test(userAgent);
  var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent);
  var chrome = !edge && /Chrome\/(\d+)/.exec(userAgent);
  var chrome_version = chrome && +chrome[1];
  var presto = /Opera\//.test(userAgent);
  var safari = /Apple Computer/.test(navigator.vendor);
  var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent);
  var phantom = /PhantomJS/.test(userAgent);

  var ios = safari && (/Mobile\/\w+/.test(userAgent) || navigator.maxTouchPoints > 2);
  var android = /Android/.test(userAgent);
  // This is woefully incomplete. Suggestions for alternative methods welcome.
  var mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent);
  var mac = ios || /Mac/.test(platform);
  var chromeOS = /\bCrOS\b/.test(userAgent);
  var windows = /win/i.test(platform);

  var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/);
  if (presto_version) { presto_version = Number(presto_version[1]); }
  if (presto_version && presto_version >= 15) { presto = false; webkit = true; }
  // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
  var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11));
  var captureRightClick = gecko || (ie && ie_version >= 9);

  function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*") }

  var rmClass = function(node, cls) {
    var current = node.className;
    var match = classTest(cls).exec(current);
    if (match) {
      var after = current.slice(match.index + match[0].length);
      node.className = current.slice(0, match.index) + (after ? match[1] + after : "");
    }
  };

  function removeChildren(e) {
    for (var count = e.childNodes.length; count > 0; --count)
      { e.removeChild(e.firstChild); }
    return e
  }

  function removeChildrenAndAdd(parent, e) {
    return removeChildren(parent).appendChild(e)
  }

  function elt(tag, content, className, style) {
    var e = document.createElement(tag);
    if (className) { e.className = className; }
    if (style) { e.style.cssText = style; }
    if (typeof content == "string") { e.appendChild(document.createTextNode(content)); }
    else if (content) { for (var i = 0; i < content.length; ++i) { e.appendChild(content[i]); } }
    return e
  }
  // wrapper for elt, which removes the elt from the accessibility tree
  function eltP(tag, content, className, style) {
    var e = elt(tag, content, className, style);
    e.setAttribute("role", "presentation");
    return e
  }

  var range;
  if (document.createRange) { range = function(node, start, end, endNode) {
    var r = document.createRange();
    r.setEnd(endNode || node, end);
    r.setStart(node, start);
    return r
  }; }
  else { range = function(node, start, end) {
    var r = document.body.createTextRange();
    try { r.moveToElementText(node.parentNode); }
    catch(e) { return r }
    r.collapse(true);
    r.moveEnd("character", end);
    r.moveStart("character", start);
    return r
  }; }

  function contains(parent, child) {
    if (child.nodeType == 3) // Android browser always returns false when child is a textnode
      { child = child.parentNode; }
    if (parent.contains)
      { return parent.contains(child) }
    do {
      if (child.nodeType == 11) { child = child.host; }
      if (child == parent) { return true }
    } while (child = child.parentNode)
  }

  function activeElt(doc) {
    // IE and Edge may throw an "Unspecified Error" when accessing document.activeElement.
    // IE < 10 will throw when accessed while the page is loading or in an iframe.
    // IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable.
    var activeElement;
    try {
      activeElement = doc.activeElement;
    } catch(e) {
      activeElement = doc.body || null;
    }
    while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement)
      { activeElement = activeElement.shadowRoot.activeElement; }
    return activeElement
  }

  function addClass(node, cls) {
    var current = node.className;
    if (!classTest(cls).test(current)) { node.className += (current ? " " : "") + cls; }
  }
  function joinClasses(a, b) {
    var as = a.split(" ");
    for (var i = 0; i < as.length; i++)
      { if (as[i] && !classTest(as[i]).test(b)) { b += " " + as[i]; } }
    return b
  }

  var selectInput = function(node) { node.select(); };
  if (ios) // Mobile Safari apparently has a bug where select() is broken.
    { selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; }; }
  else if (ie) // Suppress mysterious IE10 errors
    { selectInput = function(node) { try { node.select(); } catch(_e) {} }; }

  function doc(cm) { return cm.display.wrapper.ownerDocument }

  function win(cm) { return doc(cm).defaultView }

  function bind(f) {
    var args = Array.prototype.slice.call(arguments, 1);
    return function(){return f.apply(null, args)}
  }

  function copyObj(obj, target, overwrite) {
    if (!target) { target = {}; }
    for (var prop in obj)
      { if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
        { target[prop] = obj[prop]; } }
    return target
  }

  // Counts the column offset in a string, taking tabs into account.
  // Used mostly to find indentation.
  function countColumn(string, end, tabSize, startIndex, startValue) {
    if (end == null) {
      end = string.search(/[^\s\u00a0]/);
      if (end == -1) { end = string.length; }
    }
    for (var i = startIndex || 0, n = startValue || 0;;) {
      var nextTab = string.indexOf("\t", i);
      if (nextTab < 0 || nextTab >= end)
        { return n + (end - i) }
      n += nextTab - i;
      n += tabSize - (n % tabSize);
      i = nextTab + 1;
    }
  }

  var Delayed = function() {
    this.id = null;
    this.f = null;
    this.time = 0;
    this.handler = bind(this.onTimeout, this);
  };
  Delayed.prototype.onTimeout = function (self) {
    self.id = 0;
    if (self.time <= +new Date) {
      self.f();
    } else {
      setTimeout(self.handler, self.time - +new Date);
    }
  };
  Delayed.prototype.set = function (ms, f) {
    this.f = f;
    var time = +new Date + ms;
    if (!this.id || time < this.time) {
      clearTimeout(this.id);
      this.id = setTimeout(this.handler, ms);
      this.time = time;
    }
  };

  function indexOf(array, elt) {
    for (var i = 0; i < array.length; ++i)
      { if (array[i] == elt) { return i } }
    return -1
  }

  // Number of pixels added to scroller and sizer to hide scrollbar
  var scrollerGap = 50;

  // Returned or thrown by various protocols to signal 'I'm not
  // handling this'.
  var Pass = {toString: function(){return "CodeMirror.Pass"}};

  // Reused option objects for setSelection & friends
  var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"};

  // The inverse of countColumn -- find the offset that corresponds to
  // a particular column.
  function findColumn(string, goal, tabSize) {
    for (var pos = 0, col = 0;;) {
      var nextTab = string.indexOf("\t", pos);
      if (nextTab == -1) { nextTab = string.length; }
      var skipped = nextTab - pos;
      if (nextTab == string.length || col + skipped >= goal)
        { return pos + Math.min(skipped, goal - col) }
      col += nextTab - pos;
      col += tabSize - (col % tabSize);
      pos = nextTab + 1;
      if (col >= goal) { return pos }
    }
  }

  var spaceStrs = [""];
  function spaceStr(n) {
    while (spaceStrs.length <= n)
      { spaceStrs.push(lst(spaceStrs) + " "); }
    return spaceStrs[n]
  }

  function lst(arr) { return arr[arr.length-1] }

  function map(array, f) {
    var out = [];
    for (var i = 0; i < array.length; i++) { out[i] = f(array[i], i); }
    return out
  }

  function insertSorted(array, value, score) {
    var pos = 0, priority = score(value);
    while (pos < array.length && score(array[pos]) <= priority) { pos++; }
    array.splice(pos, 0, value);
  }

  function nothing() {}

  function createObj(base, props) {
    var inst;
    if (Object.create) {
      inst = Object.create(base);
    } else {
      nothing.prototype = base;
      inst = new nothing();
    }
    if (props) { copyObj(props, inst); }
    return inst
  }

  var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
  function isWordCharBasic(ch) {
    return /\w/.test(ch) || ch > "\x80" &&
      (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch))
  }
  function isWordChar(ch, helper) {
    if (!helper) { return isWordCharBasic(ch) }
    if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { return true }
    return helper.test(ch)
  }

  function isEmpty(obj) {
    for (var n in obj) { if (obj.hasOwnProperty(n) && obj[n]) { return false } }
    return true
  }

  // Extending unicode characters. A series of a non-extending char +
  // any number of extending chars is treated as a single unit as far
  // as editing and measuring is concerned. This is not fully correct,
  // since some scripts/fonts/browsers also treat other configurations
  // of code points as a group.
  var extendingChars = /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/;
  function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch) }

  // Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range.
  function skipExtendingChars(str, pos, dir) {
    while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) { pos += dir; }
    return pos
  }

  // Returns the value from the range [`from`; `to`] that satisfies
  // `pred` and is closest to `from`. Assumes that at least `to`
  // satisfies `pred`. Supports `from` being greater than `to`.
  function findFirst(pred, from, to) {
    // At any point we are certain `to` satisfies `pred`, don't know
    // whether `from` does.
    var dir = from > to ? -1 : 1;
    for (;;) {
      if (from == to) { return from }
      var midF = (from + to) / 2, mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF);
      if (mid == from) { return pred(mid) ? from : to }
      if (pred(mid)) { to = mid; }
      else { from = mid + dir; }
    }
  }

  // BIDI HELPERS

  function iterateBidiSections(order, from, to, f) {
    if (!order) { return f(from, to, "ltr", 0) }
    var found = false;
    for (var i = 0; i < order.length; ++i) {
      var part = order[i];
      if (part.from < to && part.to > from || from == to && part.to == from) {
        f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr", i);
        found = true;
      }
    }
    if (!found) { f(from, to, "ltr"); }
  }

  var bidiOther = null;
  function getBidiPartAt(order, ch, sticky) {
    var found;
    bidiOther = null;
    for (var i = 0; i < order.length; ++i) {
      var cur = order[i];
      if (cur.from < ch && cur.to > ch) { return i }
      if (cur.to == ch) {
        if (cur.from != cur.to && sticky == "before") { found = i; }
        else { bidiOther = i; }
      }
      if (cur.from == ch) {
        if (cur.from != cur.to && sticky != "before") { found = i; }
        else { bidiOther = i; }
      }
    }
    return found != null ? found : bidiOther
  }

  // Bidirectional ordering algorithm
  // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
  // that this (partially) implements.

  // One-char codes used for character types:
  // L (L):   Left-to-Right
  // R (R):   Right-to-Left
  // r (AL):  Right-to-Left Arabic
  // 1 (EN):  European Number
  // + (ES):  European Number Separator
  // % (ET):  European Number Terminator
  // n (AN):  Arabic Number
  // , (CS):  Common Number Separator
  // m (NSM): Non-Spacing Mark
  // b (BN):  Boundary Neutral
  // s (B):   Paragraph Separator
  // t (S):   Segment Separator
  // w (WS):  Whitespace
  // N (ON):  Other Neutrals

  // Returns null if characters are ordered as they appear
  // (left-to-right), or an array of sections ({from, to, level}
  // objects) in the order in which they occur visually.
  var bidiOrdering = (function() {
    // Character types for codepoints 0 to 0xff
    var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
    // Character types for codepoints 0x600 to 0x6f9
    var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111";
    function charType(code) {
      if (code <= 0xf7) { return lowTypes.charAt(code) }
      else if (0x590 <= code && code <= 0x5f4) { return "R" }
      else if (0x600 <= code && code <= 0x6f9) { return arabicTypes.charAt(code - 0x600) }
      else if (0x6ee <= code && code <= 0x8ac) { return "r" }
      else if (0x2000 <= code && code <= 0x200b) { return "w" }
      else if (code == 0x200c) { return "b" }
      else { return "L" }
    }

    var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
    var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;

    function BidiSpan(level, from, to) {
      this.level = level;
      this.from = from; this.to = to;
    }

    return function(str, direction) {
      var outerType = direction == "ltr" ? "L" : "R";

      if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) { return false }
      var len = str.length, types = [];
      for (var i = 0; i < len; ++i)
        { types.push(charType(str.charCodeAt(i))); }

      // W1. Examine each non-spacing mark (NSM) in the level run, and
      // change the type of the NSM to the type of the previous
      // character. If the NSM is at the start of the level run, it will
      // get the type of sor.
      for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) {
        var type = types[i$1];
        if (type == "m") { types[i$1] = prev; }
        else { prev = type; }
      }

      // W2. Search backwards from each instance of a European number
      // until the first strong type (R, L, AL, or sor) is found. If an
      // AL is found, change the type of the European number to Arabic
      // number.
      // W3. Change all ALs to R.
      for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) {
        var type$1 = types[i$2];
        if (type$1 == "1" && cur == "r") { types[i$2] = "n"; }
        else if (isStrong.test(type$1)) { cur = type$1; if (type$1 == "r") { types[i$2] = "R"; } }
      }

      // W4. A single European separator between two European numbers
      // changes to a European number. A single common separator between
      // two numbers of the same type changes to that type.
      for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) {
        var type$2 = types[i$3];
        if (type$2 == "+" && prev$1 == "1" && types[i$3+1] == "1") { types[i$3] = "1"; }
        else if (type$2 == "," && prev$1 == types[i$3+1] &&
                 (prev$1 == "1" || prev$1 == "n")) { types[i$3] = prev$1; }
        prev$1 = type$2;
      }

      // W5. A sequence of European terminators adjacent to European
      // numbers changes to all European numbers.
      // W6. Otherwise, separators and terminators change to Other
      // Neutral.
      for (var i$4 = 0; i$4 < len; ++i$4) {
        var type$3 = types[i$4];
        if (type$3 == ",") { types[i$4] = "N"; }
        else if (type$3 == "%") {
          var end = (void 0);
          for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {}
          var replace = (i$4 && types[i$4-1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
          for (var j = i$4; j < end; ++j) { types[j] = replace; }
          i$4 = end - 1;
        }
      }

      // W7. Search backwards from each instance of a European number
      // until the first strong type (R, L, or sor) is found. If an L is
      // found, then change the type of the European number to L.
      for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) {
        var type$4 = types[i$5];
        if (cur$1 == "L" && type$4 == "1") { types[i$5] = "L"; }
        else if (isStrong.test(type$4)) { cur$1 = type$4; }
      }

      // N1. A sequence of neutrals takes the direction of the
      // surrounding strong text if the text on both sides has the same
      // direction. European and Arabic numbers act as if they were R in
      // terms of their influence on neutrals. Start-of-level-run (sor)
      // and end-of-level-run (eor) are used at level run boundaries.
      // N2. Any remaining neutrals take the embedding direction.
      for (var i$6 = 0; i$6 < len; ++i$6) {
        if (isNeutral.test(types[i$6])) {
          var end$1 = (void 0);
          for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {}
          var before = (i$6 ? types[i$6-1] : outerType) == "L";
          var after = (end$1 < len ? types[end$1] : outerType) == "L";
          var replace$1 = before == after ? (before ? "L" : "R") : outerType;
          for (var j$1 = i$6; j$1 < end$1; ++j$1) { types[j$1] = replace$1; }
          i$6 = end$1 - 1;
        }
      }

      // Here we depart from the documented algorithm, in order to avoid
      // building up an actual levels array. Since there are only three
      // levels (0, 1, 2) in an implementation that doesn't take
      // explicit embedding into account, we can build up the order on
      // the fly, without following the level-based algorithm.
      var order = [], m;
      for (var i$7 = 0; i$7 < len;) {
        if (countsAsLeft.test(types[i$7])) {
          var start = i$7;
          for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {}
          order.push(new BidiSpan(0, start, i$7));
        } else {
          var pos = i$7, at = order.length, isRTL = direction == "rtl" ? 1 : 0;
          for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {}
          for (var j$2 = pos; j$2 < i$7;) {
            if (countsAsNum.test(types[j$2])) {
              if (pos < j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)); at += isRTL; }
              var nstart = j$2;
              for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {}
              order.splice(at, 0, new BidiSpan(2, nstart, j$2));
              at += isRTL;
              pos = j$2;
            } else { ++j$2; }
          }
          if (pos < i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)); }
        }
      }
      if (direction == "ltr") {
        if (order[0].level == 1 && (m = str.match(/^\s+/))) {
          order[0].from = m[0].length;
          order.unshift(new BidiSpan(0, 0, m[0].length));
        }
        if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
          lst(order).to -= m[0].length;
          order.push(new BidiSpan(0, len - m[0].length, len));
        }
      }

      return direction == "rtl" ? order.reverse() : order
    }
  })();

  // Get the bidi ordering for the given line (and cache it). Returns
  // false for lines that are fully left-to-right, and an array of
  // BidiSpan objects otherwise.
  function getOrder(line, direction) {
    var order = line.order;
    if (order == null) { order = line.order = bidiOrdering(line.text, direction); }
    return order
  }

  // EVENT HANDLING

  // Lightweight event framework. on/off also work on DOM nodes,
  // registering native DOM handlers.

  var noHandlers = [];

  var on = function(emitter, type, f) {
    if (emitter.addEventListener) {
      emitter.addEventListener(type, f, false);
    } else if (emitter.attachEvent) {
      emitter.attachEvent("on" + type, f);
    } else {
      var map = emitter._handlers || (emitter._handlers = {});
      map[type] = (map[type] || noHandlers).concat(f);
    }
  };

  function getHandlers(emitter, type) {
    return emitter._handlers && emitter._handlers[type] || noHandlers
  }

  function off(emitter, type, f) {
    if (emitter.removeEventListener) {
      emitter.removeEventListener(type, f, false);
    } else if (emitter.detachEvent) {
      emitter.detachEvent("on" + type, f);
    } else {
      var map = emitter._handlers, arr = map && map[type];
      if (arr) {
        var index = indexOf(arr, f);
        if (index > -1)
          { map[type] = arr.slice(0, index).concat(arr.slice(index + 1)); }
      }
    }
  }

  function signal(emitter, type /*, values...*/) {
    var handlers = getHandlers(emitter, type);
    if (!handlers.length) { return }
    var args = Array.prototype.slice.call(arguments, 2);
    for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(null, args); }
  }

  // The DOM events that CodeMirror handles can be overridden by
  // registering a (non-DOM) handler on the editor for the event name,
  // and preventDefault-ing the event in that handler.
  function signalDOMEvent(cm, e, override) {
    if (typeof e == "string")
      { e = {type: e, preventDefault: function() { this.defaultPrevented = true; }}; }
    signal(cm, override || e.type, cm, e);
    return e_defaultPrevented(e) || e.codemirrorIgnore
  }

  function signalCursorActivity(cm) {
    var arr = cm._handlers && cm._handlers.cursorActivity;
    if (!arr) { return }
    var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
    for (var i = 0; i < arr.length; ++i) { if (indexOf(set, arr[i]) == -1)
      { set.push(arr[i]); } }
  }

  function hasHandler(emitter, type) {
    return getHandlers(emitter, type).length > 0
  }

  // Add on and off methods to a constructor's prototype, to make
  // registering events on such objects more convenient.
  function eventMixin(ctor) {
    ctor.prototype.on = function(type, f) {on(this, type, f);};
    ctor.prototype.off = function(type, f) {off(this, type, f);};
  }

  // Due to the fact that we still support jurassic IE versions, some
  // compatibility wrappers are needed.

  function e_preventDefault(e) {
    if (e.preventDefault) { e.preventDefault(); }
    else { e.returnValue = false; }
  }
  function e_stopPropagation(e) {
    if (e.stopPropagation) { e.stopPropagation(); }
    else { e.cancelBubble = true; }
  }
  function e_defaultPrevented(e) {
    return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false
  }
  function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);}

  function e_target(e) {return e.target || e.srcElement}
  function e_button(e) {
    var b = e.which;
    if (b == null) {
      if (e.button & 1) { b = 1; }
      else if (e.button & 2) { b = 3; }
      else if (e.button & 4) { b = 2; }
    }
    if (mac && e.ctrlKey && b == 1) { b = 3; }
    return b
  }

  // Detect drag-and-drop
  var dragAndDrop = function() {
    // There is *some* kind of drag-and-drop support in IE6-8, but I
    // couldn't get it to work yet.
    if (ie && ie_version < 9) { return false }
    var div = elt('div');
    return "draggable" in div || "dragDrop" in div
  }();

  var zwspSupported;
  function zeroWidthElement(measure) {
    if (zwspSupported == null) {
      var test = elt("span", "\u200b");
      removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
      if (measure.firstChild.offsetHeight != 0)
        { zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); }
    }
    var node = zwspSupported ? elt("span", "\u200b") :
      elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
    node.setAttribute("cm-text", "");
    return node
  }

  // Feature-detect IE's crummy client rect reporting for bidi text
  var badBidiRects;
  function hasBadBidiRects(measure) {
    if (badBidiRects != null) { return badBidiRects }
    var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
    var r0 = range(txt, 0, 1).getBoundingClientRect();
    var r1 = range(txt, 1, 2).getBoundingClientRect();
    removeChildren(measure);
    if (!r0 || r0.left == r0.right) { return false } // Safari returns null in some cases (#2780)
    return badBidiRects = (r1.right - r0.right < 3)
  }

  // See if "".split is the broken IE version, if so, provide an
  // alternative way to split lines.
  var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) {
    var pos = 0, result = [], l = string.length;
    while (pos <= l) {
      var nl = string.indexOf("\n", pos);
      if (nl == -1) { nl = string.length; }
      var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
      var rt = line.indexOf("\r");
      if (rt != -1) {
        result.push(line.slice(0, rt));
        pos += rt + 1;
      } else {
        result.push(line);
        pos = nl + 1;
      }
    }
    return result
  } : function (string) { return string.split(/\r\n?|\n/); };

  var hasSelection = window.getSelection ? function (te) {
    try { return te.selectionStart != te.selectionEnd }
    catch(e) { return false }
  } : function (te) {
    var range;
    try {range = te.ownerDocument.selection.createRange();}
    catch(e) {}
    if (!range || range.parentElement() != te) { return false }
    return range.compareEndPoints("StartToEnd", range) != 0
  };

  var hasCopyEvent = (function () {
    var e = elt("div");
    if ("oncopy" in e) { return true }
    e.setAttribute("oncopy", "return;");
    return typeof e.oncopy == "function"
  })();

  var badZoomedRects = null;
  function hasBadZoomedRects(measure) {
    if (badZoomedRects != null) { return badZoomedRects }
    var node = removeChildrenAndAdd(measure, elt("span", "x"));
    var normal = node.getBoundingClientRect();
    var fromRange = range(node, 0, 1).getBoundingClientRect();
    return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1
  }

  // Known modes, by name and by MIME
  var modes = {}, mimeModes = {};

  // Extra arguments are stored as the mode's dependencies, which is
  // used by (legacy) mechanisms like loadmode.js to automatically
  // load a mode. (Preferred mechanism is the require/define calls.)
  function defineMode(name, mode) {
    if (arguments.length > 2)
      { mode.dependencies = Array.prototype.slice.call(arguments, 2); }
    modes[name] = mode;
  }

  function defineMIME(mime, spec) {
    mimeModes[mime] = spec;
  }

  // Given a MIME type, a {name, ...options} config object, or a name
  // string, return a mode config object.
  function resolveMode(spec) {
    if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
      spec = mimeModes[spec];
    } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
      var found = mimeModes[spec.name];
      if (typeof found == "string") { found = {name: found}; }
      spec = createObj(found, spec);
      spec.name = found.name;
    } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
      return resolveMode("application/xml")
    } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) {
      return resolveMode("application/json")
    }
    if (typeof spec == "string") { return {name: spec} }
    else { return spec || {name: "null"} }
  }

  // Given a mode spec (anything that resolveMode accepts), find and
  // initialize an actual mode object.
  function getMode(options, spec) {
    spec = resolveMode(spec);
    var mfactory = modes[spec.name];
    if (!mfactory) { return getMode(options, "text/plain") }
    var modeObj = mfactory(options, spec);
    if (modeExtensions.hasOwnProperty(spec.name)) {
      var exts = modeExtensions[spec.name];
      for (var prop in exts) {
        if (!exts.hasOwnProperty(prop)) { continue }
        if (modeObj.hasOwnProperty(prop)) { modeObj["_" + prop] = modeObj[prop]; }
        modeObj[prop] = exts[prop];
      }
    }
    modeObj.name = spec.name;
    if (spec.helperType) { modeObj.helperType = spec.helperType; }
    if (spec.modeProps) { for (var prop$1 in spec.modeProps)
      { modeObj[prop$1] = spec.modeProps[prop$1]; } }

    return modeObj
  }

  // This can be used to attach properties to mode objects from
  // outside the actual mode definition.
  var modeExtensions = {};
  function extendMode(mode, properties) {
    var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
    copyObj(properties, exts);
  }

  function copyState(mode, state) {
    if (state === true) { return state }
    if (mode.copyState) { return mode.copyState(state) }
    var nstate = {};
    for (var n in state) {
      var val = state[n];
      if (val instanceof Array) { val = val.concat([]); }
      nstate[n] = val;
    }
    return nstate
  }

  // Given a mode and a state (for that mode), find the inner mode and
  // state at the position that the state refers to.
  function innerMode(mode, state) {
    var info;
    while (mode.innerMode) {
      info = mode.innerMode(state);
      if (!info || info.mode == mode) { break }
      state = info.state;
      mode = info.mode;
    }
    return info || {mode: mode, state: state}
  }

  function startState(mode, a1, a2) {
    return mode.startState ? mode.startState(a1, a2) : true
  }

  // STRING STREAM

  // Fed to the mode parsers, provides helper functions to make
  // parsers more succinct.

  var StringStream = function(string, tabSize, lineOracle) {
    this.pos = this.start = 0;
    this.string = string;
    this.tabSize = tabSize || 8;
    this.lastColumnPos = this.lastColumnValue = 0;
    this.lineStart = 0;
    this.lineOracle = lineOracle;
  };

  StringStream.prototype.eol = function () {return this.pos >= this.string.length};
  StringStream.prototype.sol = function () {return this.pos == this.lineStart};
  StringStream.prototype.peek = function () {return this.string.charAt(this.pos) || undefined};
  StringStream.prototype.next = function () {
    if (this.pos < this.string.length)
      { return this.string.charAt(this.pos++) }
  };
  StringStream.prototype.eat = function (match) {
    var ch = this.string.charAt(this.pos);
    var ok;
    if (typeof match == "string") { ok = ch == match; }
    else { ok = ch && (match.test ? match.test(ch) : match(ch)); }
    if (ok) {++this.pos; return ch}
  };
  StringStream.prototype.eatWhile = function (match) {
    var start = this.pos;
    while (this.eat(match)){}
    return this.pos > start
  };
  StringStream.prototype.eatSpace = function () {
    var start = this.pos;
    while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { ++this.pos; }
    return this.pos > start
  };
  StringStream.prototype.skipToEnd = function () {this.pos = this.string.length;};
  StringStream.prototype.skipTo = function (ch) {
    var found = this.string.indexOf(ch, this.pos);
    if (found > -1) {this.pos = found; return true}
  };
  StringStream.prototype.backUp = function (n) {this.pos -= n;};
  StringStream.prototype.column = function () {
    if (this.lastColumnPos < this.start) {
      this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
      this.lastColumnPos = this.start;
    }
    return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
  };
  StringStream.prototype.indentation = function () {
    return countColumn(this.string, null, this.tabSize) -
      (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
  };
  StringStream.prototype.match = function (pattern, consume, caseInsensitive) {
    if (typeof pattern == "string") {
      var cased = function (str) { return caseInsensitive ? str.toLowerCase() : str; };
      var substr = this.string.substr(this.pos, pattern.length);
      if (cased(substr) == cased(pattern)) {
        if (consume !== false) { this.pos += pattern.length; }
        return true
      }
    } else {
      var match = this.string.slice(this.pos).match(pattern);
      if (match && match.index > 0) { return null }
      if (match && consume !== false) { this.pos += match[0].length; }
      return match
    }
  };
  StringStream.prototype.current = function (){return this.string.slice(this.start, this.pos)};
  StringStream.prototype.hideFirstChars = function (n, inner) {
    this.lineStart += n;
    try { return inner() }
    finally { this.lineStart -= n; }
  };
  StringStream.prototype.lookAhead = function (n) {
    var oracle = this.lineOracle;
    return oracle && oracle.lookAhead(n)
  };
  StringStream.prototype.baseToken = function () {
    var oracle = this.lineOracle;
    return oracle && oracle.baseToken(this.pos)
  };

  // Find the line object corresponding to the given line number.
  function getLine(doc, n) {
    n -= doc.first;
    if (n < 0 || n >= doc.size) { throw new Error("There is no line " + (n + doc.first) + " in the document.") }
    var chunk = doc;
    while (!chunk.lines) {
      for (var i = 0;; ++i) {
        var child = chunk.children[i], sz = child.chunkSize();
        if (n < sz) { chunk = child; break }
        n -= sz;
      }
    }
    return chunk.lines[n]
  }

  // Get the part of a document between two positions, as an array of
  // strings.
  function getBetween(doc, start, end) {
    var out = [], n = start.line;
    doc.iter(start.line, end.line + 1, function (line) {
      var text = line.text;
      if (n == end.line) { text = text.slice(0, end.ch); }
      if (n == start.line) { text = text.slice(start.ch); }
      out.push(text);
      ++n;
    });
    return out
  }
  // Get the lines between from and to, as array of strings.
  function getLines(doc, from, to) {
    var out = [];
    doc.iter(from, to, function (line) { out.push(line.text); }); // iter aborts when callback returns truthy value
    return out
  }

  // Update the height of a line, propagating the height change
  // upwards to parent nodes.
  function updateLineHeight(line, height) {
    var diff = height - line.height;
    if (diff) { for (var n = line; n; n = n.parent) { n.height += diff; } }
  }

  // Given a line object, find its line number by walking up through
  // its parent links.
  function lineNo(line) {
    if (line.parent == null) { return null }
    var cur = line.parent, no = indexOf(cur.lines, line);
    for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
      for (var i = 0;; ++i) {
        if (chunk.children[i] == cur) { break }
        no += chunk.children[i].chunkSize();
      }
    }
    return no + cur.first
  }

  // Find the line at the given vertical position, using the height
  // information in the document tree.
  function lineAtHeight(chunk, h) {
    var n = chunk.first;
    outer: do {
      for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) {
        var child = chunk.children[i$1], ch = child.height;
        if (h < ch) { chunk = child; continue outer }
        h -= ch;
        n += child.chunkSize();
      }
      return n
    } while (!chunk.lines)
    var i = 0;
    for (; i < chunk.lines.length; ++i) {
      var line = chunk.lines[i], lh = line.height;
      if (h < lh) { break }
      h -= lh;
    }
    return n + i
  }

  function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size}

  function lineNumberFor(options, i) {
    return String(options.lineNumberFormatter(i + options.firstLineNumber))
  }

  // A Pos instance represents a position within the text.
  function Pos(line, ch, sticky) {
    if ( sticky === void 0 ) sticky = null;

    if (!(this instanceof Pos)) { return new Pos(line, ch, sticky) }
    this.line = line;
    this.ch = ch;
    this.sticky = sticky;
  }

  // Compare two positions, return 0 if they are the same, a negative
  // number when a is less, and a positive number otherwise.
  function cmp(a, b) { return a.line - b.line || a.ch - b.ch }

  function equalCursorPos(a, b) { return a.sticky == b.sticky && cmp(a, b) == 0 }

  function copyPos(x) {return Pos(x.line, x.ch)}
  function maxPos(a, b) { return cmp(a, b) < 0 ? b : a }
  function minPos(a, b) { return cmp(a, b) < 0 ? a : b }

  // Most of the external API clips given positions to make sure they
  // actually exist within the document.
  function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))}
  function clipPos(doc, pos) {
    if (pos.line < doc.first) { return Pos(doc.first, 0) }
    var last = doc.first + doc.size - 1;
    if (pos.line > last) { return Pos(last, getLine(doc, last).text.length) }
    return clipToLen(pos, getLine(doc, pos.line).text.length)
  }
  function clipToLen(pos, linelen) {
    var ch = pos.ch;
    if (ch == null || ch > linelen) { return Pos(pos.line, linelen) }
    else if (ch < 0) { return Pos(pos.line, 0) }
    else { return pos }
  }
  function clipPosArray(doc, array) {
    var out = [];
    for (var i = 0; i < array.length; i++) { out[i] = clipPos(doc, array[i]); }
    return out
  }

  var SavedContext = function(state, lookAhead) {
    this.state = state;
    this.lookAhead = lookAhead;
  };

  var Context = function(doc, state, line, lookAhead) {
    this.state = state;
    this.doc = doc;
    this.line = line;
    this.maxLookAhead = lookAhead || 0;
    this.baseTokens = null;
    this.baseTokenPos = 1;
  };

  Context.prototype.lookAhead = function (n) {
    var line = this.doc.getLine(this.line + n);
    if (line != null && n > this.maxLookAhead) { this.maxLookAhead = n; }
    return line
  };

  Context.prototype.baseToken = function (n) {
    if (!this.baseTokens) { return null }
    while (this.baseTokens[this.baseTokenPos] <= n)
      { this.baseTokenPos += 2; }
    var type = this.baseTokens[this.baseTokenPos + 1];
    return {type: type && type.replace(/( |^)overlay .*/, ""),
            size: this.baseTokens[this.baseTokenPos] - n}
  };

  Context.prototype.nextLine = function () {
    this.line++;
    if (this.maxLookAhead > 0) { this.maxLookAhead--; }
  };

  Context.fromSaved = function (doc, saved, line) {
    if (saved instanceof SavedContext)
      { return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead) }
    else
      { return new Context(doc, copyState(doc.mode, saved), line) }
  };

  Context.prototype.save = function (copy) {
    var state = copy !== false ? copyState(this.doc.mode, this.state) : this.state;
    return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state
  };


  // Compute a style array (an array starting with a mode generation
  // -- for invalidation -- followed by pairs of end positions and
  // style strings), which is used to highlight the tokens on the
  // line.
  function highlightLine(cm, line, context, forceToEnd) {
    // A styles array always starts with a number identifying the
    // mode/overlays that it is based on (for easy invalidation).
    var st = [cm.state.modeGen], lineClasses = {};
    // Compute the base array of styles
    runMode(cm, line.text, cm.doc.mode, context, function (end, style) { return st.push(end, style); },
            lineClasses, forceToEnd);
    var state = context.state;

    // Run overlays, adjust style array.
    var loop = function ( o ) {
      context.baseTokens = st;
      var overlay = cm.state.overlays[o], i = 1, at = 0;
      context.state = true;
      runMode(cm, line.text, overlay.mode, context, function (end, style) {
        var start = i;
        // Ensure there's a token end at the current position, and that i points at it
        while (at < end) {
          var i_end = st[i];
          if (i_end > end)
            { st.splice(i, 1, end, st[i+1], i_end); }
          i += 2;
          at = Math.min(end, i_end);
        }
        if (!style) { return }
        if (overlay.opaque) {
          st.splice(start, i - start, end, "overlay " + style);
          i = start + 2;
        } else {
          for (; start < i; start += 2) {
            var cur = st[start+1];
            st[start+1] = (cur ? cur + " " : "") + "overlay " + style;
          }
        }
      }, lineClasses);
      context.state = state;
      context.baseTokens = null;
      context.baseTokenPos = 1;
    };

    for (var o = 0; o < cm.state.overlays.length; ++o) loop( o );

    return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}
  }

  function getLineStyles(cm, line, updateFrontier) {
    if (!line.styles || line.styles[0] != cm.state.modeGen) {
      var context = getContextBefore(cm, lineNo(line));
      var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state);
      var result = highlightLine(cm, line, context);
      if (resetState) { context.state = resetState; }
      line.stateAfter = context.save(!resetState);
      line.styles = result.styles;
      if (result.classes) { line.styleClasses = result.classes; }
      else if (line.styleClasses) { line.styleClasses = null; }
      if (updateFrontier === cm.doc.highlightFrontier)
        { cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier); }
    }
    return line.styles
  }

  function getContextBefore(cm, n, precise) {
    var doc = cm.doc, display = cm.display;
    if (!doc.mode.startState) { return new Context(doc, true, n) }
    var start = findStartLine(cm, n, precise);
    var saved = start > doc.first && getLine(doc, start - 1).stateAfter;
    var context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start);

    doc.iter(start, n, function (line) {
      processLine(cm, line.text, context);
      var pos = context.line;
      line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null;
      context.nextLine();
    });
    if (precise) { doc.modeFrontier = context.line; }
    return context
  }

  // Lightweight form of highlight -- proceed over this line and
  // update state, but don't save a style array. Used for lines that
  // aren't currently visible.
  function processLine(cm, text, context, startAt) {
    var mode = cm.doc.mode;
    var stream = new StringStream(text, cm.options.tabSize, context);
    stream.start = stream.pos = startAt || 0;
    if (text == "") { callBlankLine(mode, context.state); }
    while (!stream.eol()) {
      readToken(mode, stream, context.state);
      stream.start = stream.pos;
    }
  }

  function callBlankLine(mode, state) {
    if (mode.blankLine) { return mode.blankLine(state) }
    if (!mode.innerMode) { return }
    var inner = innerMode(mode, state);
    if (inner.mode.blankLine) { return inner.mode.blankLine(inner.state) }
  }

  function readToken(mode, stream, state, inner) {
    for (var i = 0; i < 10; i++) {
      if (inner) { inner[0] = innerMode(mode, state).mode; }
      var style = mode.token(stream, state);
      if (stream.pos > stream.start) { return style }
    }
    throw new Error("Mode " + mode.name + " failed to advance stream.")
  }

  var Token = function(stream, type, state) {
    this.start = stream.start; this.end = stream.pos;
    this.string = stream.current();
    this.type = type || null;
    this.state = state;
  };

  // Utility for getTokenAt and getLineTokens
  function takeToken(cm, pos, precise, asArray) {
    var doc = cm.doc, mode = doc.mode, style;
    pos = clipPos(doc, pos);
    var line = getLine(doc, pos.line), context = getContextBefore(cm, pos.line, precise);
    var stream = new StringStream(line.text, cm.options.tabSize, context), tokens;
    if (asArray) { tokens = []; }
    while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
      stream.start = stream.pos;
      style = readToken(mode, stream, context.state);
      if (asArray) { tokens.push(new Token(stream, style, copyState(doc.mode, context.state))); }
    }
    return asArray ? tokens : new Token(stream, style, context.state)
  }

  function extractLineClasses(type, output) {
    if (type) { for (;;) {
      var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
      if (!lineClass) { break }
      type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
      var prop = lineClass[1] ? "bgClass" : "textClass";
      if (output[prop] == null)
        { output[prop] = lineClass[2]; }
      else if (!(new RegExp("(?:^|\\s)" + lineClass[2] + "(?:$|\\s)")).test(output[prop]))
        { output[prop] += " " + lineClass[2]; }
    } }
    return type
  }

  // Run the given mode's parser over a line, calling f for each token.
  function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) {
    var flattenSpans = mode.flattenSpans;
    if (flattenSpans == null) { flattenSpans = cm.options.flattenSpans; }
    var curStart = 0, curStyle = null;
    var stream = new StringStream(text, cm.options.tabSize, context), style;
    var inner = cm.options.addModeClass && [null];
    if (text == "") { extractLineClasses(callBlankLine(mode, context.state), lineClasses); }
    while (!stream.eol()) {
      if (stream.pos > cm.options.maxHighlightLength) {
        flattenSpans = false;
        if (forceToEnd) { processLine(cm, text, context, stream.pos); }
        stream.pos = text.length;
        style = null;
      } else {
        style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses);
      }
      if (inner) {
        var mName = inner[0].name;
        if (mName) { style = "m-" + (style ? mName + " " + style : mName); }
      }
      if (!flattenSpans || curStyle != style) {
        while (curStart < stream.start) {
          curStart = Math.min(stream.start, curStart + 5000);
          f(curStart, curStyle);
        }
        curStyle = style;
      }
      stream.start = stream.pos;
    }
    while (curStart < stream.pos) {
      // Webkit seems to refuse to render text nodes longer than 57444
      // characters, and returns inaccurate measurements in nodes
      // starting around 5000 chars.
      var pos = Math.min(stream.pos, curStart + 5000);
      f(pos, curStyle);
      curStart = pos;
    }
  }

  // Finds the line to start with when starting a parse. Tries to
  // find a line with a stateAfter, so that it can start with a
  // valid state. If that fails, it returns the line with the
  // smallest indentation, which tends to need the least context to
  // parse correctly.
  function findStartLine(cm, n, precise) {
    var minindent, minline, doc = cm.doc;
    var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
    for (var search = n; search > lim; --search) {
      if (search <= doc.first) { return doc.first }
      var line = getLine(doc, search - 1), after = line.stateAfter;
      if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier))
        { return search }
      var indented = countColumn(line.text, null, cm.options.tabSize);
      if (minline == null || minindent > indented) {
        minline = search - 1;
        minindent = indented;
      }
    }
    return minline
  }

  function retreatFrontier(doc, n) {
    doc.modeFrontier = Math.min(doc.modeFrontier, n);
    if (doc.highlightFrontier < n - 10) { return }
    var start = doc.first;
    for (var line = n - 1; line > start; line--) {
      var saved = getLine(doc, line).stateAfter;
      // change is on 3
      // state on line 1 looked ahead 2 -- so saw 3
      // test 1 + 2 < 3 should cover this
      if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) {
        start = line + 1;
        break
      }
    }
    doc.highlightFrontier = Math.min(doc.highlightFrontier, start);
  }

  // Optimize some code when these features are not used.
  var sawReadOnlySpans = false, sawCollapsedSpans = false;

  function seeReadOnlySpans() {
    sawReadOnlySpans = true;
  }

  function seeCollapsedSpans() {
    sawCollapsedSpans = true;
  }

  // TEXTMARKER SPANS

  function MarkedSpan(marker, from, to) {
    this.marker = marker;
    this.from = from; this.to = to;
  }

  // Search an array of spans for a span matching the given marker.
  function getMarkedSpanFor(spans, marker) {
    if (spans) { for (var i = 0; i < spans.length; ++i) {
      var span = spans[i];
      if (span.marker == marker) { return span }
    } }
  }

  // Remove a span from an array, returning undefined if no spans are
  // left (we don't store arrays for lines without spans).
  function removeMarkedSpan(spans, span) {
    var r;
    for (var i = 0; i < spans.length; ++i)
      { if (spans[i] != span) { (r || (r = [])).push(spans[i]); } }
    return r
  }

  // Add a span to a line.
  function addMarkedSpan(line, span, op) {
    var inThisOp = op && window.WeakSet && (op.markedSpans || (op.markedSpans = new WeakSet));
    if (inThisOp && line.markedSpans && inThisOp.has(line.markedSpans)) {
      line.markedSpans.push(span);
    } else {
      line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
      if (inThisOp) { inThisOp.add(line.markedSpans); }
    }
    span.marker.attachLine(line);
  }

  // Used for the algorithm that adjusts markers for a change in the
  // document. These functions cut an array of spans at a given
  // character position, returning an array of remaining chunks (or
  // undefined if nothing remains).
  function markedSpansBefore(old, startCh, isInsert) {
    var nw;
    if (old) { for (var i = 0; i < old.length; ++i) {
      var span = old[i], marker = span.marker;
      var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
      if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
        var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh)
        ;(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
      }
    } }
    return nw
  }
  function markedSpansAfter(old, endCh, isInsert) {
    var nw;
    if (old) { for (var i = 0; i < old.length; ++i) {
      var span = old[i], marker = span.marker;
      var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
      if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
        var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh)
        ;(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
                                              span.to == null ? null : span.to - endCh));
      }
    } }
    return nw
  }

  // Given a change object, compute the new set of marker spans that
  // cover the line in which the change took place. Removes spans
  // entirely within the change, reconnects spans belonging to the
  // same marker that appear on both sides of the change, and cuts off
  // spans partially within the change. Returns an array of span
  // arrays with one element for each line in (after) the change.
  function stretchSpansOverChange(doc, change) {
    if (change.full) { return null }
    var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
    var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
    if (!oldFirst && !oldLast) { return null }

    var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
    // Get the spans that 'stick out' on both sides
    var first = markedSpansBefore(oldFirst, startCh, isInsert);
    var last = markedSpansAfter(oldLast, endCh, isInsert);

    // Next, merge those two ends
    var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
    if (first) {
      // Fix up .to properties of first
      for (var i = 0; i < first.length; ++i) {
        var span = first[i];
        if (span.to == null) {
          var found = getMarkedSpanFor(last, span.marker);
          if (!found) { span.to = startCh; }
          else if (sameLine) { span.to = found.to == null ? null : found.to + offset; }
        }
      }
    }
    if (last) {
      // Fix up .from in last (or move them into first in case of sameLine)
      for (var i$1 = 0; i$1 < last.length; ++i$1) {
        var span$1 = last[i$1];
        if (span$1.to != null) { span$1.to += offset; }
        if (span$1.from == null) {
          var found$1 = getMarkedSpanFor(first, span$1.marker);
          if (!found$1) {
            span$1.from = offset;
            if (sameLine) { (first || (first = [])).push(span$1); }
          }
        } else {
          span$1.from += offset;
          if (sameLine) { (first || (first = [])).push(span$1); }
        }
      }
    }
    // Make sure we didn't create any zero-length spans
    if (first) { first = clearEmptySpans(first); }
    if (last && last != first) { last = clearEmptySpans(last); }

    var newMarkers = [first];
    if (!sameLine) {
      // Fill gap with whole-line-spans
      var gap = change.text.length - 2, gapMarkers;
      if (gap > 0 && first)
        { for (var i$2 = 0; i$2 < first.length; ++i$2)
          { if (first[i$2].to == null)
            { (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null)); } } }
      for (var i$3 = 0; i$3 < gap; ++i$3)
        { newMarkers.push(gapMarkers); }
      newMarkers.push(last);
    }
    return newMarkers
  }

  // Remove spans that are empty and don't have a clearWhenEmpty
  // option of false.
  function clearEmptySpans(spans) {
    for (var i = 0; i < spans.length; ++i) {
      var span = spans[i];
      if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
        { spans.splice(i--, 1); }
    }
    if (!spans.length) { return null }
    return spans
  }

  // Used to 'clip' out readOnly ranges when making a change.
  function removeReadOnlyRanges(doc, from, to) {
    var markers = null;
    doc.iter(from.line, to.line + 1, function (line) {
      if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
        var mark = line.markedSpans[i].marker;
        if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
          { (markers || (markers = [])).push(mark); }
      } }
    });
    if (!markers) { return null }
    var parts = [{from: from, to: to}];
    for (var i = 0; i < markers.length; ++i) {
      var mk = markers[i], m = mk.find(0);
      for (var j = 0; j < parts.length; ++j) {
        var p = parts[j];
        if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { continue }
        var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
        if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
          { newParts.push({from: p.from, to: m.from}); }
        if (dto > 0 || !mk.inclusiveRight && !dto)
          { newParts.push({from: m.to, to: p.to}); }
        parts.splice.apply(parts, newParts);
        j += newParts.length - 3;
      }
    }
    return parts
  }

  // Connect or disconnect spans from a line.
  function detachMarkedSpans(line) {
    var spans = line.markedSpans;
    if (!spans) { return }
    for (var i = 0; i < spans.length; ++i)
      { spans[i].marker.detachLine(line); }
    line.markedSpans = null;
  }
  function attachMarkedSpans(line, spans) {
    if (!spans) { return }
    for (var i = 0; i < spans.length; ++i)
      { spans[i].marker.attachLine(line); }
    line.markedSpans = spans;
  }

  // Helpers used when computing which overlapping collapsed span
  // counts as the larger one.
  function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0 }
  function extraRight(marker) { return marker.inclusiveRight ? 1 : 0 }

  // Returns a number indicating which of two overlapping collapsed
  // spans is larger (and thus includes the other). Falls back to
  // comparing ids when the spans cover exactly the same range.
  function compareCollapsedMarkers(a, b) {
    var lenDiff = a.lines.length - b.lines.length;
    if (lenDiff != 0) { return lenDiff }
    var aPos = a.find(), bPos = b.find();
    var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
    if (fromCmp) { return -fromCmp }
    var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
    if (toCmp) { return toCmp }
    return b.id - a.id
  }

  // Find out whether a line ends or starts in a collapsed span. If
  // so, return the marker for that span.
  function collapsedSpanAtSide(line, start) {
    var sps = sawCollapsedSpans && line.markedSpans, found;
    if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
      sp = sps[i];
      if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
          (!found || compareCollapsedMarkers(found, sp.marker) < 0))
        { found = sp.marker; }
    } }
    return found
  }
  function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true) }
  function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false) }

  function collapsedSpanAround(line, ch) {
    var sps = sawCollapsedSpans && line.markedSpans, found;
    if (sps) { for (var i = 0; i < sps.length; ++i) {
      var sp = sps[i];
      if (sp.marker.collapsed && (sp.from == null || sp.from < ch) && (sp.to == null || sp.to > ch) &&
          (!found || compareCollapsedMarkers(found, sp.marker) < 0)) { found = sp.marker; }
    } }
    return found
  }

  // Test whether there exists a collapsed span that partially
  // overlaps (covers the start or end, but not both) of a new span.
  // Such overlap is not allowed.
  function conflictingCollapsedRange(doc, lineNo, from, to, marker) {
    var line = getLine(doc, lineNo);
    var sps = sawCollapsedSpans && line.markedSpans;
    if (sps) { for (var i = 0; i < sps.length; ++i) {
      var sp = sps[i];
      if (!sp.marker.collapsed) { continue }
      var found = sp.marker.find(0);
      var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
      var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
      if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { continue }
      if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) ||
          fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0))
        { return true }
    } }
  }

  // A visual line is a line as drawn on the screen. Folding, for
  // example, can cause multiple logical lines to appear on the same
  // visual line. This finds the start of the visual line that the
  // given line is part of (usually that is the line itself).
  function visualLine(line) {
    var merged;
    while (merged = collapsedSpanAtStart(line))
      { line = merged.find(-1, true).line; }
    return line
  }

  function visualLineEnd(line) {
    var merged;
    while (merged = collapsedSpanAtEnd(line))
      { line = merged.find(1, true).line; }
    return line
  }

  // Returns an array of logical lines that continue the visual line
  // started by the argument, or undefined if there are no such lines.
  function visualLineContinued(line) {
    var merged, lines;
    while (merged = collapsedSpanAtEnd(line)) {
      line = merged.find(1, true).line
      ;(lines || (lines = [])).push(line);
    }
    return lines
  }

  // Get the line number of the start of the visual line that the
  // given line number is part of.
  function visualLineNo(doc, lineN) {
    var line = getLine(doc, lineN), vis = visualLine(line);
    if (line == vis) { return lineN }
    return lineNo(vis)
  }

  // Get the line number of the start of the next visual line after
  // the given line.
  function visualLineEndNo(doc, lineN) {
    if (lineN > doc.lastLine()) { return lineN }
    var line = getLine(doc, lineN), merged;
    if (!lineIsHidden(doc, line)) { return lineN }
    while (merged = collapsedSpanAtEnd(line))
      { line = merged.find(1, true).line; }
    return lineNo(line) + 1
  }

  // Compute whether a line is hidden. Lines count as hidden when they
  // are part of a visual line that starts with another line, or when
  // they are entirely covered by collapsed, non-widget span.
  function lineIsHidden(doc, line) {
    var sps = sawCollapsedSpans && line.markedSpans;
    if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
      sp = sps[i];
      if (!sp.marker.collapsed) { continue }
      if (sp.from == null) { return true }
      if (sp.marker.widgetNode) { continue }
      if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
        { return true }
    } }
  }
  function lineIsHiddenInner(doc, line, span) {
    if (span.to == null) {
      var end = span.marker.find(1, true);
      return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker))
    }
    if (span.marker.inclusiveRight && span.to == line.text.length)
      { return true }
    for (var sp = (void 0), i = 0; i < line.markedSpans.length; ++i) {
      sp = line.markedSpans[i];
      if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
          (sp.to == null || sp.to != span.from) &&
          (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
          lineIsHiddenInner(doc, line, sp)) { return true }
    }
  }

  // Find the height above the given line.
  function heightAtLine(lineObj) {
    lineObj = visualLine(lineObj);

    var h = 0, chunk = lineObj.parent;
    for (var i = 0; i < chunk.lines.length; ++i) {
      var line = chunk.lines[i];
      if (line == lineObj) { break }
      else { h += line.height; }
    }
    for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
      for (var i$1 = 0; i$1 < p.children.length; ++i$1) {
        var cur = p.children[i$1];
        if (cur == chunk) { break }
        else { h += cur.height; }
      }
    }
    return h
  }

  // Compute the character length of a line, taking into account
  // collapsed ranges (see markText) that might hide parts, and join
  // other lines onto it.
  function lineLength(line) {
    if (line.height == 0) { return 0 }
    var len = line.text.length, merged, cur = line;
    while (merged = collapsedSpanAtStart(cur)) {
      var found = merged.find(0, true);
      cur = found.from.line;
      len += found.from.ch - found.to.ch;
    }
    cur = line;
    while (merged = collapsedSpanAtEnd(cur)) {
      var found$1 = merged.find(0, true);
      len -= cur.text.length - found$1.from.ch;
      cur = found$1.to.line;
      len += cur.text.length - found$1.to.ch;
    }
    return len
  }

  // Find the longest line in the document.
  function findMaxLine(cm) {
    var d = cm.display, doc = cm.doc;
    d.maxLine = getLine(doc, doc.first);
    d.maxLineLength = lineLength(d.maxLine);
    d.maxLineChanged = true;
    doc.iter(function (line) {
      var len = lineLength(line);
      if (len > d.maxLineLength) {
        d.maxLineLength = len;
        d.maxLine = line;
      }
    });
  }

  // LINE DATA STRUCTURE

  // Line objects. These hold state related to a line, including
  // highlighting info (the styles array).
  var Line = function(text, markedSpans, estimateHeight) {
    this.text = text;
    attachMarkedSpans(this, markedSpans);
    this.height = estimateHeight ? estimateHeight(this) : 1;
  };

  Line.prototype.lineNo = function () { return lineNo(this) };
  eventMixin(Line);

  // Change the content (text, markers) of a line. Automatically
  // invalidates cached information and tries to re-estimate the
  // line's height.
  function updateLine(line, text, markedSpans, estimateHeight) {
    line.text = text;
    if (line.stateAfter) { line.stateAfter = null; }
    if (line.styles) { line.styles = null; }
    if (line.order != null) { line.order = null; }
    detachMarkedSpans(line);
    attachMarkedSpans(line, markedSpans);
    var estHeight = estimateHeight ? estimateHeight(line) : 1;
    if (estHeight != line.height) { updateLineHeight(line, estHeight); }
  }

  // Detach a line from the document tree and its markers.
  function cleanUpLine(line) {
    line.parent = null;
    detachMarkedSpans(line);
  }

  // Convert a style as returned by a mode (either null, or a string
  // containing one or more styles) to a CSS style. This is cached,
  // and also looks for line-wide styles.
  var styleToClassCache = {}, styleToClassCacheWithMode = {};
  function interpretTokenStyle(style, options) {
    if (!style || /^\s*$/.test(style)) { return null }
    var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
    return cache[style] ||
      (cache[style] = style.replace(/\S+/g, "cm-$&"))
  }

  // Render the DOM representation of the text of a line. Also builds
  // up a 'line map', which points at the DOM nodes that represent
  // specific stretches of text, and is used by the measuring code.
  // The returned object contains the DOM node, this map, and
  // information about line-wide styles that were set by the mode.
  function buildLineContent(cm, lineView) {
    // The padding-right forces the element to have a 'border', which
    // is needed on Webkit to be able to get line-level bounding
    // rectangles for it (in measureChar).
    var content = eltP("span", null, null, webkit ? "padding-right: .1px" : null);
    var builder = {pre: eltP("pre", [content], "CodeMirror-line"), content: content,
                   col: 0, pos: 0, cm: cm,
                   trailingSpace: false,
                   splitSpaces: cm.getOption("lineWrapping")};
    lineView.measure = {};

    // Iterate over the logical lines that make up this visual line.
    for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
      var line = i ? lineView.rest[i - 1] : lineView.line, order = (void 0);
      builder.pos = 0;
      builder.addToken = buildToken;
      // Optionally wire in some hacks into the token-rendering
      // algorithm, to deal with browser quirks.
      if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction)))
        { builder.addToken = buildTokenBadBidi(builder.addToken, order); }
      builder.map = [];
      var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
      insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
      if (line.styleClasses) {
        if (line.styleClasses.bgClass)
          { builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || ""); }
        if (line.styleClasses.textClass)
          { builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || ""); }
      }

      // Ensure at least a single node is present, for measuring.
      if (builder.map.length == 0)
        { builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); }

      // Store the map and a cache object for the current logical line
      if (i == 0) {
        lineView.measure.map = builder.map;
        lineView.measure.cache = {};
      } else {
  (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map)
        ;(lineView.measure.caches || (lineView.measure.caches = [])).push({});
      }
    }

    // See issue #2901
    if (webkit) {
      var last = builder.content.lastChild;
      if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab")))
        { builder.content.className = "cm-tab-wrap-hack"; }
    }

    signal(cm, "renderLine", cm, lineView.line, builder.pre);
    if (builder.pre.className)
      { builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); }

    return builder
  }

  function defaultSpecialCharPlaceholder(ch) {
    var token = elt("span", "\u2022", "cm-invalidchar");
    token.title = "\\u" + ch.charCodeAt(0).toString(16);
    token.setAttribute("aria-label", token.title);
    return token
  }

  // Build up the DOM representation for a single token, and add it to
  // the line map. Takes care to render special characters separately.
  function buildToken(builder, text, style, startStyle, endStyle, css, attributes) {
    if (!text) { return }
    var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text;
    var special = builder.cm.state.specialChars, mustWrap = false;
    var content;
    if (!special.test(text)) {
      builder.col += text.length;
      content = document.createTextNode(displayText);
      builder.map.push(builder.pos, builder.pos + text.length, content);
      if (ie && ie_version < 9) { mustWrap = true; }
      builder.pos += text.length;
    } else {
      content = document.createDocumentFragment();
      var pos = 0;
      while (true) {
        special.lastIndex = pos;
        var m = special.exec(text);
        var skipped = m ? m.index - pos : text.length - pos;
        if (skipped) {
          var txt = document.createTextNode(displayText.slice(pos, pos + skipped));
          if (ie && ie_version < 9) { content.appendChild(elt("span", [txt])); }
          else { content.appendChild(txt); }
          builder.map.push(builder.pos, builder.pos + skipped, txt);
          builder.col += skipped;
          builder.pos += skipped;
        }
        if (!m) { break }
        pos += skipped + 1;
        var txt$1 = (void 0);
        if (m[0] == "\t") {
          var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
          txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
          txt$1.setAttribute("role", "presentation");
          txt$1.setAttribute("cm-text", "\t");
          builder.col += tabWidth;
        } else if (m[0] == "\r" || m[0] == "\n") {
          txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar"));
          txt$1.setAttribute("cm-text", m[0]);
          builder.col += 1;
        } else {
          txt$1 = builder.cm.options.specialCharPlaceholder(m[0]);
          txt$1.setAttribute("cm-text", m[0]);
          if (ie && ie_version < 9) { content.appendChild(elt("span", [txt$1])); }
          else { content.appendChild(txt$1); }
          builder.col += 1;
        }
        builder.map.push(builder.pos, builder.pos + 1, txt$1);
        builder.pos++;
      }
    }
    builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32;
    if (style || startStyle || endStyle || mustWrap || css || attributes) {
      var fullStyle = style || "";
      if (startStyle) { fullStyle += startStyle; }
      if (endStyle) { fullStyle += endStyle; }
      var token = elt("span", [content], fullStyle, css);
      if (attributes) {
        for (var attr in attributes) { if (attributes.hasOwnProperty(attr) && attr != "style" && attr != "class")
          { token.setAttribute(attr, attributes[attr]); } }
      }
      return builder.content.appendChild(token)
    }
    builder.content.appendChild(content);
  }

  // Change some spaces to NBSP to prevent the browser from collapsing
  // trailing spaces at the end of a line when rendering text (issue #1362).
  function splitSpaces(text, trailingBefore) {
    if (text.length > 1 && !/  /.test(text)) { return text }
    var spaceBefore = trailingBefore, result = "";
    for (var i = 0; i < text.length; i++) {
      var ch = text.charAt(i);
      if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32))
        { ch = "\u00a0"; }
      result += ch;
      spaceBefore = ch == " ";
    }
    return result
  }

  // Work around nonsense dimensions being reported for stretches of
  // right-to-left text.
  function buildTokenBadBidi(inner, order) {
    return function (builder, text, style, startStyle, endStyle, css, attributes) {
      style = style ? style + " cm-force-border" : "cm-force-border";
      var start = builder.pos, end = start + text.length;
      for (;;) {
        // Find the part that overlaps with the start of this text
        var part = (void 0);
        for (var i = 0; i < order.length; i++) {
          part = order[i];
          if (part.to > start && part.from <= start) { break }
        }
        if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, css, attributes) }
        inner(builder, text.slice(0, part.to - start), style, startStyle, null, css, attributes);
        startStyle = null;
        text = text.slice(part.to - start);
        start = part.to;
      }
    }
  }

  function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
    var widget = !ignoreWidget && marker.widgetNode;
    if (widget) { builder.map.push(builder.pos, builder.pos + size, widget); }
    if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
      if (!widget)
        { widget = builder.content.appendChild(document.createElement("span")); }
      widget.setAttribute("cm-marker", marker.id);
    }
    if (widget) {
      builder.cm.display.input.setUneditable(widget);
      builder.content.appendChild(widget);
    }
    builder.pos += size;
    builder.trailingSpace = false;
  }

  // Outputs a number of spans to make up a line, taking highlighting
  // and marked text into account.
  function insertLineContent(line, builder, styles) {
    var spans = line.markedSpans, allText = line.text, at = 0;
    if (!spans) {
      for (var i$1 = 1; i$1 < styles.length; i$1+=2)
        { builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1+1], builder.cm.options)); }
      return
    }

    var len = allText.length, pos = 0, i = 1, text = "", style, css;
    var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, collapsed, attributes;
    for (;;) {
      if (nextChange == pos) { // Update current marker set
        spanStyle = spanEndStyle = spanStartStyle = css = "";
        attributes = null;
        collapsed = null; nextChange = Infinity;
        var foundBookmarks = [], endStyles = (void 0);
        for (var j = 0; j < spans.length; ++j) {
          var sp = spans[j], m = sp.marker;
          if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
            foundBookmarks.push(m);
          } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
            if (sp.to != null && sp.to != pos && nextChange > sp.to) {
              nextChange = sp.to;
              spanEndStyle = "";
            }
            if (m.className) { spanStyle += " " + m.className; }
            if (m.css) { css = (css ? css + ";" : "") + m.css; }
            if (m.startStyle && sp.from == pos) { spanStartStyle += " " + m.startStyle; }
            if (m.endStyle && sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to); }
            // support for the old title property
            // https://github.com/codemirror/CodeMirror/pull/5673
            if (m.title) { (attributes || (attributes = {})).title = m.title; }
            if (m.attributes) {
              for (var attr in m.attributes)
                { (attributes || (attributes = {}))[attr] = m.attributes[attr]; }
            }
            if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
              { collapsed = sp; }
          } else if (sp.from > pos && nextChange > sp.from) {
            nextChange = sp.from;
          }
        }
        if (endStyles) { for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2)
          { if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += " " + endStyles[j$1]; } } }

        if (!collapsed || collapsed.from == pos) { for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2)
          { buildCollapsedSpan(builder, 0, foundBookmarks[j$2]); } }
        if (collapsed && (collapsed.from || 0) == pos) {
          buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
                             collapsed.marker, collapsed.from == null);
          if (collapsed.to == null) { return }
          if (collapsed.to == pos) { collapsed = false; }
        }
      }
      if (pos >= len) { break }

      var upto = Math.min(len, nextChange);
      while (true) {
        if (text) {
          var end = pos + text.length;
          if (!collapsed) {
            var tokenText = end > upto ? text.slice(0, upto - pos) : text;
            builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
                             spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", css, attributes);
          }
          if (end >= upto) {text = text.slice(upto - pos); pos = upto; break}
          pos = end;
          spanStartStyle = "";
        }
        text = allText.slice(at, at = styles[i++]);
        style = interpretTokenStyle(styles[i++], builder.cm.options);
      }
    }
  }


  // These objects are used to represent the visible (currently drawn)
  // part of the document. A LineView may correspond to multiple
  // logical lines, if those are connected by collapsed ranges.
  function LineView(doc, line, lineN) {
    // The starting line
    this.line = line;
    // Continuing lines, if any
    this.rest = visualLineContinued(line);
    // Number of logical lines in this visual line
    this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
    this.node = this.text = null;
    this.hidden = lineIsHidden(doc, line);
  }

  // Create a range of LineView objects for the given lines.
  function buildViewArray(cm, from, to) {
    var array = [], nextPos;
    for (var pos = from; pos < to; pos = nextPos) {
      var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
      nextPos = pos + view.size;
      array.push(view);
    }
    return array
  }

  var operationGroup = null;

  function pushOperation(op) {
    if (operationGroup) {
      operationGroup.ops.push(op);
    } else {
      op.ownsGroup = operationGroup = {
        ops: [op],
        delayedCallbacks: []
      };
    }
  }

  function fireCallbacksForOps(group) {
    // Calls delayed callbacks and cursorActivity handlers until no
    // new ones appear
    var callbacks = group.delayedCallbacks, i = 0;
    do {
      for (; i < callbacks.length; i++)
        { callbacks[i].call(null); }
      for (var j = 0; j < group.ops.length; j++) {
        var op = group.ops[j];
        if (op.cursorActivityHandlers)
          { while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
            { op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm); } }
      }
    } while (i < callbacks.length)
  }

  function finishOperation(op, endCb) {
    var group = op.ownsGroup;
    if (!group) { return }

    try { fireCallbacksForOps(group); }
    finally {
      operationGroup = null;
      endCb(group);
    }
  }

  var orphanDelayedCallbacks = null;

  // Often, we want to signal events at a point where we are in the
  // middle of some work, but don't want the handler to start calling
  // other methods on the editor, which might be in an inconsistent
  // state or simply not expect any other events to happen.
  // signalLater looks whether there are any handlers, and schedules
  // them to be executed when the last operation ends, or, if no
  // operation is active, when a timeout fires.
  function signalLater(emitter, type /*, values...*/) {
    var arr = getHandlers(emitter, type);
    if (!arr.length) { return }
    var args = Array.prototype.slice.call(arguments, 2), list;
    if (operationGroup) {
      list = operationGroup.delayedCallbacks;
    } else if (orphanDelayedCallbacks) {
      list = orphanDelayedCallbacks;
    } else {
      list = orphanDelayedCallbacks = [];
      setTimeout(fireOrphanDelayed, 0);
    }
    var loop = function ( i ) {
      list.push(function () { return arr[i].apply(null, args); });
    };

    for (var i = 0; i < arr.length; ++i)
      loop( i );
  }

  function fireOrphanDelayed() {
    var delayed = orphanDelayedCallbacks;
    orphanDelayedCallbacks = null;
    for (var i = 0; i < delayed.length; ++i) { delayed[i](); }
  }

  // When an aspect of a line changes, a string is added to
  // lineView.changes. This updates the relevant part of the line's
  // DOM structure.
  function updateLineForChanges(cm, lineView, lineN, dims) {
    for (var j = 0; j < lineView.changes.length; j++) {
      var type = lineView.changes[j];
      if (type == "text") { updateLineText(cm, lineView); }
      else if (type == "gutter") { updateLineGutter(cm, lineView, lineN, dims); }
      else if (type == "class") { updateLineClasses(cm, lineView); }
      else if (type == "widget") { updateLineWidgets(cm, lineView, dims); }
    }
    lineView.changes = null;
  }

  // Lines with gutter elements, widgets or a background class need to
  // be wrapped, and have the extra elements added to the wrapper div
  function ensureLineWrapped(lineView) {
    if (lineView.node == lineView.text) {
      lineView.node = elt("div", null, null, "position: relative");
      if (lineView.text.parentNode)
        { lineView.text.parentNode.replaceChild(lineView.node, lineView.text); }
      lineView.node.appendChild(lineView.text);
      if (ie && ie_version < 8) { lineView.node.style.zIndex = 2; }
    }
    return lineView.node
  }

  function updateLineBackground(cm, lineView) {
    var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
    if (cls) { cls += " CodeMirror-linebackground"; }
    if (lineView.background) {
      if (cls) { lineView.background.className = cls; }
      else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }
    } else if (cls) {
      var wrap = ensureLineWrapped(lineView);
      lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
      cm.display.input.setUneditable(lineView.background);
    }
  }

  // Wrapper around buildLineContent which will reuse the structure
  // in display.externalMeasured when possible.
  function getLineContent(cm, lineView) {
    var ext = cm.display.externalMeasured;
    if (ext && ext.line == lineView.line) {
      cm.display.externalMeasured = null;
      lineView.measure = ext.measure;
      return ext.built
    }
    return buildLineContent(cm, lineView)
  }

  // Redraw the line's text. Interacts with the background and text
  // classes because the mode may output tokens that influence these
  // classes.
  function updateLineText(cm, lineView) {
    var cls = lineView.text.className;
    var built = getLineContent(cm, lineView);
    if (lineView.text == lineView.node) { lineView.node = built.pre; }
    lineView.text.parentNode.replaceChild(built.pre, lineView.text);
    lineView.text = built.pre;
    if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
      lineView.bgClass = built.bgClass;
      lineView.textClass = built.textClass;
      updateLineClasses(cm, lineView);
    } else if (cls) {
      lineView.text.className = cls;
    }
  }

  function updateLineClasses(cm, lineView) {
    updateLineBackground(cm, lineView);
    if (lineView.line.wrapClass)
      { ensureLineWrapped(lineView).className = lineView.line.wrapClass; }
    else if (lineView.node != lineView.text)
      { lineView.node.className = ""; }
    var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
    lineView.text.className = textClass || "";
  }

  function updateLineGutter(cm, lineView, lineN, dims) {
    if (lineView.gutter) {
      lineView.node.removeChild(lineView.gutter);
      lineView.gutter = null;
    }
    if (lineView.gutterBackground) {
      lineView.node.removeChild(lineView.gutterBackground);
      lineView.gutterBackground = null;
    }
    if (lineView.line.gutterClass) {
      var wrap = ensureLineWrapped(lineView);
      lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass,
                                      ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + (dims.gutterTotalWidth) + "px"));
      cm.display.input.setUneditable(lineView.gutterBackground);
      wrap.insertBefore(lineView.gutterBackground, lineView.text);
    }
    var markers = lineView.line.gutterMarkers;
    if (cm.options.lineNumbers || markers) {
      var wrap$1 = ensureLineWrapped(lineView);
      var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"));
      gutterWrap.setAttribute("aria-hidden", "true");
      cm.display.input.setUneditable(gutterWrap);
      wrap$1.insertBefore(gutterWrap, lineView.text);
      if (lineView.line.gutterClass)
        { gutterWrap.className += " " + lineView.line.gutterClass; }
      if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
        { lineView.lineNumber = gutterWrap.appendChild(
          elt("div", lineNumberFor(cm.options, lineN),
              "CodeMirror-linenumber CodeMirror-gutter-elt",
              ("left: " + (dims.gutterLeft["CodeMirror-linenumbers"]) + "px; width: " + (cm.display.lineNumInnerWidth) + "px"))); }
      if (markers) { for (var k = 0; k < cm.display.gutterSpecs.length; ++k) {
        var id = cm.display.gutterSpecs[k].className, found = markers.hasOwnProperty(id) && markers[id];
        if (found)
          { gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt",
                                     ("left: " + (dims.gutterLeft[id]) + "px; width: " + (dims.gutterWidth[id]) + "px"))); }
      } }
    }
  }

  function updateLineWidgets(cm, lineView, dims) {
    if (lineView.alignable) { lineView.alignable = null; }
    var isWidget = classTest("CodeMirror-linewidget");
    for (var node = lineView.node.firstChild, next = (void 0); node; node = next) {
      next = node.nextSibling;
      if (isWidget.test(node.className)) { lineView.node.removeChild(node); }
    }
    insertLineWidgets(cm, lineView, dims);
  }

  // Build a line's DOM representation from scratch
  function buildLineElement(cm, lineView, lineN, dims) {
    var built = getLineContent(cm, lineView);
    lineView.text = lineView.node = built.pre;
    if (built.bgClass) { lineView.bgClass = built.bgClass; }
    if (built.textClass) { lineView.textClass = built.textClass; }

    updateLineClasses(cm, lineView);
    updateLineGutter(cm, lineView, lineN, dims);
    insertLineWidgets(cm, lineView, dims);
    return lineView.node
  }

  // A lineView may contain multiple logical lines (when merged by
  // collapsed spans). The widgets for all of them need to be drawn.
  function insertLineWidgets(cm, lineView, dims) {
    insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);
    if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
      { insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false); } }
  }

  function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
    if (!line.widgets) { return }
    var wrap = ensureLineWrapped(lineView);
    for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
      var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget" + (widget.className ? " " + widget.className : ""));
      if (!widget.handleMouseEvents) { node.setAttribute("cm-ignore-events", "true"); }
      positionLineWidget(widget, node, lineView, dims);
      cm.display.input.setUneditable(node);
      if (allowAbove && widget.above)
        { wrap.insertBefore(node, lineView.gutter || lineView.text); }
      else
        { wrap.appendChild(node); }
      signalLater(widget, "redraw");
    }
  }

  function positionLineWidget(widget, node, lineView, dims) {
    if (widget.noHScroll) {
  (lineView.alignable || (lineView.alignable = [])).push(node);
      var width = dims.wrapperWidth;
      node.style.left = dims.fixedPos + "px";
      if (!widget.coverGutter) {
        width -= dims.gutterTotalWidth;
        node.style.paddingLeft = dims.gutterTotalWidth + "px";
      }
      node.style.width = width + "px";
    }
    if (widget.coverGutter) {
      node.style.zIndex = 5;
      node.style.position = "relative";
      if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + "px"; }
    }
  }

  function widgetHeight(widget) {
    if (widget.height != null) { return widget.height }
    var cm = widget.doc.cm;
    if (!cm) { return 0 }
    if (!contains(document.body, widget.node)) {
      var parentStyle = "position: relative;";
      if (widget.coverGutter)
        { parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;"; }
      if (widget.noHScroll)
        { parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;"; }
      removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle));
    }
    return widget.height = widget.node.parentNode.offsetHeight
  }

  // Return true when the given mouse event happened in a widget
  function eventInWidget(display, e) {
    for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
      if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
          (n.parentNode == display.sizer && n != display.mover))
        { return true }
    }
  }

  // POSITION MEASUREMENT

  function paddingTop(display) {return display.lineSpace.offsetTop}
  function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight}
  function paddingH(display) {
    if (display.cachedPaddingH) { return display.cachedPaddingH }
    var e = removeChildrenAndAdd(display.measure, elt("pre", "x", "CodeMirror-line-like"));
    var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
    var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};
    if (!isNaN(data.left) && !isNaN(data.right)) { display.cachedPaddingH = data; }
    return data
  }

  function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth }
  function displayWidth(cm) {
    return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth
  }
  function displayHeight(cm) {
    return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight
  }

  // Ensure the lineView.wrapping.heights array is populated. This is
  // an array of bottom offsets for the lines that make up a drawn
  // line. When lineWrapping is on, there might be more than one
  // height.
  function ensureLineHeights(cm, lineView, rect) {
    var wrapping = cm.options.lineWrapping;
    var curWidth = wrapping && displayWidth(cm);
    if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
      var heights = lineView.measure.heights = [];
      if (wrapping) {
        lineView.measure.width = curWidth;
        var rects = lineView.text.firstChild.getClientRects();
        for (var i = 0; i < rects.length - 1; i++) {
          var cur = rects[i], next = rects[i + 1];
          if (Math.abs(cur.bottom - next.bottom) > 2)
            { heights.push((cur.bottom + next.top) / 2 - rect.top); }
        }
      }
      heights.push(rect.bottom - rect.top);
    }
  }

  // Find a line map (mapping character offsets to text nodes) and a
  // measurement cache for the given line number. (A line view might
  // contain multiple lines when collapsed ranges are present.)
  function mapFromLineView(lineView, line, lineN) {
    if (lineView.line == line)
      { return {map: lineView.measure.map, cache: lineView.measure.cache} }
    if (lineView.rest) {
      for (var i = 0; i < lineView.rest.length; i++)
        { if (lineView.rest[i] == line)
          { return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]} } }
      for (var i$1 = 0; i$1 < lineView.rest.length; i$1++)
        { if (lineNo(lineView.rest[i$1]) > lineN)
          { return {map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], before: true} } }
    }
  }

  // Render a line into the hidden node display.externalMeasured. Used
  // when measurement is needed for a line that's not in the viewport.
  function updateExternalMeasurement(cm, line) {
    line = visualLine(line);
    var lineN = lineNo(line);
    var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
    view.lineN = lineN;
    var built = view.built = buildLineContent(cm, view);
    view.text = built.pre;
    removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
    return view
  }

  // Get a {top, bottom, left, right} box (in line-local coordinates)
  // for a given character.
  function measureChar(cm, line, ch, bias) {
    return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias)
  }

  // Find a line view that corresponds to the given line number.
  function findViewForLine(cm, lineN) {
    if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
      { return cm.display.view[findViewIndex(cm, lineN)] }
    var ext = cm.display.externalMeasured;
    if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
      { return ext }
  }

  // Measurement can be split in two steps, the set-up work that
  // applies to the whole line, and the measurement of the actual
  // character. Functions like coordsChar, that need to do a lot of
  // measurements in a row, can thus ensure that the set-up work is
  // only done once.
  function prepareMeasureForLine(cm, line) {
    var lineN = lineNo(line);
    var view = findViewForLine(cm, lineN);
    if (view && !view.text) {
      view = null;
    } else if (view && view.changes) {
      updateLineForChanges(cm, view, lineN, getDimensions(cm));
      cm.curOp.forceUpdate = true;
    }
    if (!view)
      { view = updateExternalMeasurement(cm, line); }

    var info = mapFromLineView(view, line, lineN);
    return {
      line: line, view: view, rect: null,
      map: info.map, cache: info.cache, before: info.before,
      hasHeights: false
    }
  }

  // Given a prepared measurement object, measures the position of an
  // actual character (or fetches it from the cache).
  function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
    if (prepared.before) { ch = -1; }
    var key = ch + (bias || ""), found;
    if (prepared.cache.hasOwnProperty(key)) {
      found = prepared.cache[key];
    } else {
      if (!prepared.rect)
        { prepared.rect = prepared.view.text.getBoundingClientRect(); }
      if (!prepared.hasHeights) {
        ensureLineHeights(cm, prepared.view, prepared.rect);
        prepared.hasHeights = true;
      }
      found = measureCharInner(cm, prepared, ch, bias);
      if (!found.bogus) { prepared.cache[key] = found; }
    }
    return {left: found.left, right: found.right,
            top: varHeight ? found.rtop : found.top,
            bottom: varHeight ? found.rbottom : found.bottom}
  }

  var nullRect = {left: 0, right: 0, top: 0, bottom: 0};

  function nodeAndOffsetInLineMap(map, ch, bias) {
    var node, start, end, collapse, mStart, mEnd;
    // First, search the line map for the text node corresponding to,
    // or closest to, the target character.
    for (var i = 0; i < map.length; i += 3) {
      mStart = map[i];
      mEnd = map[i + 1];
      if (ch < mStart) {
        start = 0; end = 1;
        collapse = "left";
      } else if (ch < mEnd) {
        start = ch - mStart;
        end = start + 1;
      } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) {
        end = mEnd - mStart;
        start = end - 1;
        if (ch >= mEnd) { collapse = "right"; }
      }
      if (start != null) {
        node = map[i + 2];
        if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
          { collapse = bias; }
        if (bias == "left" && start == 0)
          { while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) {
            node = map[(i -= 3) + 2];
            collapse = "left";
          } }
        if (bias == "right" && start == mEnd - mStart)
          { while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) {
            node = map[(i += 3) + 2];
            collapse = "right";
          } }
        break
      }
    }
    return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd}
  }

  function getUsefulRect(rects, bias) {
    var rect = nullRect;
    if (bias == "left") { for (var i = 0; i < rects.length; i++) {
      if ((rect = rects[i]).left != rect.right) { break }
    } } else { for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) {
      if ((rect = rects[i$1]).left != rect.right) { break }
    } }
    return rect
  }

  function measureCharInner(cm, prepared, ch, bias) {
    var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);
    var node = place.node, start = place.start, end = place.end, collapse = place.collapse;

    var rect;
    if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
      for (var i$1 = 0; i$1 < 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned
        while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { --start; }
        while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { ++end; }
        if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart)
          { rect = node.parentNode.getBoundingClientRect(); }
        else
          { rect = getUsefulRect(range(node, start, end).getClientRects(), bias); }
        if (rect.left || rect.right || start == 0) { break }
        end = start;
        start = start - 1;
        collapse = "right";
      }
      if (ie && ie_version < 11) { rect = maybeUpdateRectForZooming(cm.display.measure, rect); }
    } else { // If it is a widget, simply get the box for the whole widget.
      if (start > 0) { collapse = bias = "right"; }
      var rects;
      if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
        { rect = rects[bias == "right" ? rects.length - 1 : 0]; }
      else
        { rect = node.getBoundingClientRect(); }
    }
    if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
      var rSpan = node.parentNode.getClientRects()[0];
      if (rSpan)
        { rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom}; }
      else
        { rect = nullRect; }
    }

    var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;
    var mid = (rtop + rbot) / 2;
    var heights = prepared.view.measure.heights;
    var i = 0;
    for (; i < heights.length - 1; i++)
      { if (mid < heights[i]) { break } }
    var top = i ? heights[i - 1] : 0, bot = heights[i];
    var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
                  right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
                  top: top, bottom: bot};
    if (!rect.left && !rect.right) { result.bogus = true; }
    if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }

    return result
  }

  // Work around problem with bounding client rects on ranges being
  // returned incorrectly when zoomed on IE10 and below.
  function maybeUpdateRectForZooming(measure, rect) {
    if (!window.screen || screen.logicalXDPI == null ||
        screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
      { return rect }
    var scaleX = screen.logicalXDPI / screen.deviceXDPI;
    var scaleY = screen.logicalYDPI / screen.deviceYDPI;
    return {left: rect.left * scaleX, right: rect.right * scaleX,
            top: rect.top * scaleY, bottom: rect.bottom * scaleY}
  }

  function clearLineMeasurementCacheFor(lineView) {
    if (lineView.measure) {
      lineView.measure.cache = {};
      lineView.measure.heights = null;
      if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
        { lineView.measure.caches[i] = {}; } }
    }
  }

  function clearLineMeasurementCache(cm) {
    cm.display.externalMeasure = null;
    removeChildren(cm.display.lineMeasure);
    for (var i = 0; i < cm.display.view.length; i++)
      { clearLineMeasurementCacheFor(cm.display.view[i]); }
  }

  function clearCaches(cm) {
    clearLineMeasurementCache(cm);
    cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
    if (!cm.options.lineWrapping) { cm.display.maxLineChanged = true; }
    cm.display.lineNumChars = null;
  }

  function pageScrollX(doc) {
    // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206
    // which causes page_Offset and bounding client rects to use
    // different reference viewports and invalidate our calculations.
    if (chrome && android) { return -(doc.body.getBoundingClientRect().left - parseInt(getComputedStyle(doc.body).marginLeft)) }
    return doc.defaultView.pageXOffset || (doc.documentElement || doc.body).scrollLeft
  }
  function pageScrollY(doc) {
    if (chrome && android) { return -(doc.body.getBoundingClientRect().top - parseInt(getComputedStyle(doc.body).marginTop)) }
    return doc.defaultView.pageYOffset || (doc.documentElement || doc.body).scrollTop
  }

  function widgetTopHeight(lineObj) {
    var ref = visualLine(lineObj);
    var widgets = ref.widgets;
    var height = 0;
    if (widgets) { for (var i = 0; i < widgets.length; ++i) { if (widgets[i].above)
      { height += widgetHeight(widgets[i]); } } }
    return height
  }

  // Converts a {top, bottom, left, right} box from line-local
  // coordinates into another coordinate system. Context may be one of
  // "line", "div" (display.lineDiv), "local"./null (editor), "window",
  // or "page".
  function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) {
    if (!includeWidgets) {
      var height = widgetTopHeight(lineObj);
      rect.top += height; rect.bottom += height;
    }
    if (context == "line") { return rect }
    if (!context) { context = "local"; }
    var yOff = heightAtLine(lineObj);
    if (context == "local") { yOff += paddingTop(cm.display); }
    else { yOff -= cm.display.viewOffset; }
    if (context == "page" || context == "window") {
      var lOff = cm.display.lineSpace.getBoundingClientRect();
      yOff += lOff.top + (context == "window" ? 0 : pageScrollY(doc(cm)));
      var xOff = lOff.left + (context == "window" ? 0 : pageScrollX(doc(cm)));
      rect.left += xOff; rect.right += xOff;
    }
    rect.top += yOff; rect.bottom += yOff;
    return rect
  }

  // Coverts a box from "div" coords to another coordinate system.
  // Context may be "window", "page", "div", or "local"./null.
  function fromCoordSystem(cm, coords, context) {
    if (context == "div") { return coords }
    var left = coords.left, top = coords.top;
    // First move into "page" coordinate system
    if (context == "page") {
      left -= pageScrollX(doc(cm));
      top -= pageScrollY(doc(cm));
    } else if (context == "local" || !context) {
      var localBox = cm.display.sizer.getBoundingClientRect();
      left += localBox.left;
      top += localBox.top;
    }

    var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
    return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}
  }

  function charCoords(cm, pos, context, lineObj, bias) {
    if (!lineObj) { lineObj = getLine(cm.doc, pos.line); }
    return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context)
  }

  // Returns a box for a given cursor position, which may have an
  // 'other' property containing the position of the secondary cursor
  // on a bidi boundary.
  // A cursor Pos(line, char, "before") is on the same visual line as `char - 1`
  // and after `char - 1` in writing order of `char - 1`
  // A cursor Pos(line, char, "after") is on the same visual line as `char`
  // and before `char` in writing order of `char`
  // Examples (upper-case letters are RTL, lower-case are LTR):
  //     Pos(0, 1, ...)
  //     before   after
  // ab     a|b     a|b
  // aB     a|B     aB|
  // Ab     |Ab     A|b
  // AB     B|A     B|A
  // Every position after the last character on a line is considered to stick
  // to the last character on the line.
  function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
    lineObj = lineObj || getLine(cm.doc, pos.line);
    if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
    function get(ch, right) {
      var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight);
      if (right) { m.left = m.right; } else { m.right = m.left; }
      return intoCoordSystem(cm, lineObj, m, context)
    }
    var order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky;
    if (ch >= lineObj.text.length) {
      ch = lineObj.text.length;
      sticky = "before";
    } else if (ch <= 0) {
      ch = 0;
      sticky = "after";
    }
    if (!order) { return get(sticky == "before" ? ch - 1 : ch, sticky == "before") }

    function getBidi(ch, partPos, invert) {
      var part = order[partPos], right = part.level == 1;
      return get(invert ? ch - 1 : ch, right != invert)
    }
    var partPos = getBidiPartAt(order, ch, sticky);
    var other = bidiOther;
    var val = getBidi(ch, partPos, sticky == "before");
    if (other != null) { val.other = getBidi(ch, other, sticky != "before"); }
    return val
  }

  // Used to cheaply estimate the coordinates for a position. Used for
  // intermediate scroll updates.
  function estimateCoords(cm, pos) {
    var left = 0;
    pos = clipPos(cm.doc, pos);
    if (!cm.options.lineWrapping) { left = charWidth(cm.display) * pos.ch; }
    var lineObj = getLine(cm.doc, pos.line);
    var top = heightAtLine(lineObj) + paddingTop(cm.display);
    return {left: left, right: left, top: top, bottom: top + lineObj.height}
  }

  // Positions returned by coordsChar contain some extra information.
  // xRel is the relative x position of the input coordinates compared
  // to the found position (so xRel > 0 means the coordinates are to
  // the right of the character position, for example). When outside
  // is true, that means the coordinates lie outside the line's
  // vertical range.
  function PosWithInfo(line, ch, sticky, outside, xRel) {
    var pos = Pos(line, ch, sticky);
    pos.xRel = xRel;
    if (outside) { pos.outside = outside; }
    return pos
  }

  // Compute the character position closest to the given coordinates.
  // Input must be lineSpace-local ("div" coordinate system).
  function coordsChar(cm, x, y) {
    var doc = cm.doc;
    y += cm.display.viewOffset;
    if (y < 0) { return PosWithInfo(doc.first, 0, null, -1, -1) }
    var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
    if (lineN > last)
      { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, 1, 1) }
    if (x < 0) { x = 0; }

    var lineObj = getLine(doc, lineN);
    for (;;) {
      var found = coordsCharInner(cm, lineObj, lineN, x, y);
      var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 || found.outside > 0 ? 1 : 0));
      if (!collapsed) { return found }
      var rangeEnd = collapsed.find(1);
      if (rangeEnd.line == lineN) { return rangeEnd }
      lineObj = getLine(doc, lineN = rangeEnd.line);
    }
  }

  function wrappedLineExtent(cm, lineObj, preparedMeasure, y) {
    y -= widgetTopHeight(lineObj);
    var end = lineObj.text.length;
    var begin = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y; }, end, 0);
    end = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch).top > y; }, begin, end);
    return {begin: begin, end: end}
  }

  function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) {
    if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
    var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top;
    return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop)
  }

  // Returns true if the given side of a box is after the given
  // coordinates, in top-to-bottom, left-to-right order.
  function boxIsAfter(box, x, y, left) {
    return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x
  }

  function coordsCharInner(cm, lineObj, lineNo, x, y) {
    // Move y into line-local coordinate space
    y -= heightAtLine(lineObj);
    var preparedMeasure = prepareMeasureForLine(cm, lineObj);
    // When directly calling `measureCharPrepared`, we have to adjust
    // for the widgets at this line.
    var widgetHeight = widgetTopHeight(lineObj);
    var begin = 0, end = lineObj.text.length, ltr = true;

    var order = getOrder(lineObj, cm.doc.direction);
    // If the line isn't plain left-to-right text, first figure out
    // which bidi section the coordinates fall into.
    if (order) {
      var part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart)
                   (cm, lineObj, lineNo, preparedMeasure, order, x, y);
      ltr = part.level != 1;
      // The awkward -1 offsets are needed because findFirst (called
      // on these below) will treat its first bound as inclusive,
      // second as exclusive, but we want to actually address the
      // characters in the part's range
      begin = ltr ? part.from : part.to - 1;
      end = ltr ? part.to : part.from - 1;
    }

    // A binary search to find the first character whose bounding box
    // starts after the coordinates. If we run across any whose box wrap
    // the coordinates, store that.
    var chAround = null, boxAround = null;
    var ch = findFirst(function (ch) {
      var box = measureCharPrepared(cm, preparedMeasure, ch);
      box.top += widgetHeight; box.bottom += widgetHeight;
      if (!boxIsAfter(box, x, y, false)) { return false }
      if (box.top <= y && box.left <= x) {
        chAround = ch;
        boxAround = box;
      }
      return true
    }, begin, end);

    var baseX, sticky, outside = false;
    // If a box around the coordinates was found, use that
    if (boxAround) {
      // Distinguish coordinates nearer to the left or right side of the box
      var atLeft = x - boxAround.left < boxAround.right - x, atStart = atLeft == ltr;
      ch = chAround + (atStart ? 0 : 1);
      sticky = atStart ? "after" : "before";
      baseX = atLeft ? boxAround.left : boxAround.right;
    } else {
      // (Adjust for extended bound, if necessary.)
      if (!ltr && (ch == end || ch == begin)) { ch++; }
      // To determine which side to associate with, get the box to the
      // left of the character and compare it's vertical position to the
      // coordinates
      sticky = ch == 0 ? "after" : ch == lineObj.text.length ? "before" :
        (measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight <= y) == ltr ?
        "after" : "before";
      // Now get accurate coordinates for this place, in order to get a
      // base X position
      var coords = cursorCoords(cm, Pos(lineNo, ch, sticky), "line", lineObj, preparedMeasure);
      baseX = coords.left;
      outside = y < coords.top ? -1 : y >= coords.bottom ? 1 : 0;
    }

    ch = skipExtendingChars(lineObj.text, ch, 1);
    return PosWithInfo(lineNo, ch, sticky, outside, x - baseX)
  }

  function coordsBidiPart(cm, lineObj, lineNo, preparedMeasure, order, x, y) {
    // Bidi parts are sorted left-to-right, and in a non-line-wrapping
    // situation, we can take this ordering to correspond to the visual
    // ordering. This finds the first part whose end is after the given
    // coordinates.
    var index = findFirst(function (i) {
      var part = order[i], ltr = part.level != 1;
      return boxIsAfter(cursorCoords(cm, Pos(lineNo, ltr ? part.to : part.from, ltr ? "before" : "after"),
                                     "line", lineObj, preparedMeasure), x, y, true)
    }, 0, order.length - 1);
    var part = order[index];
    // If this isn't the first part, the part's start is also after
    // the coordinates, and the coordinates aren't on the same line as
    // that start, move one part back.
    if (index > 0) {
      var ltr = part.level != 1;
      var start = cursorCoords(cm, Pos(lineNo, ltr ? part.from : part.to, ltr ? "after" : "before"),
                               "line", lineObj, preparedMeasure);
      if (boxIsAfter(start, x, y, true) && start.top > y)
        { part = order[index - 1]; }
    }
    return part
  }

  function coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x, y) {
    // In a wrapped line, rtl text on wrapping boundaries can do things
    // that don't correspond to the ordering in our `order` array at
    // all, so a binary search doesn't work, and we want to return a
    // part that only spans one line so that the binary search in
    // coordsCharInner is safe. As such, we first find the extent of the
    // wrapped line, and then do a flat search in which we discard any
    // spans that aren't on the line.
    var ref = wrappedLineExtent(cm, lineObj, preparedMeasure, y);
    var begin = ref.begin;
    var end = ref.end;
    if (/\s/.test(lineObj.text.charAt(end - 1))) { end--; }
    var part = null, closestDist = null;
    for (var i = 0; i < order.length; i++) {
      var p = order[i];
      if (p.from >= end || p.to <= begin) { continue }
      var ltr = p.level != 1;
      var endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right;
      // Weigh against spans ending before this, so that they are only
      // picked if nothing ends after
      var dist = endX < x ? x - endX + 1e9 : endX - x;
      if (!part || closestDist > dist) {
        part = p;
        closestDist = dist;
      }
    }
    if (!part) { part = order[order.length - 1]; }
    // Clip the part to the wrapped line.
    if (part.from < begin) { part = {from: begin, to: part.to, level: part.level}; }
    if (part.to > end) { part = {from: part.from, to: end, level: part.level}; }
    return part
  }

  var measureText;
  // Compute the default text height.
  function textHeight(display) {
    if (display.cachedTextHeight != null) { return display.cachedTextHeight }
    if (measureText == null) {
      measureText = elt("pre", null, "CodeMirror-line-like");
      // Measure a bunch of lines, for browsers that compute
      // fractional heights.
      for (var i = 0; i < 49; ++i) {
        measureText.appendChild(document.createTextNode("x"));
        measureText.appendChild(elt("br"));
      }
      measureText.appendChild(document.createTextNode("x"));
    }
    removeChildrenAndAdd(display.measure, measureText);
    var height = measureText.offsetHeight / 50;
    if (height > 3) { display.cachedTextHeight = height; }
    removeChildren(display.measure);
    return height || 1
  }

  // Compute the default character width.
  function charWidth(display) {
    if (display.cachedCharWidth != null) { return display.cachedCharWidth }
    var anchor = elt("span", "xxxxxxxxxx");
    var pre = elt("pre", [anchor], "CodeMirror-line-like");
    removeChildrenAndAdd(display.measure, pre);
    var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
    if (width > 2) { display.cachedCharWidth = width; }
    return width || 10
  }

  // Do a bulk-read of the DOM positions and sizes needed to draw the
  // view, so that we don't interleave reading and writing to the DOM.
  function getDimensions(cm) {
    var d = cm.display, left = {}, width = {};
    var gutterLeft = d.gutters.clientLeft;
    for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
      var id = cm.display.gutterSpecs[i].className;
      left[id] = n.offsetLeft + n.clientLeft + gutterLeft;
      width[id] = n.clientWidth;
    }
    return {fixedPos: compensateForHScroll(d),
            gutterTotalWidth: d.gutters.offsetWidth,
            gutterLeft: left,
            gutterWidth: width,
            wrapperWidth: d.wrapper.clientWidth}
  }

  // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
  // but using getBoundingClientRect to get a sub-pixel-accurate
  // result.
  function compensateForHScroll(display) {
    return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left
  }

  // Returns a function that estimates the height of a line, to use as
  // first approximation until the line becomes visible (and is thus
  // properly measurable).
  function estimateHeight(cm) {
    var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
    var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
    return function (line) {
      if (lineIsHidden(cm.doc, line)) { return 0 }

      var widgetsHeight = 0;
      if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) {
        if (line.widgets[i].height) { widgetsHeight += line.widgets[i].height; }
      } }

      if (wrapping)
        { return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th }
      else
        { return widgetsHeight + th }
    }
  }

  function estimateLineHeights(cm) {
    var doc = cm.doc, est = estimateHeight(cm);
    doc.iter(function (line) {
      var estHeight = est(line);
      if (estHeight != line.height) { updateLineHeight(line, estHeight); }
    });
  }

  // Given a mouse event, find the corresponding position. If liberal
  // is false, it checks whether a gutter or scrollbar was clicked,
  // and returns null if it was. forRect is used by rectangular
  // selections, and tries to estimate a character position even for
  // coordinates beyond the right of the text.
  function posFromMouse(cm, e, liberal, forRect) {
    var display = cm.display;
    if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") { return null }

    var x, y, space = display.lineSpace.getBoundingClientRect();
    // Fails unpredictably on IE[67] when mouse is dragged around quickly.
    try { x = e.clientX - space.left; y = e.clientY - space.top; }
    catch (e$1) { return null }
    var coords = coordsChar(cm, x, y), line;
    if (forRect && coords.xRel > 0 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
      var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
      coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
    }
    return coords
  }

  // Find the view element corresponding to a given line. Return null
  // when the line isn't visible.
  function findViewIndex(cm, n) {
    if (n >= cm.display.viewTo) { return null }
    n -= cm.display.viewFrom;
    if (n < 0) { return null }
    var view = cm.display.view;
    for (var i = 0; i < view.length; i++) {
      n -= view[i].size;
      if (n < 0) { return i }
    }
  }

  // Updates the display.view data structure for a given change to the
  // document. From and to are in pre-change coordinates. Lendiff is
  // the amount of lines added or subtracted by the change. This is
  // used for changes that span multiple lines, or change the way
  // lines are divided into visual lines. regLineChange (below)
  // registers single-line changes.
  function regChange(cm, from, to, lendiff) {
    if (from == null) { from = cm.doc.first; }
    if (to == null) { to = cm.doc.first + cm.doc.size; }
    if (!lendiff) { lendiff = 0; }

    var display = cm.display;
    if (lendiff && to < display.viewTo &&
        (display.updateLineNumbers == null || display.updateLineNumbers > from))
      { display.updateLineNumbers = from; }

    cm.curOp.viewChanged = true;

    if (from >= display.viewTo) { // Change after
      if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
        { resetView(cm); }
    } else if (to <= display.viewFrom) { // Change before
      if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
        resetView(cm);
      } else {
        display.viewFrom += lendiff;
        display.viewTo += lendiff;
      }
    } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
      resetView(cm);
    } else if (from <= display.viewFrom) { // Top overlap
      var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
      if (cut) {
        display.view = display.view.slice(cut.index);
        display.viewFrom = cut.lineN;
        display.viewTo += lendiff;
      } else {
        resetView(cm);
      }
    } else if (to >= display.viewTo) { // Bottom overlap
      var cut$1 = viewCuttingPoint(cm, from, from, -1);
      if (cut$1) {
        display.view = display.view.slice(0, cut$1.index);
        display.viewTo = cut$1.lineN;
      } else {
        resetView(cm);
      }
    } else { // Gap in the middle
      var cutTop = viewCuttingPoint(cm, from, from, -1);
      var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
      if (cutTop && cutBot) {
        display.view = display.view.slice(0, cutTop.index)
          .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
          .concat(display.view.slice(cutBot.index));
        display.viewTo += lendiff;
      } else {
        resetView(cm);
      }
    }

    var ext = display.externalMeasured;
    if (ext) {
      if (to < ext.lineN)
        { ext.lineN += lendiff; }
      else if (from < ext.lineN + ext.size)
        { display.externalMeasured = null; }
    }
  }

  // Register a change to a single line. Type must be one of "text",
  // "gutter", "class", "widget"
  function regLineChange(cm, line, type) {
    cm.curOp.viewChanged = true;
    var display = cm.display, ext = cm.display.externalMeasured;
    if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
      { display.externalMeasured = null; }

    if (line < display.viewFrom || line >= display.viewTo) { return }
    var lineView = display.view[findViewIndex(cm, line)];
    if (lineView.node == null) { return }
    var arr = lineView.changes || (lineView.changes = []);
    if (indexOf(arr, type) == -1) { arr.push(type); }
  }

  // Clear the view.
  function resetView(cm) {
    cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
    cm.display.view = [];
    cm.display.viewOffset = 0;
  }

  function viewCuttingPoint(cm, oldN, newN, dir) {
    var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
    if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
      { return {index: index, lineN: newN} }
    var n = cm.display.viewFrom;
    for (var i = 0; i < index; i++)
      { n += view[i].size; }
    if (n != oldN) {
      if (dir > 0) {
        if (index == view.length - 1) { return null }
        diff = (n + view[index].size) - oldN;
        index++;
      } else {
        diff = n - oldN;
      }
      oldN += diff; newN += diff;
    }
    while (visualLineNo(cm.doc, newN) != newN) {
      if (index == (dir < 0 ? 0 : view.length - 1)) { return null }
      newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
      index += dir;
    }
    return {index: index, lineN: newN}
  }

  // Force the view to cover a given range, adding empty view element
  // or clipping off existing ones as needed.
  function adjustView(cm, from, to) {
    var display = cm.display, view = display.view;
    if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
      display.view = buildViewArray(cm, from, to);
      display.viewFrom = from;
    } else {
      if (display.viewFrom > from)
        { display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); }
      else if (display.viewFrom < from)
        { display.view = display.view.slice(findViewIndex(cm, from)); }
      display.viewFrom = from;
      if (display.viewTo < to)
        { display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); }
      else if (display.viewTo > to)
        { display.view = display.view.slice(0, findViewIndex(cm, to)); }
    }
    display.viewTo = to;
  }

  // Count the number of lines in the view whose DOM representation is
  // out of date (or nonexistent).
  function countDirtyView(cm) {
    var view = cm.display.view, dirty = 0;
    for (var i = 0; i < view.length; i++) {
      var lineView = view[i];
      if (!lineView.hidden && (!lineView.node || lineView.changes)) { ++dirty; }
    }
    return dirty
  }

  function updateSelection(cm) {
    cm.display.input.showSelection(cm.display.input.prepareSelection());
  }

  function prepareSelection(cm, primary) {
    if ( primary === void 0 ) primary = true;

    var doc = cm.doc, result = {};
    var curFragment = result.cursors = document.createDocumentFragment();
    var selFragment = result.selection = document.createDocumentFragment();

    var customCursor = cm.options.$customCursor;
    if (customCursor) { primary = true; }
    for (var i = 0; i < doc.sel.ranges.length; i++) {
      if (!primary && i == doc.sel.primIndex) { continue }
      var range = doc.sel.ranges[i];
      if (range.from().line >= cm.display.viewTo || range.to().line < cm.display.viewFrom) { continue }
      var collapsed = range.empty();
      if (customCursor) {
        var head = customCursor(cm, range);
        if (head) { drawSelectionCursor(cm, head, curFragment); }
      } else if (collapsed || cm.options.showCursorWhenSelecting) {
        drawSelectionCursor(cm, range.head, curFragment);
      }
      if (!collapsed)
        { drawSelectionRange(cm, range, selFragment); }
    }
    return result
  }

  // Draws a cursor for the given range
  function drawSelectionCursor(cm, head, output) {
    var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine);

    var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
    cursor.style.left = pos.left + "px";
    cursor.style.top = pos.top + "px";
    cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";

    if (/\bcm-fat-cursor\b/.test(cm.getWrapperElement().className)) {
      var charPos = charCoords(cm, head, "div", null, null);
      var width = charPos.right - charPos.left;
      cursor.style.width = (width > 0 ? width : cm.defaultCharWidth()) + "px";
    }

    if (pos.other) {
      // Secondary cursor, shown when on a 'jump' in bi-directional text
      var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
      otherCursor.style.display = "";
      otherCursor.style.left = pos.other.left + "px";
      otherCursor.style.top = pos.other.top + "px";
      otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
    }
  }

  function cmpCoords(a, b) { return a.top - b.top || a.left - b.left }

  // Draws the given range as a highlighted selection
  function drawSelectionRange(cm, range, output) {
    var display = cm.display, doc = cm.doc;
    var fragment = document.createDocumentFragment();
    var padding = paddingH(cm.display), leftSide = padding.left;
    var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;
    var docLTR = doc.direction == "ltr";

    function add(left, top, width, bottom) {
      if (top < 0) { top = 0; }
      top = Math.round(top);
      bottom = Math.round(bottom);
      fragment.appendChild(elt("div", null, "CodeMirror-selected", ("position: absolute; left: " + left + "px;\n                             top: " + top + "px; width: " + (width == null ? rightSide - left : width) + "px;\n                             height: " + (bottom - top) + "px")));
    }

    function drawForLine(line, fromArg, toArg) {
      var lineObj = getLine(doc, line);
      var lineLen = lineObj.text.length;
      var start, end;
      function coords(ch, bias) {
        return charCoords(cm, Pos(line, ch), "div", lineObj, bias)
      }

      function wrapX(pos, dir, side) {
        var extent = wrappedLineExtentChar(cm, lineObj, null, pos);
        var prop = (dir == "ltr") == (side == "after") ? "left" : "right";
        var ch = side == "after" ? extent.begin : extent.end - (/\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1);
        return coords(ch, prop)[prop]
      }

      var order = getOrder(lineObj, doc.direction);
      iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) {
        var ltr = dir == "ltr";
        var fromPos = coords(from, ltr ? "left" : "right");
        var toPos = coords(to - 1, ltr ? "right" : "left");

        var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen;
        var first = i == 0, last = !order || i == order.length - 1;
        if (toPos.top - fromPos.top <= 3) { // Single line
          var openLeft = (docLTR ? openStart : openEnd) && first;
          var openRight = (docLTR ? openEnd : openStart) && last;
          var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left;
          var right = openRight ? rightSide : (ltr ? toPos : fromPos).right;
          add(left, fromPos.top, right - left, fromPos.bottom);
        } else { // Multiple lines
          var topLeft, topRight, botLeft, botRight;
          if (ltr) {
            topLeft = docLTR && openStart && first ? leftSide : fromPos.left;
            topRight = docLTR ? rightSide : wrapX(from, dir, "before");
            botLeft = docLTR ? leftSide : wrapX(to, dir, "after");
            botRight = docLTR && openEnd && last ? rightSide : toPos.right;
          } else {
            topLeft = !docLTR ? leftSide : wrapX(from, dir, "before");
            topRight = !docLTR && openStart && first ? rightSide : fromPos.right;
            botLeft = !docLTR && openEnd && last ? leftSide : toPos.left;
            botRight = !docLTR ? rightSide : wrapX(to, dir, "after");
          }
          add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom);
          if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); }
          add(botLeft, toPos.top, botRight - botLeft, toPos.bottom);
        }

        if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; }
        if (cmpCoords(toPos, start) < 0) { start = toPos; }
        if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; }
        if (cmpCoords(toPos, end) < 0) { end = toPos; }
      });
      return {start: start, end: end}
    }

    var sFrom = range.from(), sTo = range.to();
    if (sFrom.line == sTo.line) {
      drawForLine(sFrom.line, sFrom.ch, sTo.ch);
    } else {
      var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
      var singleVLine = visualLine(fromLine) == visualLine(toLine);
      var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
      var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
      if (singleVLine) {
        if (leftEnd.top < rightStart.top - 2) {
          add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
          add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
        } else {
          add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
        }
      }
      if (leftEnd.bottom < rightStart.top)
        { add(leftSide, leftEnd.bottom, null, rightStart.top); }
    }

    output.appendChild(fragment);
  }

  // Cursor-blinking
  function restartBlink(cm) {
    if (!cm.state.focused) { return }
    var display = cm.display;
    clearInterval(display.blinker);
    var on = true;
    display.cursorDiv.style.visibility = "";
    if (cm.options.cursorBlinkRate > 0)
      { display.blinker = setInterval(function () {
        if (!cm.hasFocus()) { onBlur(cm); }
        display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden";
      }, cm.options.cursorBlinkRate); }
    else if (cm.options.cursorBlinkRate < 0)
      { display.cursorDiv.style.visibility = "hidden"; }
  }

  function ensureFocus(cm) {
    if (!cm.hasFocus()) {
      cm.display.input.focus();
      if (!cm.state.focused) { onFocus(cm); }
    }
  }

  function delayBlurEvent(cm) {
    cm.state.delayingBlurEvent = true;
    setTimeout(function () { if (cm.state.delayingBlurEvent) {
      cm.state.delayingBlurEvent = false;
      if (cm.state.focused) { onBlur(cm); }
    } }, 100);
  }

  function onFocus(cm, e) {
    if (cm.state.delayingBlurEvent && !cm.state.draggingText) { cm.state.delayingBlurEvent = false; }

    if (cm.options.readOnly == "nocursor") { return }
    if (!cm.state.focused) {
      signal(cm, "focus", cm, e);
      cm.state.focused = true;
      addClass(cm.display.wrapper, "CodeMirror-focused");
      // This test prevents this from firing when a context
      // menu is closed (since the input reset would kill the
      // select-all detection hack)
      if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
        cm.display.input.reset();
        if (webkit) { setTimeout(function () { return cm.display.input.reset(true); }, 20); } // Issue #1730
      }
      cm.display.input.receivedFocus();
    }
    restartBlink(cm);
  }
  function onBlur(cm, e) {
    if (cm.state.delayingBlurEvent) { return }

    if (cm.state.focused) {
      signal(cm, "blur", cm, e);
      cm.state.focused = false;
      rmClass(cm.display.wrapper, "CodeMirror-focused");
    }
    clearInterval(cm.display.blinker);
    setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false; } }, 150);
  }

  // Read the actual heights of the rendered lines, and update their
  // stored heights to match.
  function updateHeightsInViewport(cm) {
    var display = cm.display;
    var prevBottom = display.lineDiv.offsetTop;
    var viewTop = Math.max(0, display.scroller.getBoundingClientRect().top);
    var oldHeight = display.lineDiv.getBoundingClientRect().top;
    var mustScroll = 0;
    for (var i = 0; i < display.view.length; i++) {
      var cur = display.view[i], wrapping = cm.options.lineWrapping;
      var height = (void 0), width = 0;
      if (cur.hidden) { continue }
      oldHeight += cur.line.height;
      if (ie && ie_version < 8) {
        var bot = cur.node.offsetTop + cur.node.offsetHeight;
        height = bot - prevBottom;
        prevBottom = bot;
      } else {
        var box = cur.node.getBoundingClientRect();
        height = box.bottom - box.top;
        // Check that lines don't extend past the right of the current
        // editor width
        if (!wrapping && cur.text.firstChild)
          { width = cur.text.firstChild.getBoundingClientRect().right - box.left - 1; }
      }
      var diff = cur.line.height - height;
      if (diff > .005 || diff < -.005) {
        if (oldHeight < viewTop) { mustScroll -= diff; }
        updateLineHeight(cur.line, height);
        updateWidgetHeight(cur.line);
        if (cur.rest) { for (var j = 0; j < cur.rest.length; j++)
          { updateWidgetHeight(cur.rest[j]); } }
      }
      if (width > cm.display.sizerWidth) {
        var chWidth = Math.ceil(width / charWidth(cm.display));
        if (chWidth > cm.display.maxLineLength) {
          cm.display.maxLineLength = chWidth;
          cm.display.maxLine = cur.line;
          cm.display.maxLineChanged = true;
        }
      }
    }
    if (Math.abs(mustScroll) > 2) { display.scroller.scrollTop += mustScroll; }
  }

  // Read and store the height of line widgets associated with the
  // given line.
  function updateWidgetHeight(line) {
    if (line.widgets) { for (var i = 0; i < line.widgets.length; ++i) {
      var w = line.widgets[i], parent = w.node.parentNode;
      if (parent) { w.height = parent.offsetHeight; }
    } }
  }

  // Compute the lines that are visible in a given viewport (defaults
  // the the current scroll position). viewport may contain top,
  // height, and ensure (see op.scrollToPos) properties.
  function visibleLines(display, doc, viewport) {
    var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;
    top = Math.floor(top - paddingTop(display));
    var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;

    var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);
    // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
    // forces those lines into the viewport (if possible).
    if (viewport && viewport.ensure) {
      var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;
      if (ensureFrom < from) {
        from = ensureFrom;
        to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);
      } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
        from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);
        to = ensureTo;
      }
    }
    return {from: from, to: Math.max(to, from + 1)}
  }

  // SCROLLING THINGS INTO VIEW

  // If an editor sits on the top or bottom of the window, partially
  // scrolled out of view, this ensures that the cursor is visible.
  function maybeScrollWindow(cm, rect) {
    if (signalDOMEvent(cm, "scrollCursorIntoView")) { return }

    var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
    var doc = display.wrapper.ownerDocument;
    if (rect.top + box.top < 0) { doScroll = true; }
    else if (rect.bottom + box.top > (doc.defaultView.innerHeight || doc.documentElement.clientHeight)) { doScroll = false; }
    if (doScroll != null && !phantom) {
      var scrollNode = elt("div", "\u200b", null, ("position: absolute;\n                         top: " + (rect.top - display.viewOffset - paddingTop(cm.display)) + "px;\n                         height: " + (rect.bottom - rect.top + scrollGap(cm) + display.barHeight) + "px;\n                         left: " + (rect.left) + "px; width: " + (Math.max(2, rect.right - rect.left)) + "px;"));
      cm.display.lineSpace.appendChild(scrollNode);
      scrollNode.scrollIntoView(doScroll);
      cm.display.lineSpace.removeChild(scrollNode);
    }
  }

  // Scroll a given position into view (immediately), verifying that
  // it actually became visible (as line heights are accurately
  // measured, the position of something may 'drift' during drawing).
  function scrollPosIntoView(cm, pos, end, margin) {
    if (margin == null) { margin = 0; }
    var rect;
    if (!cm.options.lineWrapping && pos == end) {
      // Set pos and end to the cursor positions around the character pos sticks to
      // If pos.sticky == "before", that is around pos.ch - 1, otherwise around pos.ch
      // If pos == Pos(_, 0, "before"), pos and end are unchanged
      end = pos.sticky == "before" ? Pos(pos.line, pos.ch + 1, "before") : pos;
      pos = pos.ch ? Pos(pos.line, pos.sticky == "before" ? pos.ch - 1 : pos.ch, "after") : pos;
    }
    for (var limit = 0; limit < 5; limit++) {
      var changed = false;
      var coords = cursorCoords(cm, pos);
      var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
      rect = {left: Math.min(coords.left, endCoords.left),
              top: Math.min(coords.top, endCoords.top) - margin,
              right: Math.max(coords.left, endCoords.left),
              bottom: Math.max(coords.bottom, endCoords.bottom) + margin};
      var scrollPos = calculateScrollPos(cm, rect);
      var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
      if (scrollPos.scrollTop != null) {
        updateScrollTop(cm, scrollPos.scrollTop);
        if (Math.abs(cm.doc.scrollTop - startTop) > 1) { changed = true; }
      }
      if (scrollPos.scrollLeft != null) {
        setScrollLeft(cm, scrollPos.scrollLeft);
        if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { changed = true; }
      }
      if (!changed) { break }
    }
    return rect
  }

  // Scroll a given set of coordinates into view (immediately).
  function scrollIntoView(cm, rect) {
    var scrollPos = calculateScrollPos(cm, rect);
    if (scrollPos.scrollTop != null) { updateScrollTop(cm, scrollPos.scrollTop); }
    if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft); }
  }

  // Calculate a new scroll position needed to scroll the given
  // rectangle into view. Returns an object with scrollTop and
  // scrollLeft properties. When these are undefined, the
  // vertical/horizontal position does not need to be adjusted.
  function calculateScrollPos(cm, rect) {
    var display = cm.display, snapMargin = textHeight(cm.display);
    if (rect.top < 0) { rect.top = 0; }
    var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
    var screen = displayHeight(cm), result = {};
    if (rect.bottom - rect.top > screen) { rect.bottom = rect.top + screen; }
    var docBottom = cm.doc.height + paddingVert(display);
    var atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin;
    if (rect.top < screentop) {
      result.scrollTop = atTop ? 0 : rect.top;
    } else if (rect.bottom > screentop + screen) {
      var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen);
      if (newTop != screentop) { result.scrollTop = newTop; }
    }

    var gutterSpace = cm.options.fixedGutter ? 0 : display.gutters.offsetWidth;
    var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft - gutterSpace;
    var screenw = displayWidth(cm) - display.gutters.offsetWidth;
    var tooWide = rect.right - rect.left > screenw;
    if (tooWide) { rect.right = rect.left + screenw; }
    if (rect.left < 10)
      { result.scrollLeft = 0; }
    else if (rect.left < screenleft)
      { result.scrollLeft = Math.max(0, rect.left + gutterSpace - (tooWide ? 0 : 10)); }
    else if (rect.right > screenw + screenleft - 3)
      { result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw; }
    return result
  }

  // Store a relative adjustment to the scroll position in the current
  // operation (to be applied when the operation finishes).
  function addToScrollTop(cm, top) {
    if (top == null) { return }
    resolveScrollToPos(cm);
    cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;
  }

  // Make sure that at the end of the operation the current cursor is
  // shown.
  function ensureCursorVisible(cm) {
    resolveScrollToPos(cm);
    var cur = cm.getCursor();
    cm.curOp.scrollToPos = {from: cur, to: cur, margin: cm.options.cursorScrollMargin};
  }

  function scrollToCoords(cm, x, y) {
    if (x != null || y != null) { resolveScrollToPos(cm); }
    if (x != null) { cm.curOp.scrollLeft = x; }
    if (y != null) { cm.curOp.scrollTop = y; }
  }

  function scrollToRange(cm, range) {
    resolveScrollToPos(cm);
    cm.curOp.scrollToPos = range;
  }

  // When an operation has its scrollToPos property set, and another
  // scroll action is applied before the end of the operation, this
  // 'simulates' scrolling that position into view in a cheap way, so
  // that the effect of intermediate scroll commands is not ignored.
  function resolveScrollToPos(cm) {
    var range = cm.curOp.scrollToPos;
    if (range) {
      cm.curOp.scrollToPos = null;
      var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to);
      scrollToCoordsRange(cm, from, to, range.margin);
    }
  }

  function scrollToCoordsRange(cm, from, to, margin) {
    var sPos = calculateScrollPos(cm, {
      left: Math.min(from.left, to.left),
      top: Math.min(from.top, to.top) - margin,
      right: Math.max(from.right, to.right),
      bottom: Math.max(from.bottom, to.bottom) + margin
    });
    scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop);
  }

  // Sync the scrollable area and scrollbars, ensure the viewport
  // covers the visible area.
  function updateScrollTop(cm, val) {
    if (Math.abs(cm.doc.scrollTop - val) < 2) { return }
    if (!gecko) { updateDisplaySimple(cm, {top: val}); }
    setScrollTop(cm, val, true);
    if (gecko) { updateDisplaySimple(cm); }
    startWorker(cm, 100);
  }

  function setScrollTop(cm, val, forceScroll) {
    val = Math.max(0, Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val));
    if (cm.display.scroller.scrollTop == val && !forceScroll) { return }
    cm.doc.scrollTop = val;
    cm.display.scrollbars.setScrollTop(val);
    if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val; }
  }

  // Sync scroller and scrollbar, ensure the gutter elements are
  // aligned.
  function setScrollLeft(cm, val, isScroller, forceScroll) {
    val = Math.max(0, Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth));
    if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) { return }
    cm.doc.scrollLeft = val;
    alignHorizontally(cm);
    if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val; }
    cm.display.scrollbars.setScrollLeft(val);
  }

  // SCROLLBARS

  // Prepare DOM reads needed to update the scrollbars. Done in one
  // shot to minimize update/measure roundtrips.
  function measureForScrollbars(cm) {
    var d = cm.display, gutterW = d.gutters.offsetWidth;
    var docH = Math.round(cm.doc.height + paddingVert(cm.display));
    return {
      clientHeight: d.scroller.clientHeight,
      viewHeight: d.wrapper.clientHeight,
      scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
      viewWidth: d.wrapper.clientWidth,
      barLeft: cm.options.fixedGutter ? gutterW : 0,
      docHeight: docH,
      scrollHeight: docH + scrollGap(cm) + d.barHeight,
      nativeBarWidth: d.nativeBarWidth,
      gutterWidth: gutterW
    }
  }

  var NativeScrollbars = function(place, scroll, cm) {
    this.cm = cm;
    var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
    var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
    vert.tabIndex = horiz.tabIndex = -1;
    place(vert); place(horiz);

    on(vert, "scroll", function () {
      if (vert.clientHeight) { scroll(vert.scrollTop, "vertical"); }
    });
    on(horiz, "scroll", function () {
      if (horiz.clientWidth) { scroll(horiz.scrollLeft, "horizontal"); }
    });

    this.checkedZeroWidth = false;
    // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
    if (ie && ie_version < 8) { this.horiz.style.minHeight = this.vert.style.minWidth = "18px"; }
  };

  NativeScrollbars.prototype.update = function (measure) {
    var needsH = measure.scrollWidth > measure.clientWidth + 1;
    var needsV = measure.scrollHeight > measure.clientHeight + 1;
    var sWidth = measure.nativeBarWidth;

    if (needsV) {
      this.vert.style.display = "block";
      this.vert.style.bottom = needsH ? sWidth + "px" : "0";
      var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);
      // A bug in IE8 can cause this value to be negative, so guard it.
      this.vert.firstChild.style.height =
        Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px";
    } else {
      this.vert.scrollTop = 0;
      this.vert.style.display = "";
      this.vert.firstChild.style.height = "0";
    }

    if (needsH) {
      this.horiz.style.display = "block";
      this.horiz.style.right = needsV ? sWidth + "px" : "0";
      this.horiz.style.left = measure.barLeft + "px";
      var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);
      this.horiz.firstChild.style.width =
        Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px";
    } else {
      this.horiz.style.display = "";
      this.horiz.firstChild.style.width = "0";
    }

    if (!this.checkedZeroWidth && measure.clientHeight > 0) {
      if (sWidth == 0) { this.zeroWidthHack(); }
      this.checkedZeroWidth = true;
    }

    return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0}
  };

  NativeScrollbars.prototype.setScrollLeft = function (pos) {
    if (this.horiz.scrollLeft != pos) { this.horiz.scrollLeft = pos; }
    if (this.disableHoriz) { this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz"); }
  };

  NativeScrollbars.prototype.setScrollTop = function (pos) {
    if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos; }
    if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert, "vert"); }
  };

  NativeScrollbars.prototype.zeroWidthHack = function () {
    var w = mac && !mac_geMountainLion ? "12px" : "18px";
    this.horiz.style.height = this.vert.style.width = w;
    this.horiz.style.visibility = this.vert.style.visibility = "hidden";
    this.disableHoriz = new Delayed;
    this.disableVert = new Delayed;
  };

  NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) {
    bar.style.visibility = "";
    function maybeDisable() {
      // To find out whether the scrollbar is still visible, we
      // check whether the element under the pixel in the bottom
      // right corner of the scrollbar box is the scrollbar box
      // itself (when the bar is still visible) or its filler child
      // (when the bar is hidden). If it is still visible, we keep
      // it enabled, if it's hidden, we disable pointer events.
      var box = bar.getBoundingClientRect();
      var elt = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2)
          : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1);
      if (elt != bar) { bar.style.visibility = "hidden"; }
      else { delay.set(1000, maybeDisable); }
    }
    delay.set(1000, maybeDisable);
  };

  NativeScrollbars.prototype.clear = function () {
    var parent = this.horiz.parentNode;
    parent.removeChild(this.horiz);
    parent.removeChild(this.vert);
  };

  var NullScrollbars = function () {};

  NullScrollbars.prototype.update = function () { return {bottom: 0, right: 0} };
  NullScrollbars.prototype.setScrollLeft = function () {};
  NullScrollbars.prototype.setScrollTop = function () {};
  NullScrollbars.prototype.clear = function () {};

  function updateScrollbars(cm, measure) {
    if (!measure) { measure = measureForScrollbars(cm); }
    var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;
    updateScrollbarsInner(cm, measure);
    for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
      if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
        { updateHeightsInViewport(cm); }
      updateScrollbarsInner(cm, measureForScrollbars(cm));
      startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;
    }
  }

  // Re-synchronize the fake scrollbars with the actual size of the
  // content.
  function updateScrollbarsInner(cm, measure) {
    var d = cm.display;
    var sizes = d.scrollbars.update(measure);

    d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px";
    d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px";
    d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent";

    if (sizes.right && sizes.bottom) {
      d.scrollbarFiller.style.display = "block";
      d.scrollbarFiller.style.height = sizes.bottom + "px";
      d.scrollbarFiller.style.width = sizes.right + "px";
    } else { d.scrollbarFiller.style.display = ""; }
    if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
      d.gutterFiller.style.display = "block";
      d.gutterFiller.style.height = sizes.bottom + "px";
      d.gutterFiller.style.width = measure.gutterWidth + "px";
    } else { d.gutterFiller.style.display = ""; }
  }

  var scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars};

  function initScrollbars(cm) {
    if (cm.display.scrollbars) {
      cm.display.scrollbars.clear();
      if (cm.display.scrollbars.addClass)
        { rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
    }

    cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) {
      cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);
      // Prevent clicks in the scrollbars from killing focus
      on(node, "mousedown", function () {
        if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0); }
      });
      node.setAttribute("cm-not-content", "true");
    }, function (pos, axis) {
      if (axis == "horizontal") { setScrollLeft(cm, pos); }
      else { updateScrollTop(cm, pos); }
    }, cm);
    if (cm.display.scrollbars.addClass)
      { addClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
  }

  // Operations are used to wrap a series of changes to the editor
  // state in such a way that each change won't have to update the
  // cursor and display (which would be awkward, slow, and
  // error-prone). Instead, display updates are batched and then all
  // combined and executed at once.

  var nextOpId = 0;
  // Start a new operation.
  function startOperation(cm) {
    cm.curOp = {
      cm: cm,
      viewChanged: false,      // Flag that indicates that lines might need to be redrawn
      startHeight: cm.doc.height, // Used to detect need to update scrollbar
      forceUpdate: false,      // Used to force a redraw
      updateInput: 0,       // Whether to reset the input textarea
      typing: false,           // Whether this reset should be careful to leave existing text (for compositing)
      changeObjs: null,        // Accumulated changes, for firing change events
      cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
      cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
      selectionChanged: false, // Whether the selection needs to be redrawn
      updateMaxLine: false,    // Set when the widest line needs to be determined anew
      scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
      scrollToPos: null,       // Used to scroll to a specific position
      focus: false,
      id: ++nextOpId,          // Unique ID
      markArrays: null         // Used by addMarkedSpan
    };
    pushOperation(cm.curOp);
  }

  // Finish an operation, updating the display and signalling delayed events
  function endOperation(cm) {
    var op = cm.curOp;
    if (op) { finishOperation(op, function (group) {
      for (var i = 0; i < group.ops.length; i++)
        { group.ops[i].cm.curOp = null; }
      endOperations(group);
    }); }
  }

  // The DOM updates done when an operation finishes are batched so
  // that the minimum number of relayouts are required.
  function endOperations(group) {
    var ops = group.ops;
    for (var i = 0; i < ops.length; i++) // Read DOM
      { endOperation_R1(ops[i]); }
    for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe)
      { endOperation_W1(ops[i$1]); }
    for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM
      { endOperation_R2(ops[i$2]); }
    for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe)
      { endOperation_W2(ops[i$3]); }
    for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM
      { endOperation_finish(ops[i$4]); }
  }

  function endOperation_R1(op) {
    var cm = op.cm, display = cm.display;
    maybeClipScrollbars(cm);
    if (op.updateMaxLine) { findMaxLine(cm); }

    op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
      op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
                         op.scrollToPos.to.line >= display.viewTo) ||
      display.maxLineChanged && cm.options.lineWrapping;
    op.update = op.mustUpdate &&
      new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
  }

  function endOperation_W1(op) {
    op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);
  }

  function endOperation_R2(op) {
    var cm = op.cm, display = cm.display;
    if (op.updatedDisplay) { updateHeightsInViewport(cm); }

    op.barMeasure = measureForScrollbars(cm);

    // If the max line changed since it was last measured, measure it,
    // and ensure the document's width matches it.
    // updateDisplay_W2 will use these properties to do the actual resizing
    if (display.maxLineChanged && !cm.options.lineWrapping) {
      op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;
      cm.display.sizerWidth = op.adjustWidthTo;
      op.barMeasure.scrollWidth =
        Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);
      op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));
    }

    if (op.updatedDisplay || op.selectionChanged)
      { op.preparedSelection = display.input.prepareSelection(); }
  }

  function endOperation_W2(op) {
    var cm = op.cm;

    if (op.adjustWidthTo != null) {
      cm.display.sizer.style.minWidth = op.adjustWidthTo + "px";
      if (op.maxScrollLeft < cm.doc.scrollLeft)
        { setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); }
      cm.display.maxLineChanged = false;
    }

    var takeFocus = op.focus && op.focus == activeElt(doc(cm));
    if (op.preparedSelection)
      { cm.display.input.showSelection(op.preparedSelection, takeFocus); }
    if (op.updatedDisplay || op.startHeight != cm.doc.height)
      { updateScrollbars(cm, op.barMeasure); }
    if (op.updatedDisplay)
      { setDocumentHeight(cm, op.barMeasure); }

    if (op.selectionChanged) { restartBlink(cm); }

    if (cm.state.focused && op.updateInput)
      { cm.display.input.reset(op.typing); }
    if (takeFocus) { ensureFocus(op.cm); }
  }

  function endOperation_finish(op) {
    var cm = op.cm, display = cm.display, doc = cm.doc;

    if (op.updatedDisplay) { postUpdateDisplay(cm, op.update); }

    // Abort mouse wheel delta measurement, when scrolling explicitly
    if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
      { display.wheelStartX = display.wheelStartY = null; }

    // Propagate the scroll position to the actual DOM scroller
    if (op.scrollTop != null) { setScrollTop(cm, op.scrollTop, op.forceScroll); }

    if (op.scrollLeft != null) { setScrollLeft(cm, op.scrollLeft, true, true); }
    // If we need to scroll a specific position into view, do so.
    if (op.scrollToPos) {
      var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
                                   clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);
      maybeScrollWindow(cm, rect);
    }

    // Fire events for markers that are hidden/unidden by editing or
    // undoing
    var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
    if (hidden) { for (var i = 0; i < hidden.length; ++i)
      { if (!hidden[i].lines.length) { signal(hidden[i], "hide"); } } }
    if (unhidden) { for (var i$1 = 0; i$1 < unhidden.length; ++i$1)
      { if (unhidden[i$1].lines.length) { signal(unhidden[i$1], "unhide"); } } }

    if (display.wrapper.offsetHeight)
      { doc.scrollTop = cm.display.scroller.scrollTop; }

    // Fire change events, and delayed event handlers
    if (op.changeObjs)
      { signal(cm, "changes", cm, op.changeObjs); }
    if (op.update)
      { op.update.finish(); }
  }

  // Run the given function in an operation
  function runInOp(cm, f) {
    if (cm.curOp) { return f() }
    startOperation(cm);
    try { return f() }
    finally { endOperation(cm); }
  }
  // Wraps a function in an operation. Returns the wrapped function.
  function operation(cm, f) {
    return function() {
      if (cm.curOp) { return f.apply(cm, arguments) }
      startOperation(cm);
      try { return f.apply(cm, arguments) }
      finally { endOperation(cm); }
    }
  }
  // Used to add methods to editor and doc instances, wrapping them in
  // operations.
  function methodOp(f) {
    return function() {
      if (this.curOp) { return f.apply(this, arguments) }
      startOperation(this);
      try { return f.apply(this, arguments) }
      finally { endOperation(this); }
    }
  }
  function docMethodOp(f) {
    return function() {
      var cm = this.cm;
      if (!cm || cm.curOp) { return f.apply(this, arguments) }
      startOperation(cm);
      try { return f.apply(this, arguments) }
      finally { endOperation(cm); }
    }
  }

  // HIGHLIGHT WORKER

  function startWorker(cm, time) {
    if (cm.doc.highlightFrontier < cm.display.viewTo)
      { cm.state.highlight.set(time, bind(highlightWorker, cm)); }
  }

  function highlightWorker(cm) {
    var doc = cm.doc;
    if (doc.highlightFrontier >= cm.display.viewTo) { return }
    var end = +new Date + cm.options.workTime;
    var context = getContextBefore(cm, doc.highlightFrontier);
    var changedLines = [];

    doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) {
      if (context.line >= cm.display.viewFrom) { // Visible
        var oldStyles = line.styles;
        var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null;
        var highlighted = highlightLine(cm, line, context, true);
        if (resetState) { context.state = resetState; }
        line.styles = highlighted.styles;
        var oldCls = line.styleClasses, newCls = highlighted.classes;
        if (newCls) { line.styleClasses = newCls; }
        else if (oldCls) { line.styleClasses = null; }
        var ischange = !oldStyles || oldStyles.length != line.styles.length ||
          oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);
        for (var i = 0; !ischange && i < oldStyles.length; ++i) { ischange = oldStyles[i] != line.styles[i]; }
        if (ischange) { changedLines.push(context.line); }
        line.stateAfter = context.save();
        context.nextLine();
      } else {
        if (line.text.length <= cm.options.maxHighlightLength)
          { processLine(cm, line.text, context); }
        line.stateAfter = context.line % 5 == 0 ? context.save() : null;
        context.nextLine();
      }
      if (+new Date > end) {
        startWorker(cm, cm.options.workDelay);
        return true
      }
    });
    doc.highlightFrontier = context.line;
    doc.modeFrontier = Math.max(doc.modeFrontier, context.line);
    if (changedLines.length) { runInOp(cm, function () {
      for (var i = 0; i < changedLines.length; i++)
        { regLineChange(cm, changedLines[i], "text"); }
    }); }
  }

  // DISPLAY DRAWING

  var DisplayUpdate = function(cm, viewport, force) {
    var display = cm.display;

    this.viewport = viewport;
    // Store some values that we'll need later (but don't want to force a relayout for)
    this.visible = visibleLines(display, cm.doc, viewport);
    this.editorIsHidden = !display.wrapper.offsetWidth;
    this.wrapperHeight = display.wrapper.clientHeight;
    this.wrapperWidth = display.wrapper.clientWidth;
    this.oldDisplayWidth = displayWidth(cm);
    this.force = force;
    this.dims = getDimensions(cm);
    this.events = [];
  };

  DisplayUpdate.prototype.signal = function (emitter, type) {
    if (hasHandler(emitter, type))
      { this.events.push(arguments); }
  };
  DisplayUpdate.prototype.finish = function () {
    for (var i = 0; i < this.events.length; i++)
      { signal.apply(null, this.events[i]); }
  };

  function maybeClipScrollbars(cm) {
    var display = cm.display;
    if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
      display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;
      display.heightForcer.style.height = scrollGap(cm) + "px";
      display.sizer.style.marginBottom = -display.nativeBarWidth + "px";
      display.sizer.style.borderRightWidth = scrollGap(cm) + "px";
      display.scrollbarsClipped = true;
    }
  }

  function selectionSnapshot(cm) {
    if (cm.hasFocus()) { return null }
    var active = activeElt(doc(cm));
    if (!active || !contains(cm.display.lineDiv, active)) { return null }
    var result = {activeElt: active};
    if (window.getSelection) {
      var sel = win(cm).getSelection();
      if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) {
        result.anchorNode = sel.anchorNode;
        result.anchorOffset = sel.anchorOffset;
        result.focusNode = sel.focusNode;
        result.focusOffset = sel.focusOffset;
      }
    }
    return result
  }

  function restoreSelection(snapshot) {
    if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt(snapshot.activeElt.ownerDocument)) { return }
    snapshot.activeElt.focus();
    if (!/^(INPUT|TEXTAREA)$/.test(snapshot.activeElt.nodeName) &&
        snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) {
      var doc = snapshot.activeElt.ownerDocument;
      var sel = doc.defaultView.getSelection(), range = doc.createRange();
      range.setEnd(snapshot.anchorNode, snapshot.anchorOffset);
      range.collapse(false);
      sel.removeAllRanges();
      sel.addRange(range);
      sel.extend(snapshot.focusNode, snapshot.focusOffset);
    }
  }

  // Does the actual updating of the line display. Bails out
  // (returning false) when there is nothing to be done and forced is
  // false.
  function updateDisplayIfNeeded(cm, update) {
    var display = cm.display, doc = cm.doc;

    if (update.editorIsHidden) {
      resetView(cm);
      return false
    }

    // Bail out if the visible area is already rendered and nothing changed.
    if (!update.force &&
        update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
        (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
        display.renderedView == display.view && countDirtyView(cm) == 0)
      { return false }

    if (maybeUpdateLineNumberWidth(cm)) {
      resetView(cm);
      update.dims = getDimensions(cm);
    }

    // Compute a suitable new viewport (from & to)
    var end = doc.first + doc.size;
    var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);
    var to = Math.min(end, update.visible.to + cm.options.viewportMargin);
    if (display.viewFrom < from && from - display.viewFrom < 20) { from = Math.max(doc.first, display.viewFrom); }
    if (display.viewTo > to && display.viewTo - to < 20) { to = Math.min(end, display.viewTo); }
    if (sawCollapsedSpans) {
      from = visualLineNo(cm.doc, from);
      to = visualLineEndNo(cm.doc, to);
    }

    var different = from != display.viewFrom || to != display.viewTo ||
      display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;
    adjustView(cm, from, to);

    display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
    // Position the mover div to align with the current scroll position
    cm.display.mover.style.top = display.viewOffset + "px";

    var toUpdate = countDirtyView(cm);
    if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&
        (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))
      { return false }

    // For big changes, we hide the enclosing element during the
    // update, since that speeds up the operations on most browsers.
    var selSnapshot = selectionSnapshot(cm);
    if (toUpdate > 4) { display.lineDiv.style.display = "none"; }
    patchDisplay(cm, display.updateLineNumbers, update.dims);
    if (toUpdate > 4) { display.lineDiv.style.display = ""; }
    display.renderedView = display.view;
    // There might have been a widget with a focused element that got
    // hidden or updated, if so re-focus it.
    restoreSelection(selSnapshot);

    // Prevent selection and cursors from interfering with the scroll
    // width and height.
    removeChildren(display.cursorDiv);
    removeChildren(display.selectionDiv);
    display.gutters.style.height = display.sizer.style.minHeight = 0;

    if (different) {
      display.lastWrapHeight = update.wrapperHeight;
      display.lastWrapWidth = update.wrapperWidth;
      startWorker(cm, 400);
    }

    display.updateLineNumbers = null;

    return true
  }

  function postUpdateDisplay(cm, update) {
    var viewport = update.viewport;

    for (var first = true;; first = false) {
      if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
        // Clip forced viewport to actual scrollable area.
        if (viewport && viewport.top != null)
          { viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)}; }
        // Updated line heights might result in the drawn area not
        // actually covering the viewport. Keep looping until it does.
        update.visible = visibleLines(cm.display, cm.doc, viewport);
        if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
          { break }
      } else if (first) {
        update.visible = visibleLines(cm.display, cm.doc, viewport);
      }
      if (!updateDisplayIfNeeded(cm, update)) { break }
      updateHeightsInViewport(cm);
      var barMeasure = measureForScrollbars(cm);
      updateSelection(cm);
      updateScrollbars(cm, barMeasure);
      setDocumentHeight(cm, barMeasure);
      update.force = false;
    }

    update.signal(cm, "update", cm);
    if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
      update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
      cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo;
    }
  }

  function updateDisplaySimple(cm, viewport) {
    var update = new DisplayUpdate(cm, viewport);
    if (updateDisplayIfNeeded(cm, update)) {
      updateHeightsInViewport(cm);
      postUpdateDisplay(cm, update);
      var barMeasure = measureForScrollbars(cm);
      updateSelection(cm);
      updateScrollbars(cm, barMeasure);
      setDocumentHeight(cm, barMeasure);
      update.finish();
    }
  }

  // Sync the actual display DOM structure with display.view, removing
  // nodes for lines that are no longer in view, and creating the ones
  // that are not there yet, and updating the ones that are out of
  // date.
  function patchDisplay(cm, updateNumbersFrom, dims) {
    var display = cm.display, lineNumbers = cm.options.lineNumbers;
    var container = display.lineDiv, cur = container.firstChild;

    function rm(node) {
      var next = node.nextSibling;
      // Works around a throw-scroll bug in OS X Webkit
      if (webkit && mac && cm.display.currentWheelTarget == node)
        { node.style.display = "none"; }
      else
        { node.parentNode.removeChild(node); }
      return next
    }

    var view = display.view, lineN = display.viewFrom;
    // Loop over the elements in the view, syncing cur (the DOM nodes
    // in display.lineDiv) with the view as we go.
    for (var i = 0; i < view.length; i++) {
      var lineView = view[i];
      if (lineView.hidden) ; else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
        var node = buildLineElement(cm, lineView, lineN, dims);
        container.insertBefore(node, cur);
      } else { // Already drawn
        while (cur != lineView.node) { cur = rm(cur); }
        var updateNumber = lineNumbers && updateNumbersFrom != null &&
          updateNumbersFrom <= lineN && lineView.lineNumber;
        if (lineView.changes) {
          if (indexOf(lineView.changes, "gutter") > -1) { updateNumber = false; }
          updateLineForChanges(cm, lineView, lineN, dims);
        }
        if (updateNumber) {
          removeChildren(lineView.lineNumber);
          lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
        }
        cur = lineView.node.nextSibling;
      }
      lineN += lineView.size;
    }
    while (cur) { cur = rm(cur); }
  }

  function updateGutterSpace(display) {
    var width = display.gutters.offsetWidth;
    display.sizer.style.marginLeft = width + "px";
    // Send an event to consumers responding to changes in gutter width.
    signalLater(display, "gutterChanged", display);
  }

  function setDocumentHeight(cm, measure) {
    cm.display.sizer.style.minHeight = measure.docHeight + "px";
    cm.display.heightForcer.style.top = measure.docHeight + "px";
    cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px";
  }

  // Re-align line numbers and gutter marks to compensate for
  // horizontal scrolling.
  function alignHorizontally(cm) {
    var display = cm.display, view = display.view;
    if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { return }
    var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
    var gutterW = display.gutters.offsetWidth, left = comp + "px";
    for (var i = 0; i < view.length; i++) { if (!view[i].hidden) {
      if (cm.options.fixedGutter) {
        if (view[i].gutter)
          { view[i].gutter.style.left = left; }
        if (view[i].gutterBackground)
          { view[i].gutterBackground.style.left = left; }
      }
      var align = view[i].alignable;
      if (align) { for (var j = 0; j < align.length; j++)
        { align[j].style.left = left; } }
    } }
    if (cm.options.fixedGutter)
      { display.gutters.style.left = (comp + gutterW) + "px"; }
  }

  // Used to ensure that the line number gutter is still the right
  // size for the current document size. Returns true when an update
  // is needed.
  function maybeUpdateLineNumberWidth(cm) {
    if (!cm.options.lineNumbers) { return false }
    var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
    if (last.length != display.lineNumChars) {
      var test = display.measure.appendChild(elt("div", [elt("div", last)],
                                                 "CodeMirror-linenumber CodeMirror-gutter-elt"));
      var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
      display.lineGutter.style.width = "";
      display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1;
      display.lineNumWidth = display.lineNumInnerWidth + padding;
      display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
      display.lineGutter.style.width = display.lineNumWidth + "px";
      updateGutterSpace(cm.display);
      return true
    }
    return false
  }

  function getGutters(gutters, lineNumbers) {
    var result = [], sawLineNumbers = false;
    for (var i = 0; i < gutters.length; i++) {
      var name = gutters[i], style = null;
      if (typeof name != "string") { style = name.style; name = name.className; }
      if (name == "CodeMirror-linenumbers") {
        if (!lineNumbers) { continue }
        else { sawLineNumbers = true; }
      }
      result.push({className: name, style: style});
    }
    if (lineNumbers && !sawLineNumbers) { result.push({className: "CodeMirror-linenumbers", style: null}); }
    return result
  }

  // Rebuild the gutter elements, ensure the margin to the left of the
  // code matches their width.
  function renderGutters(display) {
    var gutters = display.gutters, specs = display.gutterSpecs;
    removeChildren(gutters);
    display.lineGutter = null;
    for (var i = 0; i < specs.length; ++i) {
      var ref = specs[i];
      var className = ref.className;
      var style = ref.style;
      var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + className));
      if (style) { gElt.style.cssText = style; }
      if (className == "CodeMirror-linenumbers") {
        display.lineGutter = gElt;
        gElt.style.width = (display.lineNumWidth || 1) + "px";
      }
    }
    gutters.style.display = specs.length ? "" : "none";
    updateGutterSpace(display);
  }

  function updateGutters(cm) {
    renderGutters(cm.display);
    regChange(cm);
    alignHorizontally(cm);
  }

  // The display handles the DOM integration, both for input reading
  // and content drawing. It holds references to DOM nodes and
  // display-related state.

  function Display(place, doc, input, options) {
    var d = this;
    this.input = input;

    // Covers bottom-right square when both scrollbars are present.
    d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
    d.scrollbarFiller.setAttribute("cm-not-content", "true");
    // Covers bottom of gutter when coverGutterNextToScrollbar is on
    // and h scrollbar is present.
    d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
    d.gutterFiller.setAttribute("cm-not-content", "true");
    // Will contain the actual code, positioned to cover the viewport.
    d.lineDiv = eltP("div", null, "CodeMirror-code");
    // Elements are added to these to represent selection and cursors.
    d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
    d.cursorDiv = elt("div", null, "CodeMirror-cursors");
    // A visibility: hidden element used to find the size of things.
    d.measure = elt("div", null, "CodeMirror-measure");
    // When lines outside of the viewport are measured, they are drawn in this.
    d.lineMeasure = elt("div", null, "CodeMirror-measure");
    // Wraps everything that needs to exist inside the vertically-padded coordinate system
    d.lineSpace = eltP("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
                      null, "position: relative; outline: none");
    var lines = eltP("div", [d.lineSpace], "CodeMirror-lines");
    // Moved around its parent to cover visible view.
    d.mover = elt("div", [lines], null, "position: relative");
    // Set to the height of the document, allowing scrolling.
    d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
    d.sizerWidth = null;
    // Behavior of elts with overflow: auto and padding is
    // inconsistent across browsers. This is used to ensure the
    // scrollable area is big enough.
    d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;");
    // Will contain the gutters, if any.
    d.gutters = elt("div", null, "CodeMirror-gutters");
    d.lineGutter = null;
    // Actual scrollable element.
    d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
    d.scroller.setAttribute("tabIndex", "-1");
    // The element in which the editor lives.
    d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
    // See #6982. FIXME remove when this has been fixed for a while in Chrome
    if (chrome && chrome_version >= 105) { d.wrapper.style.clipPath = "inset(0px)"; }

    // This attribute is respected by automatic translation systems such as Google Translate,
    // and may also be respected by tools used by human translators.
    d.wrapper.setAttribute('translate', 'no');

    // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
    if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
    if (!webkit && !(gecko && mobile)) { d.scroller.draggable = true; }

    if (place) {
      if (place.appendChild) { place.appendChild(d.wrapper); }
      else { place(d.wrapper); }
    }

    // Current rendered range (may be bigger than the view window).
    d.viewFrom = d.viewTo = doc.first;
    d.reportedViewFrom = d.reportedViewTo = doc.first;
    // Information about the rendered lines.
    d.view = [];
    d.renderedView = null;
    // Holds info about a single rendered line when it was rendered
    // for measurement, while not in view.
    d.externalMeasured = null;
    // Empty space (in pixels) above the view
    d.viewOffset = 0;
    d.lastWrapHeight = d.lastWrapWidth = 0;
    d.updateLineNumbers = null;

    d.nativeBarWidth = d.barHeight = d.barWidth = 0;
    d.scrollbarsClipped = false;

    // Used to only resize the line number gutter when necessary (when
    // the amount of lines crosses a boundary that makes its width change)
    d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
    // Set to true when a non-horizontal-scrolling line widget is
    // added. As an optimization, line widget aligning is skipped when
    // this is false.
    d.alignWidgets = false;

    d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;

    // Tracks the maximum line length so that the horizontal scrollbar
    // can be kept static when scrolling.
    d.maxLine = null;
    d.maxLineLength = 0;
    d.maxLineChanged = false;

    // Used for measuring wheel scrolling granularity
    d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;

    // True when shift is held down.
    d.shift = false;

    // Used to track whether anything happened since the context menu
    // was opened.
    d.selForContextMenu = null;

    d.activeTouch = null;

    d.gutterSpecs = getGutters(options.gutters, options.lineNumbers);
    renderGutters(d);

    input.init(d);
  }

  // Since the delta values reported on mouse wheel events are
  // unstandardized between browsers and even browser versions, and
  // generally horribly unpredictable, this code starts by measuring
  // the scroll effect that the first few mouse wheel events have,
  // and, from that, detects the way it can convert deltas to pixel
  // offsets afterwards.
  //
  // The reason we want to know the amount a wheel event will scroll
  // is that it gives us a chance to update the display before the
  // actual scrolling happens, reducing flickering.

  var wheelSamples = 0, wheelPixelsPerUnit = null;
  // Fill in a browser-detected starting value on browsers where we
  // know one. These don't have to be accurate -- the result of them
  // being wrong would just be a slight flicker on the first wheel
  // scroll (if it is large enough).
  if (ie) { wheelPixelsPerUnit = -.53; }
  else if (gecko) { wheelPixelsPerUnit = 15; }
  else if (chrome) { wheelPixelsPerUnit = -.7; }
  else if (safari) { wheelPixelsPerUnit = -1/3; }

  function wheelEventDelta(e) {
    var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
    if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { dx = e.detail; }
    if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { dy = e.detail; }
    else if (dy == null) { dy = e.wheelDelta; }
    return {x: dx, y: dy}
  }
  function wheelEventPixels(e) {
    var delta = wheelEventDelta(e);
    delta.x *= wheelPixelsPerUnit;
    delta.y *= wheelPixelsPerUnit;
    return delta
  }

  function onScrollWheel(cm, e) {
    // On Chrome 102, viewport updates somehow stop wheel-based
    // scrolling. Turning off pointer events during the scroll seems
    // to avoid the issue.
    if (chrome && chrome_version == 102) {
      if (cm.display.chromeScrollHack == null) { cm.display.sizer.style.pointerEvents = "none"; }
      else { clearTimeout(cm.display.chromeScrollHack); }
      cm.display.chromeScrollHack = setTimeout(function () {
        cm.display.chromeScrollHack = null;
        cm.display.sizer.style.pointerEvents = "";
      }, 100);
    }
    var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;
    var pixelsPerUnit = wheelPixelsPerUnit;
    if (e.deltaMode === 0) {
      dx = e.deltaX;
      dy = e.deltaY;
      pixelsPerUnit = 1;
    }

    var display = cm.display, scroll = display.scroller;
    // Quit if there's nothing to scroll here
    var canScrollX = scroll.scrollWidth > scroll.clientWidth;
    var canScrollY = scroll.scrollHeight > scroll.clientHeight;
    if (!(dx && canScrollX || dy && canScrollY)) { return }

    // Webkit browsers on OS X abort momentum scrolls when the target
    // of the scroll event is removed from the scrollable element.
    // This hack (see related code in patchDisplay) makes sure the
    // element is kept around.
    if (dy && mac && webkit) {
      outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
        for (var i = 0; i < view.length; i++) {
          if (view[i].node == cur) {
            cm.display.currentWheelTarget = cur;
            break outer
          }
        }
      }
    }

    // On some browsers, horizontal scrolling will cause redraws to
    // happen before the gutter has been realigned, causing it to
    // wriggle around in a most unseemly way. When we have an
    // estimated pixels/delta value, we just handle horizontal
    // scrolling entirely here. It'll be slightly off from native, but
    // better than glitching out.
    if (dx && !gecko && !presto && pixelsPerUnit != null) {
      if (dy && canScrollY)
        { updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * pixelsPerUnit)); }
      setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * pixelsPerUnit));
      // Only prevent default scrolling if vertical scrolling is
      // actually possible. Otherwise, it causes vertical scroll
      // jitter on OSX trackpads when deltaX is small and deltaY
      // is large (issue #3579)
      if (!dy || (dy && canScrollY))
        { e_preventDefault(e); }
      display.wheelStartX = null; // Abort measurement, if in progress
      return
    }

    // 'Project' the visible viewport to cover the area that is being
    // scrolled into view (if we know enough to estimate it).
    if (dy && pixelsPerUnit != null) {
      var pixels = dy * pixelsPerUnit;
      var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
      if (pixels < 0) { top = Math.max(0, top + pixels - 50); }
      else { bot = Math.min(cm.doc.height, bot + pixels + 50); }
      updateDisplaySimple(cm, {top: top, bottom: bot});
    }

    if (wheelSamples < 20 && e.deltaMode !== 0) {
      if (display.wheelStartX == null) {
        display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
        display.wheelDX = dx; display.wheelDY = dy;
        setTimeout(function () {
          if (display.wheelStartX == null) { return }
          var movedX = scroll.scrollLeft - display.wheelStartX;
          var movedY = scroll.scrollTop - display.wheelStartY;
          var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
            (movedX && display.wheelDX && movedX / display.wheelDX);
          display.wheelStartX = display.wheelStartY = null;
          if (!sample) { return }
          wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
          ++wheelSamples;
        }, 200);
      } else {
        display.wheelDX += dx; display.wheelDY += dy;
      }
    }
  }

  // Selection objects are immutable. A new one is created every time
  // the selection changes. A selection is one or more non-overlapping
  // (and non-touching) ranges, sorted, and an integer that indicates
  // which one is the primary selection (the one that's scrolled into
  // view, that getCursor returns, etc).
  var Selection = function(ranges, primIndex) {
    this.ranges = ranges;
    this.primIndex = primIndex;
  };

  Selection.prototype.primary = function () { return this.ranges[this.primIndex] };

  Selection.prototype.equals = function (other) {
    if (other == this) { return true }
    if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { return false }
    for (var i = 0; i < this.ranges.length; i++) {
      var here = this.ranges[i], there = other.ranges[i];
      if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) { return false }
    }
    return true
  };

  Selection.prototype.deepCopy = function () {
    var out = [];
    for (var i = 0; i < this.ranges.length; i++)
      { out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head)); }
    return new Selection(out, this.primIndex)
  };

  Selection.prototype.somethingSelected = function () {
    for (var i = 0; i < this.ranges.length; i++)
      { if (!this.ranges[i].empty()) { return true } }
    return false
  };

  Selection.prototype.contains = function (pos, end) {
    if (!end) { end = pos; }
    for (var i = 0; i < this.ranges.length; i++) {
      var range = this.ranges[i];
      if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
        { return i }
    }
    return -1
  };

  var Range = function(anchor, head) {
    this.anchor = anchor; this.head = head;
  };

  Range.prototype.from = function () { return minPos(this.anchor, this.head) };
  Range.prototype.to = function () { return maxPos(this.anchor, this.head) };
  Range.prototype.empty = function () { return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch };

  // Take an unsorted, potentially overlapping set of ranges, and
  // build a selection out of it. 'Consumes' ranges array (modifying
  // it).
  function normalizeSelection(cm, ranges, primIndex) {
    var mayTouch = cm && cm.options.selectionsMayTouch;
    var prim = ranges[primIndex];
    ranges.sort(function (a, b) { return cmp(a.from(), b.from()); });
    primIndex = indexOf(ranges, prim);
    for (var i = 1; i < ranges.length; i++) {
      var cur = ranges[i], prev = ranges[i - 1];
      var diff = cmp(prev.to(), cur.from());
      if (mayTouch && !cur.empty() ? diff > 0 : diff >= 0) {
        var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
        var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
        if (i <= primIndex) { --primIndex; }
        ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
      }
    }
    return new Selection(ranges, primIndex)
  }

  function simpleSelection(anchor, head) {
    return new Selection([new Range(anchor, head || anchor)], 0)
  }

  // Compute the position of the end of a change (its 'to' property
  // refers to the pre-change end).
  function changeEnd(change) {
    if (!change.text) { return change.to }
    return Pos(change.from.line + change.text.length - 1,
               lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0))
  }

  // Adjust a position to refer to the post-change position of the
  // same text, or the end of the change if the change covers it.
  function adjustForChange(pos, change) {
    if (cmp(pos, change.from) < 0) { return pos }
    if (cmp(pos, change.to) <= 0) { return changeEnd(change) }

    var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
    if (pos.line == change.to.line) { ch += changeEnd(change).ch - change.to.ch; }
    return Pos(line, ch)
  }

  function computeSelAfterChange(doc, change) {
    var out = [];
    for (var i = 0; i < doc.sel.ranges.length; i++) {
      var range = doc.sel.ranges[i];
      out.push(new Range(adjustForChange(range.anchor, change),
                         adjustForChange(range.head, change)));
    }
    return normalizeSelection(doc.cm, out, doc.sel.primIndex)
  }

  function offsetPos(pos, old, nw) {
    if (pos.line == old.line)
      { return Pos(nw.line, pos.ch - old.ch + nw.ch) }
    else
      { return Pos(nw.line + (pos.line - old.line), pos.ch) }
  }

  // Used by replaceSelections to allow moving the selection to the
  // start or around the replaced test. Hint may be "start" or "around".
  function computeReplacedSel(doc, changes, hint) {
    var out = [];
    var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
    for (var i = 0; i < changes.length; i++) {
      var change = changes[i];
      var from = offsetPos(change.from, oldPrev, newPrev);
      var to = offsetPos(changeEnd(change), oldPrev, newPrev);
      oldPrev = change.to;
      newPrev = to;
      if (hint == "around") {
        var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;
        out[i] = new Range(inv ? to : from, inv ? from : to);
      } else {
        out[i] = new Range(from, from);
      }
    }
    return new Selection(out, doc.sel.primIndex)
  }

  // Used to get the editor into a consistent state again when options change.

  function loadMode(cm) {
    cm.doc.mode = getMode(cm.options, cm.doc.modeOption);
    resetModeState(cm);
  }

  function resetModeState(cm) {
    cm.doc.iter(function (line) {
      if (line.stateAfter) { line.stateAfter = null; }
      if (line.styles) { line.styles = null; }
    });
    cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first;
    startWorker(cm, 100);
    cm.state.modeGen++;
    if (cm.curOp) { regChange(cm); }
  }

  // DOCUMENT DATA STRUCTURE

  // By default, updates that start and end at the beginning of a line
  // are treated specially, in order to make the association of line
  // widgets and marker elements with the text behave more intuitive.
  function isWholeLineUpdate(doc, change) {
    return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
      (!doc.cm || doc.cm.options.wholeLineUpdateBefore)
  }

  // Perform a change on the document data structure.
  function updateDoc(doc, change, markedSpans, estimateHeight) {
    function spansFor(n) {return markedSpans ? markedSpans[n] : null}
    function update(line, text, spans) {
      updateLine(line, text, spans, estimateHeight);
      signalLater(line, "change", line, change);
    }
    function linesFor(start, end) {
      var result = [];
      for (var i = start; i < end; ++i)
        { result.push(new Line(text[i], spansFor(i), estimateHeight)); }
      return result
    }

    var from = change.from, to = change.to, text = change.text;
    var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
    var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;

    // Adjust the line structure
    if (change.full) {
      doc.insert(0, linesFor(0, text.length));
      doc.remove(text.length, doc.size - text.length);
    } else if (isWholeLineUpdate(doc, change)) {
      // This is a whole-line replace. Treated specially to make
      // sure line objects move the way they are supposed to.
      var added = linesFor(0, text.length - 1);
      update(lastLine, lastLine.text, lastSpans);
      if (nlines) { doc.remove(from.line, nlines); }
      if (added.length) { doc.insert(from.line, added); }
    } else if (firstLine == lastLine) {
      if (text.length == 1) {
        update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
      } else {
        var added$1 = linesFor(1, text.length - 1);
        added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight));
        update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
        doc.insert(from.line + 1, added$1);
      }
    } else if (text.length == 1) {
      update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
      doc.remove(from.line + 1, nlines);
    } else {
      update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
      update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
      var added$2 = linesFor(1, text.length - 1);
      if (nlines > 1) { doc.remove(from.line + 1, nlines - 1); }
      doc.insert(from.line + 1, added$2);
    }

    signalLater(doc, "change", doc, change);
  }

  // Call f for all linked documents.
  function linkedDocs(doc, f, sharedHistOnly) {
    function propagate(doc, skip, sharedHist) {
      if (doc.linked) { for (var i = 0; i < doc.linked.length; ++i) {
        var rel = doc.linked[i];
        if (rel.doc == skip) { continue }
        var shared = sharedHist && rel.sharedHist;
        if (sharedHistOnly && !shared) { continue }
        f(rel.doc, shared);
        propagate(rel.doc, doc, shared);
      } }
    }
    propagate(doc, null, true);
  }

  // Attach a document to an editor.
  function attachDoc(cm, doc) {
    if (doc.cm) { throw new Error("This document is already in use.") }
    cm.doc = doc;
    doc.cm = cm;
    estimateLineHeights(cm);
    loadMode(cm);
    setDirectionClass(cm);
    cm.options.direction = doc.direction;
    if (!cm.options.lineWrapping) { findMaxLine(cm); }
    cm.options.mode = doc.modeOption;
    regChange(cm);
  }

  function setDirectionClass(cm) {
  (cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl");
  }

  function directionChanged(cm) {
    runInOp(cm, function () {
      setDirectionClass(cm);
      regChange(cm);
    });
  }

  function History(prev) {
    // Arrays of change events and selections. Doing something adds an
    // event to done and clears undo. Undoing moves events from done
    // to undone, redoing moves them in the other direction.
    this.done = []; this.undone = [];
    this.undoDepth = prev ? prev.undoDepth : Infinity;
    // Used to track when changes can be merged into a single undo
    // event
    this.lastModTime = this.lastSelTime = 0;
    this.lastOp = this.lastSelOp = null;
    this.lastOrigin = this.lastSelOrigin = null;
    // Used by the isClean() method
    this.generation = this.maxGeneration = prev ? prev.maxGeneration : 1;
  }

  // Create a history change event from an updateDoc-style change
  // object.
  function historyChangeFromChange(doc, change) {
    var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
    attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
    linkedDocs(doc, function (doc) { return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); }, true);
    return histChange
  }

  // Pop all selection events off the end of a history array. Stop at
  // a change event.
  function clearSelectionEvents(array) {
    while (array.length) {
      var last = lst(array);
      if (last.ranges) { array.pop(); }
      else { break }
    }
  }

  // Find the top change event in the history. Pop off selection
  // events that are in the way.
  function lastChangeEvent(hist, force) {
    if (force) {
      clearSelectionEvents(hist.done);
      return lst(hist.done)
    } else if (hist.done.length && !lst(hist.done).ranges) {
      return lst(hist.done)
    } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
      hist.done.pop();
      return lst(hist.done)
    }
  }

  // Register a change in the history. Merges changes that are within
  // a single operation, or are close together with an origin that
  // allows merging (starting with "+") into a single event.
  function addChangeToHistory(doc, change, selAfter, opId) {
    var hist = doc.history;
    hist.undone.length = 0;
    var time = +new Date, cur;
    var last;

    if ((hist.lastOp == opId ||
         hist.lastOrigin == change.origin && change.origin &&
         ((change.origin.charAt(0) == "+" && hist.lastModTime > time - (doc.cm ? doc.cm.options.historyEventDelay : 500)) ||
          change.origin.charAt(0) == "*")) &&
        (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
      // Merge this change into the last event
      last = lst(cur.changes);
      if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
        // Optimized case for simple insertion -- don't want to add
        // new changesets for every character typed
        last.to = changeEnd(change);
      } else {
        // Add new sub-event
        cur.changes.push(historyChangeFromChange(doc, change));
      }
    } else {
      // Can not be merged, start a new event.
      var before = lst(hist.done);
      if (!before || !before.ranges)
        { pushSelectionToHistory(doc.sel, hist.done); }
      cur = {changes: [historyChangeFromChange(doc, change)],
             generation: hist.generation};
      hist.done.push(cur);
      while (hist.done.length > hist.undoDepth) {
        hist.done.shift();
        if (!hist.done[0].ranges) { hist.done.shift(); }
      }
    }
    hist.done.push(selAfter);
    hist.generation = ++hist.maxGeneration;
    hist.lastModTime = hist.lastSelTime = time;
    hist.lastOp = hist.lastSelOp = opId;
    hist.lastOrigin = hist.lastSelOrigin = change.origin;

    if (!last) { signal(doc, "historyAdded"); }
  }

  function selectionEventCanBeMerged(doc, origin, prev, sel) {
    var ch = origin.charAt(0);
    return ch == "*" ||
      ch == "+" &&
      prev.ranges.length == sel.ranges.length &&
      prev.somethingSelected() == sel.somethingSelected() &&
      new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500)
  }

  // Called whenever the selection changes, sets the new selection as
  // the pending selection in the history, and pushes the old pending
  // selection into the 'done' array when it was significantly
  // different (in number of selected ranges, emptiness, or time).
  function addSelectionToHistory(doc, sel, opId, options) {
    var hist = doc.history, origin = options && options.origin;

    // A new event is started when the previous origin does not match
    // the current, or the origins don't allow matching. Origins
    // starting with * are always merged, those starting with + are
    // merged when similar and close together in time.
    if (opId == hist.lastSelOp ||
        (origin && hist.lastSelOrigin == origin &&
         (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
          selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
      { hist.done[hist.done.length - 1] = sel; }
    else
      { pushSelectionToHistory(sel, hist.done); }

    hist.lastSelTime = +new Date;
    hist.lastSelOrigin = origin;
    hist.lastSelOp = opId;
    if (options && options.clearRedo !== false)
      { clearSelectionEvents(hist.undone); }
  }

  function pushSelectionToHistory(sel, dest) {
    var top = lst(dest);
    if (!(top && top.ranges && top.equals(sel)))
      { dest.push(sel); }
  }

  // Used to store marked span information in the history.
  function attachLocalSpans(doc, change, from, to) {
    var existing = change["spans_" + doc.id], n = 0;
    doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {
      if (line.markedSpans)
        { (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; }
      ++n;
    });
  }

  // When un/re-doing restores text containing marked spans, those
  // that have been explicitly cleared should not be restored.
  function removeClearedSpans(spans) {
    if (!spans) { return null }
    var out;
    for (var i = 0; i < spans.length; ++i) {
      if (spans[i].marker.explicitlyCleared) { if (!out) { out = spans.slice(0, i); } }
      else if (out) { out.push(spans[i]); }
    }
    return !out ? spans : out.length ? out : null
  }

  // Retrieve and filter the old marked spans stored in a change event.
  function getOldSpans(doc, change) {
    var found = change["spans_" + doc.id];
    if (!found) { return null }
    var nw = [];
    for (var i = 0; i < change.text.length; ++i)
      { nw.push(removeClearedSpans(found[i])); }
    return nw
  }

  // Used for un/re-doing changes from the history. Combines the
  // result of computing the existing spans with the set of spans that
  // existed in the history (so that deleting around a span and then
  // undoing brings back the span).
  function mergeOldSpans(doc, change) {
    var old = getOldSpans(doc, change);
    var stretched = stretchSpansOverChange(doc, change);
    if (!old) { return stretched }
    if (!stretched) { return old }

    for (var i = 0; i < old.length; ++i) {
      var oldCur = old[i], stretchCur = stretched[i];
      if (oldCur && stretchCur) {
        spans: for (var j = 0; j < stretchCur.length; ++j) {
          var span = stretchCur[j];
          for (var k = 0; k < oldCur.length; ++k)
            { if (oldCur[k].marker == span.marker) { continue spans } }
          oldCur.push(span);
        }
      } else if (stretchCur) {
        old[i] = stretchCur;
      }
    }
    return old
  }

  // Used both to provide a JSON-safe object in .getHistory, and, when
  // detaching a document, to split the history in two
  function copyHistoryArray(events, newGroup, instantiateSel) {
    var copy = [];
    for (var i = 0; i < events.length; ++i) {
      var event = events[i];
      if (event.ranges) {
        copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
        continue
      }
      var changes = event.changes, newChanges = [];
      copy.push({changes: newChanges});
      for (var j = 0; j < changes.length; ++j) {
        var change = changes[j], m = (void 0);
        newChanges.push({from: change.from, to: change.to, text: change.text});
        if (newGroup) { for (var prop in change) { if (m = prop.match(/^spans_(\d+)$/)) {
          if (indexOf(newGroup, Number(m[1])) > -1) {
            lst(newChanges)[prop] = change[prop];
            delete change[prop];
          }
        } } }
      }
    }
    return copy
  }

  // The 'scroll' parameter given to many of these indicated whether
  // the new cursor position should be scrolled into view after
  // modifying the selection.

  // If shift is held or the extend flag is set, extends a range to
  // include a given position (and optionally a second position).
  // Otherwise, simply returns the range between the given positions.
  // Used for cursor motion and such.
  function extendRange(range, head, other, extend) {
    if (extend) {
      var anchor = range.anchor;
      if (other) {
        var posBefore = cmp(head, anchor) < 0;
        if (posBefore != (cmp(other, anchor) < 0)) {
          anchor = head;
          head = other;
        } else if (posBefore != (cmp(head, other) < 0)) {
          head = other;
        }
      }
      return new Range(anchor, head)
    } else {
      return new Range(other || head, head)
    }
  }

  // Extend the primary selection range, discard the rest.
  function extendSelection(doc, head, other, options, extend) {
    if (extend == null) { extend = doc.cm && (doc.cm.display.shift || doc.extend); }
    setSelection(doc, new Selection([extendRange(doc.sel.primary(), head, other, extend)], 0), options);
  }

  // Extend all selections (pos is an array of selections with length
  // equal the number of selections)
  function extendSelections(doc, heads, options) {
    var out = [];
    var extend = doc.cm && (doc.cm.display.shift || doc.extend);
    for (var i = 0; i < doc.sel.ranges.length; i++)
      { out[i] = extendRange(doc.sel.ranges[i], heads[i], null, extend); }
    var newSel = normalizeSelection(doc.cm, out, doc.sel.primIndex);
    setSelection(doc, newSel, options);
  }

  // Updates a single range in the selection.
  function replaceOneSelection(doc, i, range, options) {
    var ranges = doc.sel.ranges.slice(0);
    ranges[i] = range;
    setSelection(doc, normalizeSelection(doc.cm, ranges, doc.sel.primIndex), options);
  }

  // Reset the selection to a single range.
  function setSimpleSelection(doc, anchor, head, options) {
    setSelection(doc, simpleSelection(anchor, head), options);
  }

  // Give beforeSelectionChange handlers a change to influence a
  // selection update.
  function filterSelectionChange(doc, sel, options) {
    var obj = {
      ranges: sel.ranges,
      update: function(ranges) {
        this.ranges = [];
        for (var i = 0; i < ranges.length; i++)
          { this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
                                     clipPos(doc, ranges[i].head)); }
      },
      origin: options && options.origin
    };
    signal(doc, "beforeSelectionChange", doc, obj);
    if (doc.cm) { signal(doc.cm, "beforeSelectionChange", doc.cm, obj); }
    if (obj.ranges != sel.ranges) { return normalizeSelection(doc.cm, obj.ranges, obj.ranges.length - 1) }
    else { return sel }
  }

  function setSelectionReplaceHistory(doc, sel, options) {
    var done = doc.history.done, last = lst(done);
    if (last && last.ranges) {
      done[done.length - 1] = sel;
      setSelectionNoUndo(doc, sel, options);
    } else {
      setSelection(doc, sel, options);
    }
  }

  // Set a new selection.
  function setSelection(doc, sel, options) {
    setSelectionNoUndo(doc, sel, options);
    addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
  }

  function setSelectionNoUndo(doc, sel, options) {
    if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
      { sel = filterSelectionChange(doc, sel, options); }

    var bias = options && options.bias ||
      (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);
    setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));

    if (!(options && options.scroll === false) && doc.cm && doc.cm.getOption("readOnly") != "nocursor")
      { ensureCursorVisible(doc.cm); }
  }

  function setSelectionInner(doc, sel) {
    if (sel.equals(doc.sel)) { return }

    doc.sel = sel;

    if (doc.cm) {
      doc.cm.curOp.updateInput = 1;
      doc.cm.curOp.selectionChanged = true;
      signalCursorActivity(doc.cm);
    }
    signalLater(doc, "cursorActivity", doc);
  }

  // Verify that the selection does not partially select any atomic
  // marked ranges.
  function reCheckSelection(doc) {
    setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false));
  }

  // Return a selection that does not partially select any atomic
  // ranges.
  function skipAtomicInSelection(doc, sel, bias, mayClear) {
    var out;
    for (var i = 0; i < sel.ranges.length; i++) {
      var range = sel.ranges[i];
      var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i];
      var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear);
      var newHead = range.head == range.anchor ? newAnchor : skipAtomic(doc, range.head, old && old.head, bias, mayClear);
      if (out || newAnchor != range.anchor || newHead != range.head) {
        if (!out) { out = sel.ranges.slice(0, i); }
        out[i] = new Range(newAnchor, newHead);
      }
    }
    return out ? normalizeSelection(doc.cm, out, sel.primIndex) : sel
  }

  function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {
    var line = getLine(doc, pos.line);
    if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
      var sp = line.markedSpans[i], m = sp.marker;

      // Determine if we should prevent the cursor being placed to the left/right of an atomic marker
      // Historically this was determined using the inclusiveLeft/Right option, but the new way to control it
      // is with selectLeft/Right
      var preventCursorLeft = ("selectLeft" in m) ? !m.selectLeft : m.inclusiveLeft;
      var preventCursorRight = ("selectRight" in m) ? !m.selectRight : m.inclusiveRight;

      if ((sp.from == null || (preventCursorLeft ? sp.from <= pos.ch : sp.from < pos.ch)) &&
          (sp.to == null || (preventCursorRight ? sp.to >= pos.ch : sp.to > pos.ch))) {
        if (mayClear) {
          signal(m, "beforeCursorEnter");
          if (m.explicitlyCleared) {
            if (!line.markedSpans) { break }
            else {--i; continue}
          }
        }
        if (!m.atomic) { continue }

        if (oldPos) {
          var near = m.find(dir < 0 ? 1 : -1), diff = (void 0);
          if (dir < 0 ? preventCursorRight : preventCursorLeft)
            { near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null); }
          if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0))
            { return skipAtomicInner(doc, near, pos, dir, mayClear) }
        }

        var far = m.find(dir < 0 ? -1 : 1);
        if (dir < 0 ? preventCursorLeft : preventCursorRight)
          { far = movePos(doc, far, dir, far.line == pos.line ? line : null); }
        return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null
      }
    } }
    return pos
  }

  // Ensure a given position is not inside an atomic range.
  function skipAtomic(doc, pos, oldPos, bias, mayClear) {
    var dir = bias || 1;
    var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) ||
        (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) ||
        skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||
        (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true));
    if (!found) {
      doc.cantEdit = true;
      return Pos(doc.first, 0)
    }
    return found
  }

  function movePos(doc, pos, dir, line) {
    if (dir < 0 && pos.ch == 0) {
      if (pos.line > doc.first) { return clipPos(doc, Pos(pos.line - 1)) }
      else { return null }
    } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {
      if (pos.line < doc.first + doc.size - 1) { return Pos(pos.line + 1, 0) }
      else { return null }
    } else {
      return new Pos(pos.line, pos.ch + dir)
    }
  }

  function selectAll(cm) {
    cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);
  }

  // UPDATING

  // Allow "beforeChange" event handlers to influence a change
  function filterChange(doc, change, update) {
    var obj = {
      canceled: false,
      from: change.from,
      to: change.to,
      text: change.text,
      origin: change.origin,
      cancel: function () { return obj.canceled = true; }
    };
    if (update) { obj.update = function (from, to, text, origin) {
      if (from) { obj.from = clipPos(doc, from); }
      if (to) { obj.to = clipPos(doc, to); }
      if (text) { obj.text = text; }
      if (origin !== undefined) { obj.origin = origin; }
    }; }
    signal(doc, "beforeChange", doc, obj);
    if (doc.cm) { signal(doc.cm, "beforeChange", doc.cm, obj); }

    if (obj.canceled) {
      if (doc.cm) { doc.cm.curOp.updateInput = 2; }
      return null
    }
    return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}
  }

  // Apply a change to a document, and add it to the document's
  // history, and propagating it to all linked documents.
  function makeChange(doc, change, ignoreReadOnly) {
    if (doc.cm) {
      if (!doc.cm.curOp) { return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly) }
      if (doc.cm.state.suppressEdits) { return }
    }

    if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
      change = filterChange(doc, change, true);
      if (!change) { return }
    }

    // Possibly split or suppress the update based on the presence
    // of read-only spans in its range.
    var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
    if (split) {
      for (var i = split.length - 1; i >= 0; --i)
        { makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text, origin: change.origin}); }
    } else {
      makeChangeInner(doc, change);
    }
  }

  function makeChangeInner(doc, change) {
    if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) { return }
    var selAfter = computeSelAfterChange(doc, change);
    addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);

    makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
    var rebased = [];

    linkedDocs(doc, function (doc, sharedHist) {
      if (!sharedHist && indexOf(rebased, doc.history) == -1) {
        rebaseHist(doc.history, change);
        rebased.push(doc.history);
      }
      makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
    });
  }

  // Revert a change stored in a document's history.
  function makeChangeFromHistory(doc, type, allowSelectionOnly) {
    var suppress = doc.cm && doc.cm.state.suppressEdits;
    if (suppress && !allowSelectionOnly) { return }

    var hist = doc.history, event, selAfter = doc.sel;
    var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;

    // Verify that there is a useable event (so that ctrl-z won't
    // needlessly clear selection events)
    var i = 0;
    for (; i < source.length; i++) {
      event = source[i];
      if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
        { break }
    }
    if (i == source.length) { return }
    hist.lastOrigin = hist.lastSelOrigin = null;

    for (;;) {
      event = source.pop();
      if (event.ranges) {
        pushSelectionToHistory(event, dest);
        if (allowSelectionOnly && !event.equals(doc.sel)) {
          setSelection(doc, event, {clearRedo: false});
          return
        }
        selAfter = event;
      } else if (suppress) {
        source.push(event);
        return
      } else { break }
    }

    // Build up a reverse change object to add to the opposite history
    // stack (redo when undoing, and vice versa).
    var antiChanges = [];
    pushSelectionToHistory(selAfter, dest);
    dest.push({changes: antiChanges, generation: hist.generation});
    hist.generation = event.generation || ++hist.maxGeneration;

    var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");

    var loop = function ( i ) {
      var change = event.changes[i];
      change.origin = type;
      if (filter && !filterChange(doc, change, false)) {
        source.length = 0;
        return {}
      }

      antiChanges.push(historyChangeFromChange(doc, change));

      var after = i ? computeSelAfterChange(doc, change) : lst(source);
      makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
      if (!i && doc.cm) { doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}); }
      var rebased = [];

      // Propagate to the linked documents
      linkedDocs(doc, function (doc, sharedHist) {
        if (!sharedHist && indexOf(rebased, doc.history) == -1) {
          rebaseHist(doc.history, change);
          rebased.push(doc.history);
        }
        makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
      });
    };

    for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) {
      var returned = loop( i$1 );

      if ( returned ) return returned.v;
    }
  }

  // Sub-views need their line numbers shifted when text is added
  // above or below them in the parent document.
  function shiftDoc(doc, distance) {
    if (distance == 0) { return }
    doc.first += distance;
    doc.sel = new Selection(map(doc.sel.ranges, function (range) { return new Range(
      Pos(range.anchor.line + distance, range.anchor.ch),
      Pos(range.head.line + distance, range.head.ch)
    ); }), doc.sel.primIndex);
    if (doc.cm) {
      regChange(doc.cm, doc.first, doc.first - distance, distance);
      for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
        { regLineChange(doc.cm, l, "gutter"); }
    }
  }

  // More lower-level change function, handling only a single document
  // (not linked ones).
  function makeChangeSingleDoc(doc, change, selAfter, spans) {
    if (doc.cm && !doc.cm.curOp)
      { return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans) }

    if (change.to.line < doc.first) {
      shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
      return
    }
    if (change.from.line > doc.lastLine()) { return }

    // Clip the change to the size of this doc
    if (change.from.line < doc.first) {
      var shift = change.text.length - 1 - (doc.first - change.from.line);
      shiftDoc(doc, shift);
      change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
                text: [lst(change.text)], origin: change.origin};
    }
    var last = doc.lastLine();
    if (change.to.line > last) {
      change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
                text: [change.text[0]], origin: change.origin};
    }

    change.removed = getBetween(doc, change.from, change.to);

    if (!selAfter) { selAfter = computeSelAfterChange(doc, change); }
    if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans); }
    else { updateDoc(doc, change, spans); }
    setSelectionNoUndo(doc, selAfter, sel_dontScroll);

    if (doc.cantEdit && skipAtomic(doc, Pos(doc.firstLine(), 0)))
      { doc.cantEdit = false; }
  }

  // Handle the interaction of a change to a document with the editor
  // that this document is part of.
  function makeChangeSingleDocInEditor(cm, change, spans) {
    var doc = cm.doc, display = cm.display, from = change.from, to = change.to;

    var recomputeMaxLength = false, checkWidthStart = from.line;
    if (!cm.options.lineWrapping) {
      checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
      doc.iter(checkWidthStart, to.line + 1, function (line) {
        if (line == display.maxLine) {
          recomputeMaxLength = true;
          return true
        }
      });
    }

    if (doc.sel.contains(change.from, change.to) > -1)
      { signalCursorActivity(cm); }

    updateDoc(doc, change, spans, estimateHeight(cm));

    if (!cm.options.lineWrapping) {
      doc.iter(checkWidthStart, from.line + change.text.length, function (line) {
        var len = lineLength(line);
        if (len > display.maxLineLength) {
          display.maxLine = line;
          display.maxLineLength = len;
          display.maxLineChanged = true;
          recomputeMaxLength = false;
        }
      });
      if (recomputeMaxLength) { cm.curOp.updateMaxLine = true; }
    }

    retreatFrontier(doc, from.line);
    startWorker(cm, 400);

    var lendiff = change.text.length - (to.line - from.line) - 1;
    // Remember that these lines changed, for updating the display
    if (change.full)
      { regChange(cm); }
    else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
      { regLineChange(cm, from.line, "text"); }
    else
      { regChange(cm, from.line, to.line + 1, lendiff); }

    var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
    if (changeHandler || changesHandler) {
      var obj = {
        from: from, to: to,
        text: change.text,
        removed: change.removed,
        origin: change.origin
      };
      if (changeHandler) { signalLater(cm, "change", cm, obj); }
      if (changesHandler) { (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); }
    }
    cm.display.selForContextMenu = null;
  }

  function replaceRange(doc, code, from, to, origin) {
    var assign;

    if (!to) { to = from; }
    if (cmp(to, from) < 0) { (assign = [to, from], from = assign[0], to = assign[1]); }
    if (typeof code == "string") { code = doc.splitLines(code); }
    makeChange(doc, {from: from, to: to, text: code, origin: origin});
  }

  // Rebasing/resetting history to deal with externally-sourced changes

  function rebaseHistSelSingle(pos, from, to, diff) {
    if (to < pos.line) {
      pos.line += diff;
    } else if (from < pos.line) {
      pos.line = from;
      pos.ch = 0;
    }
  }

  // Tries to rebase an array of history events given a change in the
  // document. If the change touches the same lines as the event, the
  // event, and everything 'behind' it, is discarded. If the change is
  // before the event, the event's positions are updated. Uses a
  // copy-on-write scheme for the positions, to avoid having to
  // reallocate them all on every rebase, but also avoid problems with
  // shared position objects being unsafely updated.
  function rebaseHistArray(array, from, to, diff) {
    for (var i = 0; i < array.length; ++i) {
      var sub = array[i], ok = true;
      if (sub.ranges) {
        if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }
        for (var j = 0; j < sub.ranges.length; j++) {
          rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
          rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
        }
        continue
      }
      for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) {
        var cur = sub.changes[j$1];
        if (to < cur.from.line) {
          cur.from = Pos(cur.from.line + diff, cur.from.ch);
          cur.to = Pos(cur.to.line + diff, cur.to.ch);
        } else if (from <= cur.to.line) {
          ok = false;
          break
        }
      }
      if (!ok) {
        array.splice(0, i + 1);
        i = 0;
      }
    }
  }

  function rebaseHist(hist, change) {
    var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
    rebaseHistArray(hist.done, from, to, diff);
    rebaseHistArray(hist.undone, from, to, diff);
  }

  // Utility for applying a change to a line by handle or number,
  // returning the number and optionally registering the line as
  // changed.
  function changeLine(doc, handle, changeType, op) {
    var no = handle, line = handle;
    if (typeof handle == "number") { line = getLine(doc, clipLine(doc, handle)); }
    else { no = lineNo(handle); }
    if (no == null) { return null }
    if (op(line, no) && doc.cm) { regLineChange(doc.cm, no, changeType); }
    return line
  }

  // The document is represented as a BTree consisting of leaves, with
  // chunk of lines in them, and branches, with up to ten leaves or
  // other branch nodes below them. The top node is always a branch
  // node, and is the document object itself (meaning it has
  // additional methods and properties).
  //
  // All nodes have parent links. The tree is used both to go from
  // line numbers to line objects, and to go from objects to numbers.
  // It also indexes by height, and is used to convert between height
  // and line object, and to find the total height of the document.
  //
  // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html

  function LeafChunk(lines) {
    this.lines = lines;
    this.parent = null;
    var height = 0;
    for (var i = 0; i < lines.length; ++i) {
      lines[i].parent = this;
      height += lines[i].height;
    }
    this.height = height;
  }

  LeafChunk.prototype = {
    chunkSize: function() { return this.lines.length },

    // Remove the n lines at offset 'at'.
    removeInner: function(at, n) {
      for (var i = at, e = at + n; i < e; ++i) {
        var line = this.lines[i];
        this.height -= line.height;
        cleanUpLine(line);
        signalLater(line, "delete");
      }
      this.lines.splice(at, n);
    },

    // Helper used to collapse a small branch into a single leaf.
    collapse: function(lines) {
      lines.push.apply(lines, this.lines);
    },

    // Insert the given array of lines at offset 'at', count them as
    // having the given height.
    insertInner: function(at, lines, height) {
      this.height += height;
      this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
      for (var i = 0; i < lines.length; ++i) { lines[i].parent = this; }
    },

    // Used to iterate over a part of the tree.
    iterN: function(at, n, op) {
      for (var e = at + n; at < e; ++at)
        { if (op(this.lines[at])) { return true } }
    }
  };

  function BranchChunk(children) {
    this.children = children;
    var size = 0, height = 0;
    for (var i = 0; i < children.length; ++i) {
      var ch = children[i];
      size += ch.chunkSize(); height += ch.height;
      ch.parent = this;
    }
    this.size = size;
    this.height = height;
    this.parent = null;
  }

  BranchChunk.prototype = {
    chunkSize: function() { return this.size },

    removeInner: function(at, n) {
      this.size -= n;
      for (var i = 0; i < this.children.length; ++i) {
        var child = this.children[i], sz = child.chunkSize();
        if (at < sz) {
          var rm = Math.min(n, sz - at), oldHeight = child.height;
          child.removeInner(at, rm);
          this.height -= oldHeight - child.height;
          if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
          if ((n -= rm) == 0) { break }
          at = 0;
        } else { at -= sz; }
      }
      // If the result is smaller than 25 lines, ensure that it is a
      // single leaf node.
      if (this.size - n < 25 &&
          (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
        var lines = [];
        this.collapse(lines);
        this.children = [new LeafChunk(lines)];
        this.children[0].parent = this;
      }
    },

    collapse: function(lines) {
      for (var i = 0; i < this.children.length; ++i) { this.children[i].collapse(lines); }
    },

    insertInner: function(at, lines, height) {
      this.size += lines.length;
      this.height += height;
      for (var i = 0; i < this.children.length; ++i) {
        var child = this.children[i], sz = child.chunkSize();
        if (at <= sz) {
          child.insertInner(at, lines, height);
          if (child.lines && child.lines.length > 50) {
            // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced.
            // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest.
            var remaining = child.lines.length % 25 + 25;
            for (var pos = remaining; pos < child.lines.length;) {
              var leaf = new LeafChunk(child.lines.slice(pos, pos += 25));
              child.height -= leaf.height;
              this.children.splice(++i, 0, leaf);
              leaf.parent = this;
            }
            child.lines = child.lines.slice(0, remaining);
            this.maybeSpill();
          }
          break
        }
        at -= sz;
      }
    },

    // When a node has grown, check whether it should be split.
    maybeSpill: function() {
      if (this.children.length <= 10) { return }
      var me = this;
      do {
        var spilled = me.children.splice(me.children.length - 5, 5);
        var sibling = new BranchChunk(spilled);
        if (!me.parent) { // Become the parent node
          var copy = new BranchChunk(me.children);
          copy.parent = me;
          me.children = [copy, sibling];
          me = copy;
       } else {
          me.size -= sibling.size;
          me.height -= sibling.height;
          var myIndex = indexOf(me.parent.children, me);
          me.parent.children.splice(myIndex + 1, 0, sibling);
        }
        sibling.parent = me.parent;
      } while (me.children.length > 10)
      me.parent.maybeSpill();
    },

    iterN: function(at, n, op) {
      for (var i = 0; i < this.children.length; ++i) {
        var child = this.children[i], sz = child.chunkSize();
        if (at < sz) {
          var used = Math.min(n, sz - at);
          if (child.iterN(at, used, op)) { return true }
          if ((n -= used) == 0) { break }
          at = 0;
        } else { at -= sz; }
      }
    }
  };

  // Line widgets are block elements displayed above or below a line.

  var LineWidget = function(doc, node, options) {
    if (options) { for (var opt in options) { if (options.hasOwnProperty(opt))
      { this[opt] = options[opt]; } } }
    this.doc = doc;
    this.node = node;
  };

  LineWidget.prototype.clear = function () {
    var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
    if (no == null || !ws) { return }
    for (var i = 0; i < ws.length; ++i) { if (ws[i] == this) { ws.splice(i--, 1); } }
    if (!ws.length) { line.widgets = null; }
    var height = widgetHeight(this);
    updateLineHeight(line, Math.max(0, line.height - height));
    if (cm) {
      runInOp(cm, function () {
        adjustScrollWhenAboveVisible(cm, line, -height);
        regLineChange(cm, no, "widget");
      });
      signalLater(cm, "lineWidgetCleared", cm, this, no);
    }
  };

  LineWidget.prototype.changed = function () {
      var this$1 = this;

    var oldH = this.height, cm = this.doc.cm, line = this.line;
    this.height = null;
    var diff = widgetHeight(this) - oldH;
    if (!diff) { return }
    if (!lineIsHidden(this.doc, line)) { updateLineHeight(line, line.height + diff); }
    if (cm) {
      runInOp(cm, function () {
        cm.curOp.forceUpdate = true;
        adjustScrollWhenAboveVisible(cm, line, diff);
        signalLater(cm, "lineWidgetChanged", cm, this$1, lineNo(line));
      });
    }
  };
  eventMixin(LineWidget);

  function adjustScrollWhenAboveVisible(cm, line, diff) {
    if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
      { addToScrollTop(cm, diff); }
  }

  function addLineWidget(doc, handle, node, options) {
    var widget = new LineWidget(doc, node, options);
    var cm = doc.cm;
    if (cm && widget.noHScroll) { cm.display.alignWidgets = true; }
    changeLine(doc, handle, "widget", function (line) {
      var widgets = line.widgets || (line.widgets = []);
      if (widget.insertAt == null) { widgets.push(widget); }
      else { widgets.splice(Math.min(widgets.length, Math.max(0, widget.insertAt)), 0, widget); }
      widget.line = line;
      if (cm && !lineIsHidden(doc, line)) {
        var aboveVisible = heightAtLine(line) < doc.scrollTop;
        updateLineHeight(line, line.height + widgetHeight(widget));
        if (aboveVisible) { addToScrollTop(cm, widget.height); }
        cm.curOp.forceUpdate = true;
      }
      return true
    });
    if (cm) { signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle)); }
    return widget
  }

  // TEXTMARKERS

  // Created with markText and setBookmark methods. A TextMarker is a
  // handle that can be used to clear or find a marked position in the
  // document. Line objects hold arrays (markedSpans) containing
  // {from, to, marker} object pointing to such marker objects, and
  // indicating that such a marker is present on that line. Multiple
  // lines may point to the same marker when it spans across lines.
  // The spans will have null for their from/to properties when the
  // marker continues beyond the start/end of the line. Markers have
  // links back to the lines they currently touch.

  // Collapsed markers have unique ids, in order to be able to order
  // them, which is needed for uniquely determining an outer marker
  // when they overlap (they may nest, but not partially overlap).
  var nextMarkerId = 0;

  var TextMarker = function(doc, type) {
    this.lines = [];
    this.type = type;
    this.doc = doc;
    this.id = ++nextMarkerId;
  };

  // Clear the marker.
  TextMarker.prototype.clear = function () {
    if (this.explicitlyCleared) { return }
    var cm = this.doc.cm, withOp = cm && !cm.curOp;
    if (withOp) { startOperation(cm); }
    if (hasHandler(this, "clear")) {
      var found = this.find();
      if (found) { signalLater(this, "clear", found.from, found.to); }
    }
    var min = null, max = null;
    for (var i = 0; i < this.lines.length; ++i) {
      var line = this.lines[i];
      var span = getMarkedSpanFor(line.markedSpans, this);
      if (cm && !this.collapsed) { regLineChange(cm, lineNo(line), "text"); }
      else if (cm) {
        if (span.to != null) { max = lineNo(line); }
        if (span.from != null) { min = lineNo(line); }
      }
      line.markedSpans = removeMarkedSpan(line.markedSpans, span);
      if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm)
        { updateLineHeight(line, textHeight(cm.display)); }
    }
    if (cm && this.collapsed && !cm.options.lineWrapping) { for (var i$1 = 0; i$1 < this.lines.length; ++i$1) {
      var visual = visualLine(this.lines[i$1]), len = lineLength(visual);
      if (len > cm.display.maxLineLength) {
        cm.display.maxLine = visual;
        cm.display.maxLineLength = len;
        cm.display.maxLineChanged = true;
      }
    } }

    if (min != null && cm && this.collapsed) { regChange(cm, min, max + 1); }
    this.lines.length = 0;
    this.explicitlyCleared = true;
    if (this.atomic && this.doc.cantEdit) {
      this.doc.cantEdit = false;
      if (cm) { reCheckSelection(cm.doc); }
    }
    if (cm) { signalLater(cm, "markerCleared", cm, this, min, max); }
    if (withOp) { endOperation(cm); }
    if (this.parent) { this.parent.clear(); }
  };

  // Find the position of the marker in the document. Returns a {from,
  // to} object by default. Side can be passed to get a specific side
  // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
  // Pos objects returned contain a line object, rather than a line
  // number (used to prevent looking up the same line twice).
  TextMarker.prototype.find = function (side, lineObj) {
    if (side == null && this.type == "bookmark") { side = 1; }
    var from, to;
    for (var i = 0; i < this.lines.length; ++i) {
      var line = this.lines[i];
      var span = getMarkedSpanFor(line.markedSpans, this);
      if (span.from != null) {
        from = Pos(lineObj ? line : lineNo(line), span.from);
        if (side == -1) { return from }
      }
      if (span.to != null) {
        to = Pos(lineObj ? line : lineNo(line), span.to);
        if (side == 1) { return to }
      }
    }
    return from && {from: from, to: to}
  };

  // Signals that the marker's widget changed, and surrounding layout
  // should be recomputed.
  TextMarker.prototype.changed = function () {
      var this$1 = this;

    var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
    if (!pos || !cm) { return }
    runInOp(cm, function () {
      var line = pos.line, lineN = lineNo(pos.line);
      var view = findViewForLine(cm, lineN);
      if (view) {
        clearLineMeasurementCacheFor(view);
        cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
      }
      cm.curOp.updateMaxLine = true;
      if (!lineIsHidden(widget.doc, line) && widget.height != null) {
        var oldHeight = widget.height;
        widget.height = null;
        var dHeight = widgetHeight(widget) - oldHeight;
        if (dHeight)
          { updateLineHeight(line, line.height + dHeight); }
      }
      signalLater(cm, "markerChanged", cm, this$1);
    });
  };

  TextMarker.prototype.attachLine = function (line) {
    if (!this.lines.length && this.doc.cm) {
      var op = this.doc.cm.curOp;
      if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
        { (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); }
    }
    this.lines.push(line);
  };

  TextMarker.prototype.detachLine = function (line) {
    this.lines.splice(indexOf(this.lines, line), 1);
    if (!this.lines.length && this.doc.cm) {
      var op = this.doc.cm.curOp
      ;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
    }
  };
  eventMixin(TextMarker);

  // Create a marker, wire it up to the right lines, and
  function markText(doc, from, to, options, type) {
    // Shared markers (across linked documents) are handled separately
    // (markTextShared will call out to this again, once per
    // document).
    if (options && options.shared) { return markTextShared(doc, from, to, options, type) }
    // Ensure we are in an operation.
    if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, markText)(doc, from, to, options, type) }

    var marker = new TextMarker(doc, type), diff = cmp(from, to);
    if (options) { copyObj(options, marker, false); }
    // Don't connect empty markers unless clearWhenEmpty is false
    if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
      { return marker }
    if (marker.replacedWith) {
      // Showing up as a widget implies collapsed (widget replaces text)
      marker.collapsed = true;
      marker.widgetNode = eltP("span", [marker.replacedWith], "CodeMirror-widget");
      if (!options.handleMouseEvents) { marker.widgetNode.setAttribute("cm-ignore-events", "true"); }
      if (options.insertLeft) { marker.widgetNode.insertLeft = true; }
    }
    if (marker.collapsed) {
      if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
          from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
        { throw new Error("Inserting collapsed marker partially overlapping an existing one") }
      seeCollapsedSpans();
    }

    if (marker.addToHistory)
      { addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN); }

    var curLine = from.line, cm = doc.cm, updateMaxLine;
    doc.iter(curLine, to.line + 1, function (line) {
      if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
        { updateMaxLine = true; }
      if (marker.collapsed && curLine != from.line) { updateLineHeight(line, 0); }
      addMarkedSpan(line, new MarkedSpan(marker,
                                         curLine == from.line ? from.ch : null,
                                         curLine == to.line ? to.ch : null), doc.cm && doc.cm.curOp);
      ++curLine;
    });
    // lineIsHidden depends on the presence of the spans, so needs a second pass
    if (marker.collapsed) { doc.iter(from.line, to.line + 1, function (line) {
      if (lineIsHidden(doc, line)) { updateLineHeight(line, 0); }
    }); }

    if (marker.clearOnEnter) { on(marker, "beforeCursorEnter", function () { return marker.clear(); }); }

    if (marker.readOnly) {
      seeReadOnlySpans();
      if (doc.history.done.length || doc.history.undone.length)
        { doc.clearHistory(); }
    }
    if (marker.collapsed) {
      marker.id = ++nextMarkerId;
      marker.atomic = true;
    }
    if (cm) {
      // Sync editor state
      if (updateMaxLine) { cm.curOp.updateMaxLine = true; }
      if (marker.collapsed)
        { regChange(cm, from.line, to.line + 1); }
      else if (marker.className || marker.startStyle || marker.endStyle || marker.css ||
               marker.attributes || marker.title)
        { for (var i = from.line; i <= to.line; i++) { regLineChange(cm, i, "text"); } }
      if (marker.atomic) { reCheckSelection(cm.doc); }
      signalLater(cm, "markerAdded", cm, marker);
    }
    return marker
  }

  // SHARED TEXTMARKERS

  // A shared marker spans multiple linked documents. It is
  // implemented as a meta-marker-object controlling multiple normal
  // markers.
  var SharedTextMarker = function(markers, primary) {
    this.markers = markers;
    this.primary = primary;
    for (var i = 0; i < markers.length; ++i)
      { markers[i].parent = this; }
  };

  SharedTextMarker.prototype.clear = function () {
    if (this.explicitlyCleared) { return }
    this.explicitlyCleared = true;
    for (var i = 0; i < this.markers.length; ++i)
      { this.markers[i].clear(); }
    signalLater(this, "clear");
  };

  SharedTextMarker.prototype.find = function (side, lineObj) {
    return this.primary.find(side, lineObj)
  };
  eventMixin(SharedTextMarker);

  function markTextShared(doc, from, to, options, type) {
    options = copyObj(options);
    options.shared = false;
    var markers = [markText(doc, from, to, options, type)], primary = markers[0];
    var widget = options.widgetNode;
    linkedDocs(doc, function (doc) {
      if (widget) { options.widgetNode = widget.cloneNode(true); }
      markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
      for (var i = 0; i < doc.linked.length; ++i)
        { if (doc.linked[i].isParent) { return } }
      primary = lst(markers);
    });
    return new SharedTextMarker(markers, primary)
  }

  function findSharedMarkers(doc) {
    return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { return m.parent; })
  }

  function copySharedMarkers(doc, markers) {
    for (var i = 0; i < markers.length; i++) {
      var marker = markers[i], pos = marker.find();
      var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
      if (cmp(mFrom, mTo)) {
        var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
        marker.markers.push(subMark);
        subMark.parent = marker;
      }
    }
  }

  function detachSharedMarkers(markers) {
    var loop = function ( i ) {
      var marker = markers[i], linked = [marker.primary.doc];
      linkedDocs(marker.primary.doc, function (d) { return linked.push(d); });
      for (var j = 0; j < marker.markers.length; j++) {
        var subMarker = marker.markers[j];
        if (indexOf(linked, subMarker.doc) == -1) {
          subMarker.parent = null;
          marker.markers.splice(j--, 1);
        }
      }
    };

    for (var i = 0; i < markers.length; i++) loop( i );
  }

  var nextDocId = 0;
  var Doc = function(text, mode, firstLine, lineSep, direction) {
    if (!(this instanceof Doc)) { return new Doc(text, mode, firstLine, lineSep, direction) }
    if (firstLine == null) { firstLine = 0; }

    BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
    this.first = firstLine;
    this.scrollTop = this.scrollLeft = 0;
    this.cantEdit = false;
    this.cleanGeneration = 1;
    this.modeFrontier = this.highlightFrontier = firstLine;
    var start = Pos(firstLine, 0);
    this.sel = simpleSelection(start);
    this.history = new History(null);
    this.id = ++nextDocId;
    this.modeOption = mode;
    this.lineSep = lineSep;
    this.direction = (direction == "rtl") ? "rtl" : "ltr";
    this.extend = false;

    if (typeof text == "string") { text = this.splitLines(text); }
    updateDoc(this, {from: start, to: start, text: text});
    setSelection(this, simpleSelection(start), sel_dontScroll);
  };

  Doc.prototype = createObj(BranchChunk.prototype, {
    constructor: Doc,
    // Iterate over the document. Supports two forms -- with only one
    // argument, it calls that for each line in the document. With
    // three, it iterates over the range given by the first two (with
    // the second being non-inclusive).
    iter: function(from, to, op) {
      if (op) { this.iterN(from - this.first, to - from, op); }
      else { this.iterN(this.first, this.first + this.size, from); }
    },

    // Non-public interface for adding and removing lines.
    insert: function(at, lines) {
      var height = 0;
      for (var i = 0; i < lines.length; ++i) { height += lines[i].height; }
      this.insertInner(at - this.first, lines, height);
    },
    remove: function(at, n) { this.removeInner(at - this.first, n); },

    // From here, the methods are part of the public interface. Most
    // are also available from CodeMirror (editor) instances.

    getValue: function(lineSep) {
      var lines = getLines(this, this.first, this.first + this.size);
      if (lineSep === false) { return lines }
      return lines.join(lineSep || this.lineSeparator())
    },
    setValue: docMethodOp(function(code) {
      var top = Pos(this.first, 0), last = this.first + this.size - 1;
      makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
                        text: this.splitLines(code), origin: "setValue", full: true}, true);
      if (this.cm) { scrollToCoords(this.cm, 0, 0); }
      setSelection(this, simpleSelection(top), sel_dontScroll);
    }),
    replaceRange: function(code, from, to, origin) {
      from = clipPos(this, from);
      to = to ? clipPos(this, to) : from;
      replaceRange(this, code, from, to, origin);
    },
    getRange: function(from, to, lineSep) {
      var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
      if (lineSep === false) { return lines }
      if (lineSep === '') { return lines.join('') }
      return lines.join(lineSep || this.lineSeparator())
    },

    getLine: function(line) {var l = this.getLineHandle(line); return l && l.text},

    getLineHandle: function(line) {if (isLine(this, line)) { return getLine(this, line) }},
    getLineNumber: function(line) {return lineNo(line)},

    getLineHandleVisualStart: function(line) {
      if (typeof line == "number") { line = getLine(this, line); }
      return visualLine(line)
    },

    lineCount: function() {return this.size},
    firstLine: function() {return this.first},
    lastLine: function() {return this.first + this.size - 1},

    clipPos: function(pos) {return clipPos(this, pos)},

    getCursor: function(start) {
      var range = this.sel.primary(), pos;
      if (start == null || start == "head") { pos = range.head; }
      else if (start == "anchor") { pos = range.anchor; }
      else if (start == "end" || start == "to" || start === false) { pos = range.to(); }
      else { pos = range.from(); }
      return pos
    },
    listSelections: function() { return this.sel.ranges },
    somethingSelected: function() {return this.sel.somethingSelected()},

    setCursor: docMethodOp(function(line, ch, options) {
      setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
    }),
    setSelection: docMethodOp(function(anchor, head, options) {
      setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
    }),
    extendSelection: docMethodOp(function(head, other, options) {
      extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
    }),
    extendSelections: docMethodOp(function(heads, options) {
      extendSelections(this, clipPosArray(this, heads), options);
    }),
    extendSelectionsBy: docMethodOp(function(f, options) {
      var heads = map(this.sel.ranges, f);
      extendSelections(this, clipPosArray(this, heads), options);
    }),
    setSelections: docMethodOp(function(ranges, primary, options) {
      if (!ranges.length) { return }
      var out = [];
      for (var i = 0; i < ranges.length; i++)
        { out[i] = new Range(clipPos(this, ranges[i].anchor),
                           clipPos(this, ranges[i].head || ranges[i].anchor)); }
      if (primary == null) { primary = Math.min(ranges.length - 1, this.sel.primIndex); }
      setSelection(this, normalizeSelection(this.cm, out, primary), options);
    }),
    addSelection: docMethodOp(function(anchor, head, options) {
      var ranges = this.sel.ranges.slice(0);
      ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
      setSelection(this, normalizeSelection(this.cm, ranges, ranges.length - 1), options);
    }),

    getSelection: function(lineSep) {
      var ranges = this.sel.ranges, lines;
      for (var i = 0; i < ranges.length; i++) {
        var sel = getBetween(this, ranges[i].from(), ranges[i].to());
        lines = lines ? lines.concat(sel) : sel;
      }
      if (lineSep === false) { return lines }
      else { return lines.join(lineSep || this.lineSeparator()) }
    },
    getSelections: function(lineSep) {
      var parts = [], ranges = this.sel.ranges;
      for (var i = 0; i < ranges.length; i++) {
        var sel = getBetween(this, ranges[i].from(), ranges[i].to());
        if (lineSep !== false) { sel = sel.join(lineSep || this.lineSeparator()); }
        parts[i] = sel;
      }
      return parts
    },
    replaceSelection: function(code, collapse, origin) {
      var dup = [];
      for (var i = 0; i < this.sel.ranges.length; i++)
        { dup[i] = code; }
      this.replaceSelections(dup, collapse, origin || "+input");
    },
    replaceSelections: docMethodOp(function(code, collapse, origin) {
      var changes = [], sel = this.sel;
      for (var i = 0; i < sel.ranges.length; i++) {
        var range = sel.ranges[i];
        changes[i] = {from: range.from(), to: range.to(), text: this.splitLines(code[i]), origin: origin};
      }
      var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
      for (var i$1 = changes.length - 1; i$1 >= 0; i$1--)
        { makeChange(this, changes[i$1]); }
      if (newSel) { setSelectionReplaceHistory(this, newSel); }
      else if (this.cm) { ensureCursorVisible(this.cm); }
    }),
    undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}),
    redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}),
    undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}),
    redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}),

    setExtending: function(val) {this.extend = val;},
    getExtending: function() {return this.extend},

    historySize: function() {
      var hist = this.history, done = 0, undone = 0;
      for (var i = 0; i < hist.done.length; i++) { if (!hist.done[i].ranges) { ++done; } }
      for (var i$1 = 0; i$1 < hist.undone.length; i$1++) { if (!hist.undone[i$1].ranges) { ++undone; } }
      return {undo: done, redo: undone}
    },
    clearHistory: function() {
      var this$1 = this;

      this.history = new History(this.history);
      linkedDocs(this, function (doc) { return doc.history = this$1.history; }, true);
    },

    markClean: function() {
      this.cleanGeneration = this.changeGeneration(true);
    },
    changeGeneration: function(forceSplit) {
      if (forceSplit)
        { this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; }
      return this.history.generation
    },
    isClean: function (gen) {
      return this.history.generation == (gen || this.cleanGeneration)
    },

    getHistory: function() {
      return {done: copyHistoryArray(this.history.done),
              undone: copyHistoryArray(this.history.undone)}
    },
    setHistory: function(histData) {
      var hist = this.history = new History(this.history);
      hist.done = copyHistoryArray(histData.done.slice(0), null, true);
      hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
    },

    setGutterMarker: docMethodOp(function(line, gutterID, value) {
      return changeLine(this, line, "gutter", function (line) {
        var markers = line.gutterMarkers || (line.gutterMarkers = {});
        markers[gutterID] = value;
        if (!value && isEmpty(markers)) { line.gutterMarkers = null; }
        return true
      })
    }),

    clearGutter: docMethodOp(function(gutterID) {
      var this$1 = this;

      this.iter(function (line) {
        if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
          changeLine(this$1, line, "gutter", function () {
            line.gutterMarkers[gutterID] = null;
            if (isEmpty(line.gutterMarkers)) { line.gutterMarkers = null; }
            return true
          });
        }
      });
    }),

    lineInfo: function(line) {
      var n;
      if (typeof line == "number") {
        if (!isLine(this, line)) { return null }
        n = line;
        line = getLine(this, line);
        if (!line) { return null }
      } else {
        n = lineNo(line);
        if (n == null) { return null }
      }
      return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
              textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
              widgets: line.widgets}
    },

    addLineClass: docMethodOp(function(handle, where, cls) {
      return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
        var prop = where == "text" ? "textClass"
                 : where == "background" ? "bgClass"
                 : where == "gutter" ? "gutterClass" : "wrapClass";
        if (!line[prop]) { line[prop] = cls; }
        else if (classTest(cls).test(line[prop])) { return false }
        else { line[prop] += " " + cls; }
        return true
      })
    }),
    removeLineClass: docMethodOp(function(handle, where, cls) {
      return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
        var prop = where == "text" ? "textClass"
                 : where == "background" ? "bgClass"
                 : where == "gutter" ? "gutterClass" : "wrapClass";
        var cur = line[prop];
        if (!cur) { return false }
        else if (cls == null) { line[prop] = null; }
        else {
          var found = cur.match(classTest(cls));
          if (!found) { return false }
          var end = found.index + found[0].length;
          line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
        }
        return true
      })
    }),

    addLineWidget: docMethodOp(function(handle, node, options) {
      return addLineWidget(this, handle, node, options)
    }),
    removeLineWidget: function(widget) { widget.clear(); },

    markText: function(from, to, options) {
      return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range")
    },
    setBookmark: function(pos, options) {
      var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
                      insertLeft: options && options.insertLeft,
                      clearWhenEmpty: false, shared: options && options.shared,
                      handleMouseEvents: options && options.handleMouseEvents};
      pos = clipPos(this, pos);
      return markText(this, pos, pos, realOpts, "bookmark")
    },
    findMarksAt: function(pos) {
      pos = clipPos(this, pos);
      var markers = [], spans = getLine(this, pos.line).markedSpans;
      if (spans) { for (var i = 0; i < spans.length; ++i) {
        var span = spans[i];
        if ((span.from == null || span.from <= pos.ch) &&
            (span.to == null || span.to >= pos.ch))
          { markers.push(span.marker.parent || span.marker); }
      } }
      return markers
    },
    findMarks: function(from, to, filter) {
      from = clipPos(this, from); to = clipPos(this, to);
      var found = [], lineNo = from.line;
      this.iter(from.line, to.line + 1, function (line) {
        var spans = line.markedSpans;
        if (spans) { for (var i = 0; i < spans.length; i++) {
          var span = spans[i];
          if (!(span.to != null && lineNo == from.line && from.ch >= span.to ||
                span.from == null && lineNo != from.line ||
                span.from != null && lineNo == to.line && span.from >= to.ch) &&
              (!filter || filter(span.marker)))
            { found.push(span.marker.parent || span.marker); }
        } }
        ++lineNo;
      });
      return found
    },
    getAllMarks: function() {
      var markers = [];
      this.iter(function (line) {
        var sps = line.markedSpans;
        if (sps) { for (var i = 0; i < sps.length; ++i)
          { if (sps[i].from != null) { markers.push(sps[i].marker); } } }
      });
      return markers
    },

    posFromIndex: function(off) {
      var ch, lineNo = this.first, sepSize = this.lineSeparator().length;
      this.iter(function (line) {
        var sz = line.text.length + sepSize;
        if (sz > off) { ch = off; return true }
        off -= sz;
        ++lineNo;
      });
      return clipPos(this, Pos(lineNo, ch))
    },
    indexFromPos: function (coords) {
      coords = clipPos(this, coords);
      var index = coords.ch;
      if (coords.line < this.first || coords.ch < 0) { return 0 }
      var sepSize = this.lineSeparator().length;
      this.iter(this.first, coords.line, function (line) { // iter aborts when callback returns a truthy value
        index += line.text.length + sepSize;
      });
      return index
    },

    copy: function(copyHistory) {
      var doc = new Doc(getLines(this, this.first, this.first + this.size),
                        this.modeOption, this.first, this.lineSep, this.direction);
      doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
      doc.sel = this.sel;
      doc.extend = false;
      if (copyHistory) {
        doc.history.undoDepth = this.history.undoDepth;
        doc.setHistory(this.getHistory());
      }
      return doc
    },

    linkedDoc: function(options) {
      if (!options) { options = {}; }
      var from = this.first, to = this.first + this.size;
      if (options.from != null && options.from > from) { from = options.from; }
      if (options.to != null && options.to < to) { to = options.to; }
      var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction);
      if (options.sharedHist) { copy.history = this.history
      ; }(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
      copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
      copySharedMarkers(copy, findSharedMarkers(this));
      return copy
    },
    unlinkDoc: function(other) {
      if (other instanceof CodeMirror) { other = other.doc; }
      if (this.linked) { for (var i = 0; i < this.linked.length; ++i) {
        var link = this.linked[i];
        if (link.doc != other) { continue }
        this.linked.splice(i, 1);
        other.unlinkDoc(this);
        detachSharedMarkers(findSharedMarkers(this));
        break
      } }
      // If the histories were shared, split them again
      if (other.history == this.history) {
        var splitIds = [other.id];
        linkedDocs(other, function (doc) { return splitIds.push(doc.id); }, true);
        other.history = new History(null);
        other.history.done = copyHistoryArray(this.history.done, splitIds);
        other.history.undone = copyHistoryArray(this.history.undone, splitIds);
      }
    },
    iterLinkedDocs: function(f) {linkedDocs(this, f);},

    getMode: function() {return this.mode},
    getEditor: function() {return this.cm},

    splitLines: function(str) {
      if (this.lineSep) { return str.split(this.lineSep) }
      return splitLinesAuto(str)
    },
    lineSeparator: function() { return this.lineSep || "\n" },

    setDirection: docMethodOp(function (dir) {
      if (dir != "rtl") { dir = "ltr"; }
      if (dir == this.direction) { return }
      this.direction = dir;
      this.iter(function (line) { return line.order = null; });
      if (this.cm) { directionChanged(this.cm); }
    })
  });

  // Public alias.
  Doc.prototype.eachLine = Doc.prototype.iter;

  // Kludge to work around strange IE behavior where it'll sometimes
  // re-fire a series of drag-related events right after the drop (#1551)
  var lastDrop = 0;

  function onDrop(e) {
    var cm = this;
    clearDragCursor(cm);
    if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
      { return }
    e_preventDefault(e);
    if (ie) { lastDrop = +new Date; }
    var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
    if (!pos || cm.isReadOnly()) { return }
    // Might be a file drop, in which case we simply extract the text
    // and insert it.
    if (files && files.length && window.FileReader && window.File) {
      var n = files.length, text = Array(n), read = 0;
      var markAsReadAndPasteIfAllFilesAreRead = function () {
        if (++read == n) {
          operation(cm, function () {
            pos = clipPos(cm.doc, pos);
            var change = {from: pos, to: pos,
                          text: cm.doc.splitLines(
                              text.filter(function (t) { return t != null; }).join(cm.doc.lineSeparator())),
                          origin: "paste"};
            makeChange(cm.doc, change);
            setSelectionReplaceHistory(cm.doc, simpleSelection(clipPos(cm.doc, pos), clipPos(cm.doc, changeEnd(change))));
          })();
        }
      };
      var readTextFromFile = function (file, i) {
        if (cm.options.allowDropFileTypes &&
            indexOf(cm.options.allowDropFileTypes, file.type) == -1) {
          markAsReadAndPasteIfAllFilesAreRead();
          return
        }
        var reader = new FileReader;
        reader.onerror = function () { return markAsReadAndPasteIfAllFilesAreRead(); };
        reader.onload = function () {
          var content = reader.result;
          if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) {
            markAsReadAndPasteIfAllFilesAreRead();
            return
          }
          text[i] = content;
          markAsReadAndPasteIfAllFilesAreRead();
        };
        reader.readAsText(file);
      };
      for (var i = 0; i < files.length; i++) { readTextFromFile(files[i], i); }
    } else { // Normal drop
      // Don't do a replace if the drop happened inside of the selected text.
      if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
        cm.state.draggingText(e);
        // Ensure the editor is re-focused
        setTimeout(function () { return cm.display.input.focus(); }, 20);
        return
      }
      try {
        var text$1 = e.dataTransfer.getData("Text");
        if (text$1) {
          var selected;
          if (cm.state.draggingText && !cm.state.draggingText.copy)
            { selected = cm.listSelections(); }
          setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
          if (selected) { for (var i$1 = 0; i$1 < selected.length; ++i$1)
            { replaceRange(cm.doc, "", selected[i$1].anchor, selected[i$1].head, "drag"); } }
          cm.replaceSelection(text$1, "around", "paste");
          cm.display.input.focus();
        }
      }
      catch(e$1){}
    }
  }

  function onDragStart(cm, e) {
    if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return }
    if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return }

    e.dataTransfer.setData("Text", cm.getSelection());
    e.dataTransfer.effectAllowed = "copyMove";

    // Use dummy image instead of default browsers image.
    // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
    if (e.dataTransfer.setDragImage && !safari) {
      var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
      img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
      if (presto) {
        img.width = img.height = 1;
        cm.display.wrapper.appendChild(img);
        // Force a relayout, or Opera won't use our image for some obscure reason
        img._top = img.offsetTop;
      }
      e.dataTransfer.setDragImage(img, 0, 0);
      if (presto) { img.parentNode.removeChild(img); }
    }
  }

  function onDragOver(cm, e) {
    var pos = posFromMouse(cm, e);
    if (!pos) { return }
    var frag = document.createDocumentFragment();
    drawSelectionCursor(cm, pos, frag);
    if (!cm.display.dragCursor) {
      cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors");
      cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv);
    }
    removeChildrenAndAdd(cm.display.dragCursor, frag);
  }

  function clearDragCursor(cm) {
    if (cm.display.dragCursor) {
      cm.display.lineSpace.removeChild(cm.display.dragCursor);
      cm.display.dragCursor = null;
    }
  }

  // These must be handled carefully, because naively registering a
  // handler for each editor will cause the editors to never be
  // garbage collected.

  function forEachCodeMirror(f) {
    if (!document.getElementsByClassName) { return }
    var byClass = document.getElementsByClassName("CodeMirror"), editors = [];
    for (var i = 0; i < byClass.length; i++) {
      var cm = byClass[i].CodeMirror;
      if (cm) { editors.push(cm); }
    }
    if (editors.length) { editors[0].operation(function () {
      for (var i = 0; i < editors.length; i++) { f(editors[i]); }
    }); }
  }

  var globalsRegistered = false;
  function ensureGlobalHandlers() {
    if (globalsRegistered) { return }
    registerGlobalHandlers();
    globalsRegistered = true;
  }
  function registerGlobalHandlers() {
    // When the window resizes, we need to refresh active editors.
    var resizeTimer;
    on(window, "resize", function () {
      if (resizeTimer == null) { resizeTimer = setTimeout(function () {
        resizeTimer = null;
        forEachCodeMirror(onResize);
      }, 100); }
    });
    // When the window loses focus, we want to show the editor as blurred
    on(window, "blur", function () { return forEachCodeMirror(onBlur); });
  }
  // Called when the window resizes
  function onResize(cm) {
    var d = cm.display;
    // Might be a text scaling operation, clear size caches.
    d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
    d.scrollbarsClipped = false;
    cm.setSize();
  }

  var keyNames = {
    3: "Pause", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
    19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
    36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
    46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod",
    106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 145: "ScrollLock",
    173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
    221: "]", 222: "'", 224: "Mod", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
    63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"
  };

  // Number keys
  for (var i = 0; i < 10; i++) { keyNames[i + 48] = keyNames[i + 96] = String(i); }
  // Alphabetic keys
  for (var i$1 = 65; i$1 <= 90; i$1++) { keyNames[i$1] = String.fromCharCode(i$1); }
  // Function keys
  for (var i$2 = 1; i$2 <= 12; i$2++) { keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2; }

  var keyMap = {};

  keyMap.basic = {
    "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
    "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
    "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
    "Tab": "defaultTab", "Shift-Tab": "indentAuto",
    "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
    "Esc": "singleSelection"
  };
  // Note that the save and find-related commands aren't defined by
  // default. User code or addons can define them. Unknown commands
  // are simply ignored.
  keyMap.pcDefault = {
    "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
    "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
    "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
    "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
    "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
    "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
    "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
    "fallthrough": "basic"
  };
  // Very basic readline/emacs-style bindings, which are standard on Mac.
  keyMap.emacsy = {
    "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
    "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd", "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp",
    "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine",
    "Ctrl-T": "transposeChars", "Ctrl-O": "openLine"
  };
  keyMap.macDefault = {
    "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
    "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
    "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
    "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
    "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
    "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
    "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
    "fallthrough": ["basic", "emacsy"]
  };
  keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;

  // KEYMAP DISPATCH

  function normalizeKeyName(name) {
    var parts = name.split(/-(?!$)/);
    name = parts[parts.length - 1];
    var alt, ctrl, shift, cmd;
    for (var i = 0; i < parts.length - 1; i++) {
      var mod = parts[i];
      if (/^(cmd|meta|m)$/i.test(mod)) { cmd = true; }
      else if (/^a(lt)?$/i.test(mod)) { alt = true; }
      else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true; }
      else if (/^s(hift)?$/i.test(mod)) { shift = true; }
      else { throw new Error("Unrecognized modifier name: " + mod) }
    }
    if (alt) { name = "Alt-" + name; }
    if (ctrl) { name = "Ctrl-" + name; }
    if (cmd) { name = "Cmd-" + name; }
    if (shift) { name = "Shift-" + name; }
    return name
  }

  // This is a kludge to keep keymaps mostly working as raw objects
  // (backwards compatibility) while at the same time support features
  // like normalization and multi-stroke key bindings. It compiles a
  // new normalized keymap, and then updates the old object to reflect
  // this.
  function normalizeKeyMap(keymap) {
    var copy = {};
    for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) {
      var value = keymap[keyname];
      if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue }
      if (value == "...") { delete keymap[keyname]; continue }

      var keys = map(keyname.split(" "), normalizeKeyName);
      for (var i = 0; i < keys.length; i++) {
        var val = (void 0), name = (void 0);
        if (i == keys.length - 1) {
          name = keys.join(" ");
          val = value;
        } else {
          name = keys.slice(0, i + 1).join(" ");
          val = "...";
        }
        var prev = copy[name];
        if (!prev) { copy[name] = val; }
        else if (prev != val) { throw new Error("Inconsistent bindings for " + name) }
      }
      delete keymap[keyname];
    } }
    for (var prop in copy) { keymap[prop] = copy[prop]; }
    return keymap
  }

  function lookupKey(key, map, handle, context) {
    map = getKeyMap(map);
    var found = map.call ? map.call(key, context) : map[key];
    if (found === false) { return "nothing" }
    if (found === "...") { return "multi" }
    if (found != null && handle(found)) { return "handled" }

    if (map.fallthrough) {
      if (Object.prototype.toString.call(map.fallthrough) != "[object Array]")
        { return lookupKey(key, map.fallthrough, handle, context) }
      for (var i = 0; i < map.fallthrough.length; i++) {
        var result = lookupKey(key, map.fallthrough[i], handle, context);
        if (result) { return result }
      }
    }
  }

  // Modifier key presses don't count as 'real' key presses for the
  // purpose of keymap fallthrough.
  function isModifierKey(value) {
    var name = typeof value == "string" ? value : keyNames[value.keyCode];
    return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"
  }

  function addModifierNames(name, event, noShift) {
    var base = name;
    if (event.altKey && base != "Alt") { name = "Alt-" + name; }
    if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { name = "Ctrl-" + name; }
    if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Mod") { name = "Cmd-" + name; }
    if (!noShift && event.shiftKey && base != "Shift") { name = "Shift-" + name; }
    return name
  }

  // Look up the name of a key as indicated by an event object.
  function keyName(event, noShift) {
    if (presto && event.keyCode == 34 && event["char"]) { return false }
    var name = keyNames[event.keyCode];
    if (name == null || event.altGraphKey) { return false }
    // Ctrl-ScrollLock has keyCode 3, same as Ctrl-Pause,
    // so we'll use event.code when available (Chrome 48+, FF 38+, Safari 10.1+)
    if (event.keyCode == 3 && event.code) { name = event.code; }
    return addModifierNames(name, event, noShift)
  }

  function getKeyMap(val) {
    return typeof val == "string" ? keyMap[val] : val
  }

  // Helper for deleting text near the selection(s), used to implement
  // backspace, delete, and similar functionality.
  function deleteNearSelection(cm, compute) {
    var ranges = cm.doc.sel.ranges, kill = [];
    // Build up a set of ranges to kill first, merging overlapping
    // ranges.
    for (var i = 0; i < ranges.length; i++) {
      var toKill = compute(ranges[i]);
      while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
        var replaced = kill.pop();
        if (cmp(replaced.from, toKill.from) < 0) {
          toKill.from = replaced.from;
          break
        }
      }
      kill.push(toKill);
    }
    // Next, remove those actual ranges.
    runInOp(cm, function () {
      for (var i = kill.length - 1; i >= 0; i--)
        { replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete"); }
      ensureCursorVisible(cm);
    });
  }

  function moveCharLogically(line, ch, dir) {
    var target = skipExtendingChars(line.text, ch + dir, dir);
    return target < 0 || target > line.text.length ? null : target
  }

  function moveLogically(line, start, dir) {
    var ch = moveCharLogically(line, start.ch, dir);
    return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before")
  }

  function endOfLine(visually, cm, lineObj, lineNo, dir) {
    if (visually) {
      if (cm.doc.direction == "rtl") { dir = -dir; }
      var order = getOrder(lineObj, cm.doc.direction);
      if (order) {
        var part = dir < 0 ? lst(order) : order[0];
        var moveInStorageOrder = (dir < 0) == (part.level == 1);
        var sticky = moveInStorageOrder ? "after" : "before";
        var ch;
        // With a wrapped rtl chunk (possibly spanning multiple bidi parts),
        // it could be that the last bidi part is not on the last visual line,
        // since visual lines contain content order-consecutive chunks.
        // Thus, in rtl, we are looking for the first (content-order) character
        // in the rtl chunk that is on the last line (that is, the same line
        // as the last (content-order) character).
        if (part.level > 0 || cm.doc.direction == "rtl") {
          var prep = prepareMeasureForLine(cm, lineObj);
          ch = dir < 0 ? lineObj.text.length - 1 : 0;
          var targetTop = measureCharPrepared(cm, prep, ch).top;
          ch = findFirst(function (ch) { return measureCharPrepared(cm, prep, ch).top == targetTop; }, (dir < 0) == (part.level == 1) ? part.from : part.to - 1, ch);
          if (sticky == "before") { ch = moveCharLogically(lineObj, ch, 1); }
        } else { ch = dir < 0 ? part.to : part.from; }
        return new Pos(lineNo, ch, sticky)
      }
    }
    return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after")
  }

  function moveVisually(cm, line, start, dir) {
    var bidi = getOrder(line, cm.doc.direction);
    if (!bidi) { return moveLogically(line, start, dir) }
    if (start.ch >= line.text.length) {
      start.ch = line.text.length;
      start.sticky = "before";
    } else if (start.ch <= 0) {
      start.ch = 0;
      start.sticky = "after";
    }
    var partPos = getBidiPartAt(bidi, start.ch, start.sticky), part = bidi[partPos];
    if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) {
      // Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines,
      // nothing interesting happens.
      return moveLogically(line, start, dir)
    }

    var mv = function (pos, dir) { return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir); };
    var prep;
    var getWrappedLineExtent = function (ch) {
      if (!cm.options.lineWrapping) { return {begin: 0, end: line.text.length} }
      prep = prep || prepareMeasureForLine(cm, line);
      return wrappedLineExtentChar(cm, line, prep, ch)
    };
    var wrappedLineExtent = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch);

    if (cm.doc.direction == "rtl" || part.level == 1) {
      var moveInStorageOrder = (part.level == 1) == (dir < 0);
      var ch = mv(start, moveInStorageOrder ? 1 : -1);
      if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) {
        // Case 2: We move within an rtl part or in an rtl editor on the same visual line
        var sticky = moveInStorageOrder ? "before" : "after";
        return new Pos(start.line, ch, sticky)
      }
    }

    // Case 3: Could not move within this bidi part in this visual line, so leave
    // the current bidi part

    var searchInVisualLine = function (partPos, dir, wrappedLineExtent) {
      var getRes = function (ch, moveInStorageOrder) { return moveInStorageOrder
        ? new Pos(start.line, mv(ch, 1), "before")
        : new Pos(start.line, ch, "after"); };

      for (; partPos >= 0 && partPos < bidi.length; partPos += dir) {
        var part = bidi[partPos];
        var moveInStorageOrder = (dir > 0) == (part.level != 1);
        var ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1);
        if (part.from <= ch && ch < part.to) { return getRes(ch, moveInStorageOrder) }
        ch = moveInStorageOrder ? part.from : mv(part.to, -1);
        if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) { return getRes(ch, moveInStorageOrder) }
      }
    };

    // Case 3a: Look for other bidi parts on the same visual line
    var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent);
    if (res) { return res }

    // Case 3b: Look for other bidi parts on the next visual line
    var nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1);
    if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) {
      res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh));
      if (res) { return res }
    }

    // Case 4: Nowhere to move
    return null
  }

  // Commands are parameter-less actions that can be performed on an
  // editor, mostly used for keybindings.
  var commands = {
    selectAll: selectAll,
    singleSelection: function (cm) { return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); },
    killLine: function (cm) { return deleteNearSelection(cm, function (range) {
      if (range.empty()) {
        var len = getLine(cm.doc, range.head.line).text.length;
        if (range.head.ch == len && range.head.line < cm.lastLine())
          { return {from: range.head, to: Pos(range.head.line + 1, 0)} }
        else
          { return {from: range.head, to: Pos(range.head.line, len)} }
      } else {
        return {from: range.from(), to: range.to()}
      }
    }); },
    deleteLine: function (cm) { return deleteNearSelection(cm, function (range) { return ({
      from: Pos(range.from().line, 0),
      to: clipPos(cm.doc, Pos(range.to().line + 1, 0))
    }); }); },
    delLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { return ({
      from: Pos(range.from().line, 0), to: range.from()
    }); }); },
    delWrappedLineLeft: function (cm) { return deleteNearSelection(cm, function (range) {
      var top = cm.charCoords(range.head, "div").top + 5;
      var leftPos = cm.coordsChar({left: 0, top: top}, "div");
      return {from: leftPos, to: range.from()}
    }); },
    delWrappedLineRight: function (cm) { return deleteNearSelection(cm, function (range) {
      var top = cm.charCoords(range.head, "div").top + 5;
      var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
      return {from: range.from(), to: rightPos }
    }); },
    undo: function (cm) { return cm.undo(); },
    redo: function (cm) { return cm.redo(); },
    undoSelection: function (cm) { return cm.undoSelection(); },
    redoSelection: function (cm) { return cm.redoSelection(); },
    goDocStart: function (cm) { return cm.extendSelection(Pos(cm.firstLine(), 0)); },
    goDocEnd: function (cm) { return cm.extendSelection(Pos(cm.lastLine())); },
    goLineStart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); },
      {origin: "+move", bias: 1}
    ); },
    goLineStartSmart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStartSmart(cm, range.head); },
      {origin: "+move", bias: 1}
    ); },
    goLineEnd: function (cm) { return cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); },
      {origin: "+move", bias: -1}
    ); },
    goLineRight: function (cm) { return cm.extendSelectionsBy(function (range) {
      var top = cm.cursorCoords(range.head, "div").top + 5;
      return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div")
    }, sel_move); },
    goLineLeft: function (cm) { return cm.extendSelectionsBy(function (range) {
      var top = cm.cursorCoords(range.head, "div").top + 5;
      return cm.coordsChar({left: 0, top: top}, "div")
    }, sel_move); },
    goLineLeftSmart: function (cm) { return cm.extendSelectionsBy(function (range) {
      var top = cm.cursorCoords(range.head, "div").top + 5;
      var pos = cm.coordsChar({left: 0, top: top}, "div");
      if (pos.ch < cm.getLine(pos.line).search(/\S/)) { return lineStartSmart(cm, range.head) }
      return pos
    }, sel_move); },
    goLineUp: function (cm) { return cm.moveV(-1, "line"); },
    goLineDown: function (cm) { return cm.moveV(1, "line"); },
    goPageUp: function (cm) { return cm.moveV(-1, "page"); },
    goPageDown: function (cm) { return cm.moveV(1, "page"); },
    goCharLeft: function (cm) { return cm.moveH(-1, "char"); },
    goCharRight: function (cm) { return cm.moveH(1, "char"); },
    goColumnLeft: function (cm) { return cm.moveH(-1, "column"); },
    goColumnRight: function (cm) { return cm.moveH(1, "column"); },
    goWordLeft: function (cm) { return cm.moveH(-1, "word"); },
    goGroupRight: function (cm) { return cm.moveH(1, "group"); },
    goGroupLeft: function (cm) { return cm.moveH(-1, "group"); },
    goWordRight: function (cm) { return cm.moveH(1, "word"); },
    delCharBefore: function (cm) { return cm.deleteH(-1, "codepoint"); },
    delCharAfter: function (cm) { return cm.deleteH(1, "char"); },
    delWordBefore: function (cm) { return cm.deleteH(-1, "word"); },
    delWordAfter: function (cm) { return cm.deleteH(1, "word"); },
    delGroupBefore: function (cm) { return cm.deleteH(-1, "group"); },
    delGroupAfter: function (cm) { return cm.deleteH(1, "group"); },
    indentAuto: function (cm) { return cm.indentSelection("smart"); },
    indentMore: function (cm) { return cm.indentSelection("add"); },
    indentLess: function (cm) { return cm.indentSelection("subtract"); },
    insertTab: function (cm) { return cm.replaceSelection("\t"); },
    insertSoftTab: function (cm) {
      var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
      for (var i = 0; i < ranges.length; i++) {
        var pos = ranges[i].from();
        var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
        spaces.push(spaceStr(tabSize - col % tabSize));
      }
      cm.replaceSelections(spaces);
    },
    defaultTab: function (cm) {
      if (cm.somethingSelected()) { cm.indentSelection("add"); }
      else { cm.execCommand("insertTab"); }
    },
    // Swap the two chars left and right of each selection's head.
    // Move cursor behind the two swapped characters afterwards.
    //
    // Doesn't consider line feeds a character.
    // Doesn't scan more than one line above to find a character.
    // Doesn't do anything on an empty line.
    // Doesn't do anything with non-empty selections.
    transposeChars: function (cm) { return runInOp(cm, function () {
      var ranges = cm.listSelections(), newSel = [];
      for (var i = 0; i < ranges.length; i++) {
        if (!ranges[i].empty()) { continue }
        var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
        if (line) {
          if (cur.ch == line.length) { cur = new Pos(cur.line, cur.ch - 1); }
          if (cur.ch > 0) {
            cur = new Pos(cur.line, cur.ch + 1);
            cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
                            Pos(cur.line, cur.ch - 2), cur, "+transpose");
          } else if (cur.line > cm.doc.first) {
            var prev = getLine(cm.doc, cur.line - 1).text;
            if (prev) {
              cur = new Pos(cur.line, 1);
              cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +
                              prev.charAt(prev.length - 1),
                              Pos(cur.line - 1, prev.length - 1), cur, "+transpose");
            }
          }
        }
        newSel.push(new Range(cur, cur));
      }
      cm.setSelections(newSel);
    }); },
    newlineAndIndent: function (cm) { return runInOp(cm, function () {
      var sels = cm.listSelections();
      for (var i = sels.length - 1; i >= 0; i--)
        { cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, "+input"); }
      sels = cm.listSelections();
      for (var i$1 = 0; i$1 < sels.length; i$1++)
        { cm.indentLine(sels[i$1].from().line, null, true); }
      ensureCursorVisible(cm);
    }); },
    openLine: function (cm) { return cm.replaceSelection("\n", "start"); },
    toggleOverwrite: function (cm) { return cm.toggleOverwrite(); }
  };


  function lineStart(cm, lineN) {
    var line = getLine(cm.doc, lineN);
    var visual = visualLine(line);
    if (visual != line) { lineN = lineNo(visual); }
    return endOfLine(true, cm, visual, lineN, 1)
  }
  function lineEnd(cm, lineN) {
    var line = getLine(cm.doc, lineN);
    var visual = visualLineEnd(line);
    if (visual != line) { lineN = lineNo(visual); }
    return endOfLine(true, cm, line, lineN, -1)
  }
  function lineStartSmart(cm, pos) {
    var start = lineStart(cm, pos.line);
    var line = getLine(cm.doc, start.line);
    var order = getOrder(line, cm.doc.direction);
    if (!order || order[0].level == 0) {
      var firstNonWS = Math.max(start.ch, line.text.search(/\S/));
      var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;
      return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky)
    }
    return start
  }

  // Run a handler that was bound to a key.
  function doHandleBinding(cm, bound, dropShift) {
    if (typeof bound == "string") {
      bound = commands[bound];
      if (!bound) { return false }
    }
    // Ensure previous input has been read, so that the handler sees a
    // consistent view of the document
    cm.display.input.ensurePolled();
    var prevShift = cm.display.shift, done = false;
    try {
      if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
      if (dropShift) { cm.display.shift = false; }
      done = bound(cm) != Pass;
    } finally {
      cm.display.shift = prevShift;
      cm.state.suppressEdits = false;
    }
    return done
  }

  function lookupKeyForEditor(cm, name, handle) {
    for (var i = 0; i < cm.state.keyMaps.length; i++) {
      var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);
      if (result) { return result }
    }
    return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
      || lookupKey(name, cm.options.keyMap, handle, cm)
  }

  // Note that, despite the name, this function is also used to check
  // for bound mouse clicks.

  var stopSeq = new Delayed;

  function dispatchKey(cm, name, e, handle) {
    var seq = cm.state.keySeq;
    if (seq) {
      if (isModifierKey(name)) { return "handled" }
      if (/\'$/.test(name))
        { cm.state.keySeq = null; }
      else
        { stopSeq.set(50, function () {
          if (cm.state.keySeq == seq) {
            cm.state.keySeq = null;
            cm.display.input.reset();
          }
        }); }
      if (dispatchKeyInner(cm, seq + " " + name, e, handle)) { return true }
    }
    return dispatchKeyInner(cm, name, e, handle)
  }

  function dispatchKeyInner(cm, name, e, handle) {
    var result = lookupKeyForEditor(cm, name, handle);

    if (result == "multi")
      { cm.state.keySeq = name; }
    if (result == "handled")
      { signalLater(cm, "keyHandled", cm, name, e); }

    if (result == "handled" || result == "multi") {
      e_preventDefault(e);
      restartBlink(cm);
    }

    return !!result
  }

  // Handle a key from the keydown event.
  function handleKeyBinding(cm, e) {
    var name = keyName(e, true);
    if (!name) { return false }

    if (e.shiftKey && !cm.state.keySeq) {
      // First try to resolve full name (including 'Shift-'). Failing
      // that, see if there is a cursor-motion command (starting with
      // 'go') bound to the keyname without 'Shift-'.
      return dispatchKey(cm, "Shift-" + name, e, function (b) { return doHandleBinding(cm, b, true); })
          || dispatchKey(cm, name, e, function (b) {
               if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
                 { return doHandleBinding(cm, b) }
             })
    } else {
      return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); })
    }
  }

  // Handle a key from the keypress event
  function handleCharBinding(cm, e, ch) {
    return dispatchKey(cm, "'" + ch + "'", e, function (b) { return doHandleBinding(cm, b, true); })
  }

  var lastStoppedKey = null;
  function onKeyDown(e) {
    var cm = this;
    if (e.target && e.target != cm.display.input.getField()) { return }
    cm.curOp.focus = activeElt(doc(cm));
    if (signalDOMEvent(cm, e)) { return }
    // IE does strange things with escape.
    if (ie && ie_version < 11 && e.keyCode == 27) { e.returnValue = false; }
    var code = e.keyCode;
    cm.display.shift = code == 16 || e.shiftKey;
    var handled = handleKeyBinding(cm, e);
    if (presto) {
      lastStoppedKey = handled ? code : null;
      // Opera has no cut event... we try to at least catch the key combo
      if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
        { cm.replaceSelection("", null, "cut"); }
    }
    if (gecko && !mac && !handled && code == 46 && e.shiftKey && !e.ctrlKey && document.execCommand)
      { document.execCommand("cut"); }

    // Turn mouse into crosshair when Alt is held on Mac.
    if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
      { showCrossHair(cm); }
  }

  function showCrossHair(cm) {
    var lineDiv = cm.display.lineDiv;
    addClass(lineDiv, "CodeMirror-crosshair");

    function up(e) {
      if (e.keyCode == 18 || !e.altKey) {
        rmClass(lineDiv, "CodeMirror-crosshair");
        off(document, "keyup", up);
        off(document, "mouseover", up);
      }
    }
    on(document, "keyup", up);
    on(document, "mouseover", up);
  }

  function onKeyUp(e) {
    if (e.keyCode == 16) { this.doc.sel.shift = false; }
    signalDOMEvent(this, e);
  }

  function onKeyPress(e) {
    var cm = this;
    if (e.target && e.target != cm.display.input.getField()) { return }
    if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { return }
    var keyCode = e.keyCode, charCode = e.charCode;
    if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return}
    if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) { return }
    var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
    // Some browsers fire keypress events for backspace
    if (ch == "\x08") { return }
    if (handleCharBinding(cm, e, ch)) { return }
    cm.display.input.onKeyPress(e);
  }

  var DOUBLECLICK_DELAY = 400;

  var PastClick = function(time, pos, button) {
    this.time = time;
    this.pos = pos;
    this.button = button;
  };

  PastClick.prototype.compare = function (time, pos, button) {
    return this.time + DOUBLECLICK_DELAY > time &&
      cmp(pos, this.pos) == 0 && button == this.button
  };

  var lastClick, lastDoubleClick;
  function clickRepeat(pos, button) {
    var now = +new Date;
    if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) {
      lastClick = lastDoubleClick = null;
      return "triple"
    } else if (lastClick && lastClick.compare(now, pos, button)) {
      lastDoubleClick = new PastClick(now, pos, button);
      lastClick = null;
      return "double"
    } else {
      lastClick = new PastClick(now, pos, button);
      lastDoubleClick = null;
      return "single"
    }
  }

  // A mouse down can be a single click, double click, triple click,
  // start of selection drag, start of text drag, new cursor
  // (ctrl-click), rectangle drag (alt-drag), or xwin
  // middle-click-paste. Or it might be a click on something we should
  // not interfere with, such as a scrollbar or widget.
  function onMouseDown(e) {
    var cm = this, display = cm.display;
    if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { return }
    display.input.ensurePolled();
    display.shift = e.shiftKey;

    if (eventInWidget(display, e)) {
      if (!webkit) {
        // Briefly turn off draggability, to allow widgets to do
        // normal dragging things.
        display.scroller.draggable = false;
        setTimeout(function () { return display.scroller.draggable = true; }, 100);
      }
      return
    }
    if (clickInGutter(cm, e)) { return }
    var pos = posFromMouse(cm, e), button = e_button(e), repeat = pos ? clickRepeat(pos, button) : "single";
    win(cm).focus();

    // #3261: make sure, that we're not starting a second selection
    if (button == 1 && cm.state.selectingText)
      { cm.state.selectingText(e); }

    if (pos && handleMappedButton(cm, button, pos, repeat, e)) { return }

    if (button == 1) {
      if (pos) { leftButtonDown(cm, pos, repeat, e); }
      else if (e_target(e) == display.scroller) { e_preventDefault(e); }
    } else if (button == 2) {
      if (pos) { extendSelection(cm.doc, pos); }
      setTimeout(function () { return display.input.focus(); }, 20);
    } else if (button == 3) {
      if (captureRightClick) { cm.display.input.onContextMenu(e); }
      else { delayBlurEvent(cm); }
    }
  }

  function handleMappedButton(cm, button, pos, repeat, event) {
    var name = "Click";
    if (repeat == "double") { name = "Double" + name; }
    else if (repeat == "triple") { name = "Triple" + name; }
    name = (button == 1 ? "Left" : button == 2 ? "Middle" : "Right") + name;

    return dispatchKey(cm,  addModifierNames(name, event), event, function (bound) {
      if (typeof bound == "string") { bound = commands[bound]; }
      if (!bound) { return false }
      var done = false;
      try {
        if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
        done = bound(cm, pos) != Pass;
      } finally {
        cm.state.suppressEdits = false;
      }
      return done
    })
  }

  function configureMouse(cm, repeat, event) {
    var option = cm.getOption("configureMouse");
    var value = option ? option(cm, repeat, event) : {};
    if (value.unit == null) {
      var rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey;
      value.unit = rect ? "rectangle" : repeat == "single" ? "char" : repeat == "double" ? "word" : "line";
    }
    if (value.extend == null || cm.doc.extend) { value.extend = cm.doc.extend || event.shiftKey; }
    if (value.addNew == null) { value.addNew = mac ? event.metaKey : event.ctrlKey; }
    if (value.moveOnDrag == null) { value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey); }
    return value
  }

  function leftButtonDown(cm, pos, repeat, event) {
    if (ie) { setTimeout(bind(ensureFocus, cm), 0); }
    else { cm.curOp.focus = activeElt(doc(cm)); }

    var behavior = configureMouse(cm, repeat, event);

    var sel = cm.doc.sel, contained;
    if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() &&
        repeat == "single" && (contained = sel.contains(pos)) > -1 &&
        (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) &&
        (cmp(contained.to(), pos) > 0 || pos.xRel < 0))
      { leftButtonStartDrag(cm, event, pos, behavior); }
    else
      { leftButtonSelect(cm, event, pos, behavior); }
  }

  // Start a text drag. When it ends, see if any dragging actually
  // happen, and treat as a click if it didn't.
  function leftButtonStartDrag(cm, event, pos, behavior) {
    var display = cm.display, moved = false;
    var dragEnd = operation(cm, function (e) {
      if (webkit) { display.scroller.draggable = false; }
      cm.state.draggingText = false;
      if (cm.state.delayingBlurEvent) {
        if (cm.hasFocus()) { cm.state.delayingBlurEvent = false; }
        else { delayBlurEvent(cm); }
      }
      off(display.wrapper.ownerDocument, "mouseup", dragEnd);
      off(display.wrapper.ownerDocument, "mousemove", mouseMove);
      off(display.scroller, "dragstart", dragStart);
      off(display.scroller, "drop", dragEnd);
      if (!moved) {
        e_preventDefault(e);
        if (!behavior.addNew)
          { extendSelection(cm.doc, pos, null, null, behavior.extend); }
        // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
        if ((webkit && !safari) || ie && ie_version == 9)
          { setTimeout(function () {display.wrapper.ownerDocument.body.focus({preventScroll: true}); display.input.focus();}, 20); }
        else
          { display.input.focus(); }
      }
    });
    var mouseMove = function(e2) {
      moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10;
    };
    var dragStart = function () { return moved = true; };
    // Let the drag handler handle this.
    if (webkit) { display.scroller.draggable = true; }
    cm.state.draggingText = dragEnd;
    dragEnd.copy = !behavior.moveOnDrag;
    on(display.wrapper.ownerDocument, "mouseup", dragEnd);
    on(display.wrapper.ownerDocument, "mousemove", mouseMove);
    on(display.scroller, "dragstart", dragStart);
    on(display.scroller, "drop", dragEnd);

    cm.state.delayingBlurEvent = true;
    setTimeout(function () { return display.input.focus(); }, 20);
    // IE's approach to draggable
    if (display.scroller.dragDrop) { display.scroller.dragDrop(); }
  }

  function rangeForUnit(cm, pos, unit) {
    if (unit == "char") { return new Range(pos, pos) }
    if (unit == "word") { return cm.findWordAt(pos) }
    if (unit == "line") { return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) }
    var result = unit(cm, pos);
    return new Range(result.from, result.to)
  }

  // Normal selection, as opposed to text dragging.
  function leftButtonSelect(cm, event, start, behavior) {
    if (ie) { delayBlurEvent(cm); }
    var display = cm.display, doc$1 = cm.doc;
    e_preventDefault(event);

    var ourRange, ourIndex, startSel = doc$1.sel, ranges = startSel.ranges;
    if (behavior.addNew && !behavior.extend) {
      ourIndex = doc$1.sel.contains(start);
      if (ourIndex > -1)
        { ourRange = ranges[ourIndex]; }
      else
        { ourRange = new Range(start, start); }
    } else {
      ourRange = doc$1.sel.primary();
      ourIndex = doc$1.sel.primIndex;
    }

    if (behavior.unit == "rectangle") {
      if (!behavior.addNew) { ourRange = new Range(start, start); }
      start = posFromMouse(cm, event, true, true);
      ourIndex = -1;
    } else {
      var range = rangeForUnit(cm, start, behavior.unit);
      if (behavior.extend)
        { ourRange = extendRange(ourRange, range.anchor, range.head, behavior.extend); }
      else
        { ourRange = range; }
    }

    if (!behavior.addNew) {
      ourIndex = 0;
      setSelection(doc$1, new Selection([ourRange], 0), sel_mouse);
      startSel = doc$1.sel;
    } else if (ourIndex == -1) {
      ourIndex = ranges.length;
      setSelection(doc$1, normalizeSelection(cm, ranges.concat([ourRange]), ourIndex),
                   {scroll: false, origin: "*mouse"});
    } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) {
      setSelection(doc$1, normalizeSelection(cm, ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),
                   {scroll: false, origin: "*mouse"});
      startSel = doc$1.sel;
    } else {
      replaceOneSelection(doc$1, ourIndex, ourRange, sel_mouse);
    }

    var lastPos = start;
    function extendTo(pos) {
      if (cmp(lastPos, pos) == 0) { return }
      lastPos = pos;

      if (behavior.unit == "rectangle") {
        var ranges = [], tabSize = cm.options.tabSize;
        var startCol = countColumn(getLine(doc$1, start.line).text, start.ch, tabSize);
        var posCol = countColumn(getLine(doc$1, pos.line).text, pos.ch, tabSize);
        var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
        for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
             line <= end; line++) {
          var text = getLine(doc$1, line).text, leftPos = findColumn(text, left, tabSize);
          if (left == right)
            { ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); }
          else if (text.length > leftPos)
            { ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); }
        }
        if (!ranges.length) { ranges.push(new Range(start, start)); }
        setSelection(doc$1, normalizeSelection(cm, startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
                     {origin: "*mouse", scroll: false});
        cm.scrollIntoView(pos);
      } else {
        var oldRange = ourRange;
        var range = rangeForUnit(cm, pos, behavior.unit);
        var anchor = oldRange.anchor, head;
        if (cmp(range.anchor, anchor) > 0) {
          head = range.head;
          anchor = minPos(oldRange.from(), range.anchor);
        } else {
          head = range.anchor;
          anchor = maxPos(oldRange.to(), range.head);
        }
        var ranges$1 = startSel.ranges.slice(0);
        ranges$1[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc$1, anchor), head));
        setSelection(doc$1, normalizeSelection(cm, ranges$1, ourIndex), sel_mouse);
      }
    }

    var editorSize = display.wrapper.getBoundingClientRect();
    // Used to ensure timeout re-tries don't fire when another extend
    // happened in the meantime (clearTimeout isn't reliable -- at
    // least on Chrome, the timeouts still happen even when cleared,
    // if the clear happens after their scheduled firing time).
    var counter = 0;

    function extend(e) {
      var curCount = ++counter;
      var cur = posFromMouse(cm, e, true, behavior.unit == "rectangle");
      if (!cur) { return }
      if (cmp(cur, lastPos) != 0) {
        cm.curOp.focus = activeElt(doc(cm));
        extendTo(cur);
        var visible = visibleLines(display, doc$1);
        if (cur.line >= visible.to || cur.line < visible.from)
          { setTimeout(operation(cm, function () {if (counter == curCount) { extend(e); }}), 150); }
      } else {
        var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
        if (outside) { setTimeout(operation(cm, function () {
          if (counter != curCount) { return }
          display.scroller.scrollTop += outside;
          extend(e);
        }), 50); }
      }
    }

    function done(e) {
      cm.state.selectingText = false;
      counter = Infinity;
      // If e is null or undefined we interpret this as someone trying
      // to explicitly cancel the selection rather than the user
      // letting go of the mouse button.
      if (e) {
        e_preventDefault(e);
        display.input.focus();
      }
      off(display.wrapper.ownerDocument, "mousemove", move);
      off(display.wrapper.ownerDocument, "mouseup", up);
      doc$1.history.lastSelOrigin = null;
    }

    var move = operation(cm, function (e) {
      if (e.buttons === 0 || !e_button(e)) { done(e); }
      else { extend(e); }
    });
    var up = operation(cm, done);
    cm.state.selectingText = up;
    on(display.wrapper.ownerDocument, "mousemove", move);
    on(display.wrapper.ownerDocument, "mouseup", up);
  }

  // Used when mouse-selecting to adjust the anchor to the proper side
  // of a bidi jump depending on the visual position of the head.
  function bidiSimplify(cm, range) {
    var anchor = range.anchor;
    var head = range.head;
    var anchorLine = getLine(cm.doc, anchor.line);
    if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) { return range }
    var order = getOrder(anchorLine);
    if (!order) { return range }
    var index = getBidiPartAt(order, anchor.ch, anchor.sticky), part = order[index];
    if (part.from != anchor.ch && part.to != anchor.ch) { return range }
    var boundary = index + ((part.from == anchor.ch) == (part.level != 1) ? 0 : 1);
    if (boundary == 0 || boundary == order.length) { return range }

    // Compute the relative visual position of the head compared to the
    // anchor (<0 is to the left, >0 to the right)
    var leftSide;
    if (head.line != anchor.line) {
      leftSide = (head.line - anchor.line) * (cm.doc.direction == "ltr" ? 1 : -1) > 0;
    } else {
      var headIndex = getBidiPartAt(order, head.ch, head.sticky);
      var dir = headIndex - index || (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1);
      if (headIndex == boundary - 1 || headIndex == boundary)
        { leftSide = dir < 0; }
      else
        { leftSide = dir > 0; }
    }

    var usePart = order[boundary + (leftSide ? -1 : 0)];
    var from = leftSide == (usePart.level == 1);
    var ch = from ? usePart.from : usePart.to, sticky = from ? "after" : "before";
    return anchor.ch == ch && anchor.sticky == sticky ? range : new Range(new Pos(anchor.line, ch, sticky), head)
  }


  // Determines whether an event happened in the gutter, and fires the
  // handlers for the corresponding event.
  function gutterEvent(cm, e, type, prevent) {
    var mX, mY;
    if (e.touches) {
      mX = e.touches[0].clientX;
      mY = e.touches[0].clientY;
    } else {
      try { mX = e.clientX; mY = e.clientY; }
      catch(e$1) { return false }
    }
    if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { return false }
    if (prevent) { e_preventDefault(e); }

    var display = cm.display;
    var lineBox = display.lineDiv.getBoundingClientRect();

    if (mY > lineBox.bottom || !hasHandler(cm, type)) { return e_defaultPrevented(e) }
    mY -= lineBox.top - display.viewOffset;

    for (var i = 0; i < cm.display.gutterSpecs.length; ++i) {
      var g = display.gutters.childNodes[i];
      if (g && g.getBoundingClientRect().right >= mX) {
        var line = lineAtHeight(cm.doc, mY);
        var gutter = cm.display.gutterSpecs[i];
        signal(cm, type, cm, line, gutter.className, e);
        return e_defaultPrevented(e)
      }
    }
  }

  function clickInGutter(cm, e) {
    return gutterEvent(cm, e, "gutterClick", true)
  }

  // CONTEXT MENU HANDLING

  // To make the context menu work, we need to briefly unhide the
  // textarea (making it as unobtrusive as possible) to let the
  // right-click take effect on it.
  function onContextMenu(cm, e) {
    if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { return }
    if (signalDOMEvent(cm, e, "contextmenu")) { return }
    if (!captureRightClick) { cm.display.input.onContextMenu(e); }
  }

  function contextMenuInGutter(cm, e) {
    if (!hasHandler(cm, "gutterContextMenu")) { return false }
    return gutterEvent(cm, e, "gutterContextMenu", false)
  }

  function themeChanged(cm) {
    cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
      cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
    clearCaches(cm);
  }

  var Init = {toString: function(){return "CodeMirror.Init"}};

  var defaults = {};
  var optionHandlers = {};

  function defineOptions(CodeMirror) {
    var optionHandlers = CodeMirror.optionHandlers;

    function option(name, deflt, handle, notOnInit) {
      CodeMirror.defaults[name] = deflt;
      if (handle) { optionHandlers[name] =
        notOnInit ? function (cm, val, old) {if (old != Init) { handle(cm, val, old); }} : handle; }
    }

    CodeMirror.defineOption = option;

    // Passed to option handlers when there is no old value.
    CodeMirror.Init = Init;

    // These two are, on init, called from the constructor because they
    // have to be initialized before the editor can start at all.
    option("value", "", function (cm, val) { return cm.setValue(val); }, true);
    option("mode", null, function (cm, val) {
      cm.doc.modeOption = val;
      loadMode(cm);
    }, true);

    option("indentUnit", 2, loadMode, true);
    option("indentWithTabs", false);
    option("smartIndent", true);
    option("tabSize", 4, function (cm) {
      resetModeState(cm);
      clearCaches(cm);
      regChange(cm);
    }, true);

    option("lineSeparator", null, function (cm, val) {
      cm.doc.lineSep = val;
      if (!val) { return }
      var newBreaks = [], lineNo = cm.doc.first;
      cm.doc.iter(function (line) {
        for (var pos = 0;;) {
          var found = line.text.indexOf(val, pos);
          if (found == -1) { break }
          pos = found + val.length;
          newBreaks.push(Pos(lineNo, found));
        }
        lineNo++;
      });
      for (var i = newBreaks.length - 1; i >= 0; i--)
        { replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)); }
    });
    option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b\u200e\u200f\u2028\u2029\u202d\u202e\u2066\u2067\u2069\ufeff\ufff9-\ufffc]/g, function (cm, val, old) {
      cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
      if (old != Init) { cm.refresh(); }
    });
    option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { return cm.refresh(); }, true);
    option("electricChars", true);
    option("inputStyle", mobile ? "contenteditable" : "textarea", function () {
      throw new Error("inputStyle can not (yet) be changed in a running editor") // FIXME
    }, true);
    option("spellcheck", false, function (cm, val) { return cm.getInputField().spellcheck = val; }, true);
    option("autocorrect", false, function (cm, val) { return cm.getInputField().autocorrect = val; }, true);
    option("autocapitalize", false, function (cm, val) { return cm.getInputField().autocapitalize = val; }, true);
    option("rtlMoveVisually", !windows);
    option("wholeLineUpdateBefore", true);

    option("theme", "default", function (cm) {
      themeChanged(cm);
      updateGutters(cm);
    }, true);
    option("keyMap", "default", function (cm, val, old) {
      var next = getKeyMap(val);
      var prev = old != Init && getKeyMap(old);
      if (prev && prev.detach) { prev.detach(cm, next); }
      if (next.attach) { next.attach(cm, prev || null); }
    });
    option("extraKeys", null);
    option("configureMouse", null);

    option("lineWrapping", false, wrappingChanged, true);
    option("gutters", [], function (cm, val) {
      cm.display.gutterSpecs = getGutters(val, cm.options.lineNumbers);
      updateGutters(cm);
    }, true);
    option("fixedGutter", true, function (cm, val) {
      cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
      cm.refresh();
    }, true);
    option("coverGutterNextToScrollbar", false, function (cm) { return updateScrollbars(cm); }, true);
    option("scrollbarStyle", "native", function (cm) {
      initScrollbars(cm);
      updateScrollbars(cm);
      cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);
      cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);
    }, true);
    option("lineNumbers", false, function (cm, val) {
      cm.display.gutterSpecs = getGutters(cm.options.gutters, val);
      updateGutters(cm);
    }, true);
    option("firstLineNumber", 1, updateGutters, true);
    option("lineNumberFormatter", function (integer) { return integer; }, updateGutters, true);
    option("showCursorWhenSelecting", false, updateSelection, true);

    option("resetSelectionOnContextMenu", true);
    option("lineWiseCopyCut", true);
    option("pasteLinesPerSelection", true);
    option("selectionsMayTouch", false);

    option("readOnly", false, function (cm, val) {
      if (val == "nocursor") {
        onBlur(cm);
        cm.display.input.blur();
      }
      cm.display.input.readOnlyChanged(val);
    });

    option("screenReaderLabel", null, function (cm, val) {
      val = (val === '') ? null : val;
      cm.display.input.screenReaderLabelChanged(val);
    });

    option("disableInput", false, function (cm, val) {if (!val) { cm.display.input.reset(); }}, true);
    option("dragDrop", true, dragDropChanged);
    option("allowDropFileTypes", null);

    option("cursorBlinkRate", 530);
    option("cursorScrollMargin", 0);
    option("cursorHeight", 1, updateSelection, true);
    option("singleCursorHeightPerLine", true, updateSelection, true);
    option("workTime", 100);
    option("workDelay", 100);
    option("flattenSpans", true, resetModeState, true);
    option("addModeClass", false, resetModeState, true);
    option("pollInterval", 100);
    option("undoDepth", 200, function (cm, val) { return cm.doc.history.undoDepth = val; });
    option("historyEventDelay", 1250);
    option("viewportMargin", 10, function (cm) { return cm.refresh(); }, true);
    option("maxHighlightLength", 10000, resetModeState, true);
    option("moveInputWithCursor", true, function (cm, val) {
      if (!val) { cm.display.input.resetPosition(); }
    });

    option("tabindex", null, function (cm, val) { return cm.display.input.getField().tabIndex = val || ""; });
    option("autofocus", null);
    option("direction", "ltr", function (cm, val) { return cm.doc.setDirection(val); }, true);
    option("phrases", null);
  }

  function dragDropChanged(cm, value, old) {
    var wasOn = old && old != Init;
    if (!value != !wasOn) {
      var funcs = cm.display.dragFunctions;
      var toggle = value ? on : off;
      toggle(cm.display.scroller, "dragstart", funcs.start);
      toggle(cm.display.scroller, "dragenter", funcs.enter);
      toggle(cm.display.scroller, "dragover", funcs.over);
      toggle(cm.display.scroller, "dragleave", funcs.leave);
      toggle(cm.display.scroller, "drop", funcs.drop);
    }
  }

  function wrappingChanged(cm) {
    if (cm.options.lineWrapping) {
      addClass(cm.display.wrapper, "CodeMirror-wrap");
      cm.display.sizer.style.minWidth = "";
      cm.display.sizerWidth = null;
    } else {
      rmClass(cm.display.wrapper, "CodeMirror-wrap");
      findMaxLine(cm);
    }
    estimateLineHeights(cm);
    regChange(cm);
    clearCaches(cm);
    setTimeout(function () { return updateScrollbars(cm); }, 100);
  }

  // A CodeMirror instance represents an editor. This is the object
  // that user code is usually dealing with.

  function CodeMirror(place, options) {
    var this$1 = this;

    if (!(this instanceof CodeMirror)) { return new CodeMirror(place, options) }

    this.options = options = options ? copyObj(options) : {};
    // Determine effective options based on given values and defaults.
    copyObj(defaults, options, false);

    var doc = options.value;
    if (typeof doc == "string") { doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction); }
    else if (options.mode) { doc.modeOption = options.mode; }
    this.doc = doc;

    var input = new CodeMirror.inputStyles[options.inputStyle](this);
    var display = this.display = new Display(place, doc, input, options);
    display.wrapper.CodeMirror = this;
    themeChanged(this);
    if (options.lineWrapping)
      { this.display.wrapper.className += " CodeMirror-wrap"; }
    initScrollbars(this);

    this.state = {
      keyMaps: [],  // stores maps added by addKeyMap
      overlays: [], // highlighting overlays, as added by addOverlay
      modeGen: 0,   // bumped when mode/overlay changes, used to invalidate highlighting info
      overwrite: false,
      delayingBlurEvent: false,
      focused: false,
      suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
      pasteIncoming: -1, cutIncoming: -1, // help recognize paste/cut edits in input.poll
      selectingText: false,
      draggingText: false,
      highlight: new Delayed(), // stores highlight worker timeout
      keySeq: null,  // Unfinished key sequence
      specialChars: null
    };

    if (options.autofocus && !mobile) { display.input.focus(); }

    // Override magic textarea content restore that IE sometimes does
    // on our hidden textarea on reload
    if (ie && ie_version < 11) { setTimeout(function () { return this$1.display.input.reset(true); }, 20); }

    registerEventHandlers(this);
    ensureGlobalHandlers();

    startOperation(this);
    this.curOp.forceUpdate = true;
    attachDoc(this, doc);

    if ((options.autofocus && !mobile) || this.hasFocus())
      { setTimeout(function () {
        if (this$1.hasFocus() && !this$1.state.focused) { onFocus(this$1); }
      }, 20); }
    else
      { onBlur(this); }

    for (var opt in optionHandlers) { if (optionHandlers.hasOwnProperty(opt))
      { optionHandlers[opt](this, options[opt], Init); } }
    maybeUpdateLineNumberWidth(this);
    if (options.finishInit) { options.finishInit(this); }
    for (var i = 0; i < initHooks.length; ++i) { initHooks[i](this); }
    endOperation(this);
    // Suppress optimizelegibility in Webkit, since it breaks text
    // measuring on line wrapping boundaries.
    if (webkit && options.lineWrapping &&
        getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
      { display.lineDiv.style.textRendering = "auto"; }
  }

  // The default configuration options.
  CodeMirror.defaults = defaults;
  // Functions to run when options are changed.
  CodeMirror.optionHandlers = optionHandlers;

  // Attach the necessary event handlers when initializing the editor
  function registerEventHandlers(cm) {
    var d = cm.display;
    on(d.scroller, "mousedown", operation(cm, onMouseDown));
    // Older IE's will not fire a second mousedown for a double click
    if (ie && ie_version < 11)
      { on(d.scroller, "dblclick", operation(cm, function (e) {
        if (signalDOMEvent(cm, e)) { return }
        var pos = posFromMouse(cm, e);
        if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { return }
        e_preventDefault(e);
        var word = cm.findWordAt(pos);
        extendSelection(cm.doc, word.anchor, word.head);
      })); }
    else
      { on(d.scroller, "dblclick", function (e) { return signalDOMEvent(cm, e) || e_preventDefault(e); }); }
    // Some browsers fire contextmenu *after* opening the menu, at
    // which point we can't mess with it anymore. Context menu is
    // handled in onMouseDown for these browsers.
    on(d.scroller, "contextmenu", function (e) { return onContextMenu(cm, e); });
    on(d.input.getField(), "contextmenu", function (e) {
      if (!d.scroller.contains(e.target)) { onContextMenu(cm, e); }
    });

    // Used to suppress mouse event handling when a touch happens
    var touchFinished, prevTouch = {end: 0};
    function finishTouch() {
      if (d.activeTouch) {
        touchFinished = setTimeout(function () { return d.activeTouch = null; }, 1000);
        prevTouch = d.activeTouch;
        prevTouch.end = +new Date;
      }
    }
    function isMouseLikeTouchEvent(e) {
      if (e.touches.length != 1) { return false }
      var touch = e.touches[0];
      return touch.radiusX <= 1 && touch.radiusY <= 1
    }
    function farAway(touch, other) {
      if (other.left == null) { return true }
      var dx = other.left - touch.left, dy = other.top - touch.top;
      return dx * dx + dy * dy > 20 * 20
    }
    on(d.scroller, "touchstart", function (e) {
      if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e) && !clickInGutter(cm, e)) {
        d.input.ensurePolled();
        clearTimeout(touchFinished);
        var now = +new Date;
        d.activeTouch = {start: now, moved: false,
                         prev: now - prevTouch.end <= 300 ? prevTouch : null};
        if (e.touches.length == 1) {
          d.activeTouch.left = e.touches[0].pageX;
          d.activeTouch.top = e.touches[0].pageY;
        }
      }
    });
    on(d.scroller, "touchmove", function () {
      if (d.activeTouch) { d.activeTouch.moved = true; }
    });
    on(d.scroller, "touchend", function (e) {
      var touch = d.activeTouch;
      if (touch && !eventInWidget(d, e) && touch.left != null &&
          !touch.moved && new Date - touch.start < 300) {
        var pos = cm.coordsChar(d.activeTouch, "page"), range;
        if (!touch.prev || farAway(touch, touch.prev)) // Single tap
          { range = new Range(pos, pos); }
        else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
          { range = cm.findWordAt(pos); }
        else // Triple tap
          { range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); }
        cm.setSelection(range.anchor, range.head);
        cm.focus();
        e_preventDefault(e);
      }
      finishTouch();
    });
    on(d.scroller, "touchcancel", finishTouch);

    // Sync scrolling between fake scrollbars and real scrollable
    // area, ensure viewport is updated when scrolling.
    on(d.scroller, "scroll", function () {
      if (d.scroller.clientHeight) {
        updateScrollTop(cm, d.scroller.scrollTop);
        setScrollLeft(cm, d.scroller.scrollLeft, true);
        signal(cm, "scroll", cm);
      }
    });

    // Listen to wheel events in order to try and update the viewport on time.
    on(d.scroller, "mousewheel", function (e) { return onScrollWheel(cm, e); });
    on(d.scroller, "DOMMouseScroll", function (e) { return onScrollWheel(cm, e); });

    // Prevent wrapper from ever scrolling
    on(d.wrapper, "scroll", function () { return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });

    d.dragFunctions = {
      enter: function (e) {if (!signalDOMEvent(cm, e)) { e_stop(e); }},
      over: function (e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }},
      start: function (e) { return onDragStart(cm, e); },
      drop: operation(cm, onDrop),
      leave: function (e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm); }}
    };

    var inp = d.input.getField();
    on(inp, "keyup", function (e) { return onKeyUp.call(cm, e); });
    on(inp, "keydown", operation(cm, onKeyDown));
    on(inp, "keypress", operation(cm, onKeyPress));
    on(inp, "focus", function (e) { return onFocus(cm, e); });
    on(inp, "blur", function (e) { return onBlur(cm, e); });
  }

  var initHooks = [];
  CodeMirror.defineInitHook = function (f) { return initHooks.push(f); };

  // Indent the given line. The how parameter can be "smart",
  // "add"/null, "subtract", or "prev". When aggressive is false
  // (typically set to true for forced single-line indents), empty
  // lines are not indented, and places where the mode returns Pass
  // are left alone.
  function indentLine(cm, n, how, aggressive) {
    var doc = cm.doc, state;
    if (how == null) { how = "add"; }
    if (how == "smart") {
      // Fall back to "prev" when the mode doesn't have an indentation
      // method.
      if (!doc.mode.indent) { how = "prev"; }
      else { state = getContextBefore(cm, n).state; }
    }

    var tabSize = cm.options.tabSize;
    var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
    if (line.stateAfter) { line.stateAfter = null; }
    var curSpaceString = line.text.match(/^\s*/)[0], indentation;
    if (!aggressive && !/\S/.test(line.text)) {
      indentation = 0;
      how = "not";
    } else if (how == "smart") {
      indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
      if (indentation == Pass || indentation > 150) {
        if (!aggressive) { return }
        how = "prev";
      }
    }
    if (how == "prev") {
      if (n > doc.first) { indentation = countColumn(getLine(doc, n-1).text, null, tabSize); }
      else { indentation = 0; }
    } else if (how == "add") {
      indentation = curSpace + cm.options.indentUnit;
    } else if (how == "subtract") {
      indentation = curSpace - cm.options.indentUnit;
    } else if (typeof how == "number") {
      indentation = curSpace + how;
    }
    indentation = Math.max(0, indentation);

    var indentString = "", pos = 0;
    if (cm.options.indentWithTabs)
      { for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";} }
    if (pos < indentation) { indentString += spaceStr(indentation - pos); }

    if (indentString != curSpaceString) {
      replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
      line.stateAfter = null;
      return true
    } else {
      // Ensure that, if the cursor was in the whitespace at the start
      // of the line, it is moved to the end of that space.
      for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) {
        var range = doc.sel.ranges[i$1];
        if (range.head.line == n && range.head.ch < curSpaceString.length) {
          var pos$1 = Pos(n, curSpaceString.length);
          replaceOneSelection(doc, i$1, new Range(pos$1, pos$1));
          break
        }
      }
    }
  }

  // This will be set to a {lineWise: bool, text: [string]} object, so
  // that, when pasting, we know what kind of selections the copied
  // text was made out of.
  var lastCopied = null;

  function setLastCopied(newLastCopied) {
    lastCopied = newLastCopied;
  }

  function applyTextInput(cm, inserted, deleted, sel, origin) {
    var doc = cm.doc;
    cm.display.shift = false;
    if (!sel) { sel = doc.sel; }

    var recent = +new Date - 200;
    var paste = origin == "paste" || cm.state.pasteIncoming > recent;
    var textLines = splitLinesAuto(inserted), multiPaste = null;
    // When pasting N lines into N selections, insert one line per selection
    if (paste && sel.ranges.length > 1) {
      if (lastCopied && lastCopied.text.join("\n") == inserted) {
        if (sel.ranges.length % lastCopied.text.length == 0) {
          multiPaste = [];
          for (var i = 0; i < lastCopied.text.length; i++)
            { multiPaste.push(doc.splitLines(lastCopied.text[i])); }
        }
      } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) {
        multiPaste = map(textLines, function (l) { return [l]; });
      }
    }

    var updateInput = cm.curOp.updateInput;
    // Normal behavior is to insert the new text into every selection
    for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) {
      var range = sel.ranges[i$1];
      var from = range.from(), to = range.to();
      if (range.empty()) {
        if (deleted && deleted > 0) // Handle deletion
          { from = Pos(from.line, from.ch - deleted); }
        else if (cm.state.overwrite && !paste) // Handle overwrite
          { to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); }
        else if (paste && lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == textLines.join("\n"))
          { from = to = Pos(from.line, 0); }
      }
      var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines,
                         origin: origin || (paste ? "paste" : cm.state.cutIncoming > recent ? "cut" : "+input")};
      makeChange(cm.doc, changeEvent);
      signalLater(cm, "inputRead", cm, changeEvent);
    }
    if (inserted && !paste)
      { triggerElectric(cm, inserted); }

    ensureCursorVisible(cm);
    if (cm.curOp.updateInput < 2) { cm.curOp.updateInput = updateInput; }
    cm.curOp.typing = true;
    cm.state.pasteIncoming = cm.state.cutIncoming = -1;
  }

  function handlePaste(e, cm) {
    var pasted = e.clipboardData && e.clipboardData.getData("Text");
    if (pasted) {
      e.preventDefault();
      if (!cm.isReadOnly() && !cm.options.disableInput && cm.hasFocus())
        { runInOp(cm, function () { return applyTextInput(cm, pasted, 0, null, "paste"); }); }
      return true
    }
  }

  function triggerElectric(cm, inserted) {
    // When an 'electric' character is inserted, immediately trigger a reindent
    if (!cm.options.electricChars || !cm.options.smartIndent) { return }
    var sel = cm.doc.sel;

    for (var i = sel.ranges.length - 1; i >= 0; i--) {
      var range = sel.ranges[i];
      if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) { continue }
      var mode = cm.getModeAt(range.head);
      var indented = false;
      if (mode.electricChars) {
        for (var j = 0; j < mode.electricChars.length; j++)
          { if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
            indented = indentLine(cm, range.head.line, "smart");
            break
          } }
      } else if (mode.electricInput) {
        if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch)))
          { indented = indentLine(cm, range.head.line, "smart"); }
      }
      if (indented) { signalLater(cm, "electricInput", cm, range.head.line); }
    }
  }

  function copyableRanges(cm) {
    var text = [], ranges = [];
    for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
      var line = cm.doc.sel.ranges[i].head.line;
      var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};
      ranges.push(lineRange);
      text.push(cm.getRange(lineRange.anchor, lineRange.head));
    }
    return {text: text, ranges: ranges}
  }

  function disableBrowserMagic(field, spellcheck, autocorrect, autocapitalize) {
    field.setAttribute("autocorrect", autocorrect ? "on" : "off");
    field.setAttribute("autocapitalize", autocapitalize ? "on" : "off");
    field.setAttribute("spellcheck", !!spellcheck);
  }

  function hiddenTextarea() {
    var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; min-height: 1em; outline: none");
    var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
    // The textarea is kept positioned near the cursor to prevent the
    // fact that it'll be scrolled into view on input from scrolling
    // our fake cursor out of view. On webkit, when wrap=off, paste is
    // very slow. So make the area wide instead.
    if (webkit) { te.style.width = "1000px"; }
    else { te.setAttribute("wrap", "off"); }
    // If border: 0; -- iOS fails to open keyboard (issue #1287)
    if (ios) { te.style.border = "1px solid black"; }
    return div
  }

  // The publicly visible API. Note that methodOp(f) means
  // 'wrap f in an operation, performed on its `this` parameter'.

  // This is not the complete set of editor methods. Most of the
  // methods defined on the Doc type are also injected into
  // CodeMirror.prototype, for backwards compatibility and
  // convenience.

  function addEditorMethods(CodeMirror) {
    var optionHandlers = CodeMirror.optionHandlers;

    var helpers = CodeMirror.helpers = {};

    CodeMirror.prototype = {
      constructor: CodeMirror,
      focus: function(){win(this).focus(); this.display.input.focus();},

      setOption: function(option, value) {
        var options = this.options, old = options[option];
        if (options[option] == value && option != "mode") { return }
        options[option] = value;
        if (optionHandlers.hasOwnProperty(option))
          { operation(this, optionHandlers[option])(this, value, old); }
        signal(this, "optionChange", this, option);
      },

      getOption: function(option) {return this.options[option]},
      getDoc: function() {return this.doc},

      addKeyMap: function(map, bottom) {
        this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map));
      },
      removeKeyMap: function(map) {
        var maps = this.state.keyMaps;
        for (var i = 0; i < maps.length; ++i)
          { if (maps[i] == map || maps[i].name == map) {
            maps.splice(i, 1);
            return true
          } }
      },

      addOverlay: methodOp(function(spec, options) {
        var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
        if (mode.startState) { throw new Error("Overlays may not be stateful.") }
        insertSorted(this.state.overlays,
                     {mode: mode, modeSpec: spec, opaque: options && options.opaque,
                      priority: (options && options.priority) || 0},
                     function (overlay) { return overlay.priority; });
        this.state.modeGen++;
        regChange(this);
      }),
      removeOverlay: methodOp(function(spec) {
        var overlays = this.state.overlays;
        for (var i = 0; i < overlays.length; ++i) {
          var cur = overlays[i].modeSpec;
          if (cur == spec || typeof spec == "string" && cur.name == spec) {
            overlays.splice(i, 1);
            this.state.modeGen++;
            regChange(this);
            return
          }
        }
      }),

      indentLine: methodOp(function(n, dir, aggressive) {
        if (typeof dir != "string" && typeof dir != "number") {
          if (dir == null) { dir = this.options.smartIndent ? "smart" : "prev"; }
          else { dir = dir ? "add" : "subtract"; }
        }
        if (isLine(this.doc, n)) { indentLine(this, n, dir, aggressive); }
      }),
      indentSelection: methodOp(function(how) {
        var ranges = this.doc.sel.ranges, end = -1;
        for (var i = 0; i < ranges.length; i++) {
          var range = ranges[i];
          if (!range.empty()) {
            var from = range.from(), to = range.to();
            var start = Math.max(end, from.line);
            end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
            for (var j = start; j < end; ++j)
              { indentLine(this, j, how); }
            var newRanges = this.doc.sel.ranges;
            if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
              { replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll); }
          } else if (range.head.line > end) {
            indentLine(this, range.head.line, how, true);
            end = range.head.line;
            if (i == this.doc.sel.primIndex) { ensureCursorVisible(this); }
          }
        }
      }),

      // Fetch the parser token for a given character. Useful for hacks
      // that want to inspect the mode state (say, for completion).
      getTokenAt: function(pos, precise) {
        return takeToken(this, pos, precise)
      },

      getLineTokens: function(line, precise) {
        return takeToken(this, Pos(line), precise, true)
      },

      getTokenTypeAt: function(pos) {
        pos = clipPos(this.doc, pos);
        var styles = getLineStyles(this, getLine(this.doc, pos.line));
        var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
        var type;
        if (ch == 0) { type = styles[2]; }
        else { for (;;) {
          var mid = (before + after) >> 1;
          if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { after = mid; }
          else if (styles[mid * 2 + 1] < ch) { before = mid + 1; }
          else { type = styles[mid * 2 + 2]; break }
        } }
        var cut = type ? type.indexOf("overlay ") : -1;
        return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1)
      },

      getModeAt: function(pos) {
        var mode = this.doc.mode;
        if (!mode.innerMode) { return mode }
        return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode
      },

      getHelper: function(pos, type) {
        return this.getHelpers(pos, type)[0]
      },

      getHelpers: function(pos, type) {
        var found = [];
        if (!helpers.hasOwnProperty(type)) { return found }
        var help = helpers[type], mode = this.getModeAt(pos);
        if (typeof mode[type] == "string") {
          if (help[mode[type]]) { found.push(help[mode[type]]); }
        } else if (mode[type]) {
          for (var i = 0; i < mode[type].length; i++) {
            var val = help[mode[type][i]];
            if (val) { found.push(val); }
          }
        } else if (mode.helperType && help[mode.helperType]) {
          found.push(help[mode.helperType]);
        } else if (help[mode.name]) {
          found.push(help[mode.name]);
        }
        for (var i$1 = 0; i$1 < help._global.length; i$1++) {
          var cur = help._global[i$1];
          if (cur.pred(mode, this) && indexOf(found, cur.val) == -1)
            { found.push(cur.val); }
        }
        return found
      },

      getStateAfter: function(line, precise) {
        var doc = this.doc;
        line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
        return getContextBefore(this, line + 1, precise).state
      },

      cursorCoords: function(start, mode) {
        var pos, range = this.doc.sel.primary();
        if (start == null) { pos = range.head; }
        else if (typeof start == "object") { pos = clipPos(this.doc, start); }
        else { pos = start ? range.from() : range.to(); }
        return cursorCoords(this, pos, mode || "page")
      },

      charCoords: function(pos, mode) {
        return charCoords(this, clipPos(this.doc, pos), mode || "page")
      },

      coordsChar: function(coords, mode) {
        coords = fromCoordSystem(this, coords, mode || "page");
        return coordsChar(this, coords.left, coords.top)
      },

      lineAtHeight: function(height, mode) {
        height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
        return lineAtHeight(this.doc, height + this.display.viewOffset)
      },
      heightAtLine: function(line, mode, includeWidgets) {
        var end = false, lineObj;
        if (typeof line == "number") {
          var last = this.doc.first + this.doc.size - 1;
          if (line < this.doc.first) { line = this.doc.first; }
          else if (line > last) { line = last; end = true; }
          lineObj = getLine(this.doc, line);
        } else {
          lineObj = line;
        }
        return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page", includeWidgets || end).top +
          (end ? this.doc.height - heightAtLine(lineObj) : 0)
      },

      defaultTextHeight: function() { return textHeight(this.display) },
      defaultCharWidth: function() { return charWidth(this.display) },

      getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}},

      addWidget: function(pos, node, scroll, vert, horiz) {
        var display = this.display;
        pos = cursorCoords(this, clipPos(this.doc, pos));
        var top = pos.bottom, left = pos.left;
        node.style.position = "absolute";
        node.setAttribute("cm-ignore-events", "true");
        this.display.input.setUneditable(node);
        display.sizer.appendChild(node);
        if (vert == "over") {
          top = pos.top;
        } else if (vert == "above" || vert == "near") {
          var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
          hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
          // Default to positioning above (if specified and possible); otherwise default to positioning below
          if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
            { top = pos.top - node.offsetHeight; }
          else if (pos.bottom + node.offsetHeight <= vspace)
            { top = pos.bottom; }
          if (left + node.offsetWidth > hspace)
            { left = hspace - node.offsetWidth; }
        }
        node.style.top = top + "px";
        node.style.left = node.style.right = "";
        if (horiz == "right") {
          left = display.sizer.clientWidth - node.offsetWidth;
          node.style.right = "0px";
        } else {
          if (horiz == "left") { left = 0; }
          else if (horiz == "middle") { left = (display.sizer.clientWidth - node.offsetWidth) / 2; }
          node.style.left = left + "px";
        }
        if (scroll)
          { scrollIntoView(this, {left: left, top: top, right: left + node.offsetWidth, bottom: top + node.offsetHeight}); }
      },

      triggerOnKeyDown: methodOp(onKeyDown),
      triggerOnKeyPress: methodOp(onKeyPress),
      triggerOnKeyUp: onKeyUp,
      triggerOnMouseDown: methodOp(onMouseDown),

      execCommand: function(cmd) {
        if (commands.hasOwnProperty(cmd))
          { return commands[cmd].call(null, this) }
      },

      triggerElectric: methodOp(function(text) { triggerElectric(this, text); }),

      findPosH: function(from, amount, unit, visually) {
        var dir = 1;
        if (amount < 0) { dir = -1; amount = -amount; }
        var cur = clipPos(this.doc, from);
        for (var i = 0; i < amount; ++i) {
          cur = findPosH(this.doc, cur, dir, unit, visually);
          if (cur.hitSide) { break }
        }
        return cur
      },

      moveH: methodOp(function(dir, unit) {
        var this$1 = this;

        this.extendSelectionsBy(function (range) {
          if (this$1.display.shift || this$1.doc.extend || range.empty())
            { return findPosH(this$1.doc, range.head, dir, unit, this$1.options.rtlMoveVisually) }
          else
            { return dir < 0 ? range.from() : range.to() }
        }, sel_move);
      }),

      deleteH: methodOp(function(dir, unit) {
        var sel = this.doc.sel, doc = this.doc;
        if (sel.somethingSelected())
          { doc.replaceSelection("", null, "+delete"); }
        else
          { deleteNearSelection(this, function (range) {
            var other = findPosH(doc, range.head, dir, unit, false);
            return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other}
          }); }
      }),

      findPosV: function(from, amount, unit, goalColumn) {
        var dir = 1, x = goalColumn;
        if (amount < 0) { dir = -1; amount = -amount; }
        var cur = clipPos(this.doc, from);
        for (var i = 0; i < amount; ++i) {
          var coords = cursorCoords(this, cur, "div");
          if (x == null) { x = coords.left; }
          else { coords.left = x; }
          cur = findPosV(this, coords, dir, unit);
          if (cur.hitSide) { break }
        }
        return cur
      },

      moveV: methodOp(function(dir, unit) {
        var this$1 = this;

        var doc = this.doc, goals = [];
        var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected();
        doc.extendSelectionsBy(function (range) {
          if (collapse)
            { return dir < 0 ? range.from() : range.to() }
          var headPos = cursorCoords(this$1, range.head, "div");
          if (range.goalColumn != null) { headPos.left = range.goalColumn; }
          goals.push(headPos.left);
          var pos = findPosV(this$1, headPos, dir, unit);
          if (unit == "page" && range == doc.sel.primary())
            { addToScrollTop(this$1, charCoords(this$1, pos, "div").top - headPos.top); }
          return pos
        }, sel_move);
        if (goals.length) { for (var i = 0; i < doc.sel.ranges.length; i++)
          { doc.sel.ranges[i].goalColumn = goals[i]; } }
      }),

      // Find the word at the given position (as returned by coordsChar).
      findWordAt: function(pos) {
        var doc = this.doc, line = getLine(doc, pos.line).text;
        var start = pos.ch, end = pos.ch;
        if (line) {
          var helper = this.getHelper(pos, "wordChars");
          if ((pos.sticky == "before" || end == line.length) && start) { --start; } else { ++end; }
          var startChar = line.charAt(start);
          var check = isWordChar(startChar, helper)
            ? function (ch) { return isWordChar(ch, helper); }
            : /\s/.test(startChar) ? function (ch) { return /\s/.test(ch); }
            : function (ch) { return (!/\s/.test(ch) && !isWordChar(ch)); };
          while (start > 0 && check(line.charAt(start - 1))) { --start; }
          while (end < line.length && check(line.charAt(end))) { ++end; }
        }
        return new Range(Pos(pos.line, start), Pos(pos.line, end))
      },

      toggleOverwrite: function(value) {
        if (value != null && value == this.state.overwrite) { return }
        if (this.state.overwrite = !this.state.overwrite)
          { addClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
        else
          { rmClass(this.display.cursorDiv, "CodeMirror-overwrite"); }

        signal(this, "overwriteToggle", this, this.state.overwrite);
      },
      hasFocus: function() { return this.display.input.getField() == activeElt(doc(this)) },
      isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) },

      scrollTo: methodOp(function (x, y) { scrollToCoords(this, x, y); }),
      getScrollInfo: function() {
        var scroller = this.display.scroller;
        return {left: scroller.scrollLeft, top: scroller.scrollTop,
                height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
                width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
                clientHeight: displayHeight(this), clientWidth: displayWidth(this)}
      },

      scrollIntoView: methodOp(function(range, margin) {
        if (range == null) {
          range = {from: this.doc.sel.primary().head, to: null};
          if (margin == null) { margin = this.options.cursorScrollMargin; }
        } else if (typeof range == "number") {
          range = {from: Pos(range, 0), to: null};
        } else if (range.from == null) {
          range = {from: range, to: null};
        }
        if (!range.to) { range.to = range.from; }
        range.margin = margin || 0;

        if (range.from.line != null) {
          scrollToRange(this, range);
        } else {
          scrollToCoordsRange(this, range.from, range.to, range.margin);
        }
      }),

      setSize: methodOp(function(width, height) {
        var this$1 = this;

        var interpret = function (val) { return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; };
        if (width != null) { this.display.wrapper.style.width = interpret(width); }
        if (height != null) { this.display.wrapper.style.height = interpret(height); }
        if (this.options.lineWrapping) { clearLineMeasurementCache(this); }
        var lineNo = this.display.viewFrom;
        this.doc.iter(lineNo, this.display.viewTo, function (line) {
          if (line.widgets) { for (var i = 0; i < line.widgets.length; i++)
            { if (line.widgets[i].noHScroll) { regLineChange(this$1, lineNo, "widget"); break } } }
          ++lineNo;
        });
        this.curOp.forceUpdate = true;
        signal(this, "refresh", this);
      }),

      operation: function(f){return runInOp(this, f)},
      startOperation: function(){return startOperation(this)},
      endOperation: function(){return endOperation(this)},

      refresh: methodOp(function() {
        var oldHeight = this.display.cachedTextHeight;
        regChange(this);
        this.curOp.forceUpdate = true;
        clearCaches(this);
        scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop);
        updateGutterSpace(this.display);
        if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5 || this.options.lineWrapping)
          { estimateLineHeights(this); }
        signal(this, "refresh", this);
      }),

      swapDoc: methodOp(function(doc) {
        var old = this.doc;
        old.cm = null;
        // Cancel the current text selection if any (#5821)
        if (this.state.selectingText) { this.state.selectingText(); }
        attachDoc(this, doc);
        clearCaches(this);
        this.display.input.reset();
        scrollToCoords(this, doc.scrollLeft, doc.scrollTop);
        this.curOp.forceScroll = true;
        signalLater(this, "swapDoc", this, old);
        return old
      }),

      phrase: function(phraseText) {
        var phrases = this.options.phrases;
        return phrases && Object.prototype.hasOwnProperty.call(phrases, phraseText) ? phrases[phraseText] : phraseText
      },

      getInputField: function(){return this.display.input.getField()},
      getWrapperElement: function(){return this.display.wrapper},
      getScrollerElement: function(){return this.display.scroller},
      getGutterElement: function(){return this.display.gutters}
    };
    eventMixin(CodeMirror);

    CodeMirror.registerHelper = function(type, name, value) {
      if (!helpers.hasOwnProperty(type)) { helpers[type] = CodeMirror[type] = {_global: []}; }
      helpers[type][name] = value;
    };
    CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
      CodeMirror.registerHelper(type, name, value);
      helpers[type]._global.push({pred: predicate, val: value});
    };
  }

  // Used for horizontal relative motion. Dir is -1 or 1 (left or
  // right), unit can be "codepoint", "char", "column" (like char, but
  // doesn't cross line boundaries), "word" (across next word), or
  // "group" (to the start of next group of word or
  // non-word-non-whitespace chars). The visually param controls
  // whether, in right-to-left text, direction 1 means to move towards
  // the next index in the string, or towards the character to the right
  // of the current position. The resulting position will have a
  // hitSide=true property if it reached the end of the document.
  function findPosH(doc, pos, dir, unit, visually) {
    var oldPos = pos;
    var origDir = dir;
    var lineObj = getLine(doc, pos.line);
    var lineDir = visually && doc.direction == "rtl" ? -dir : dir;
    function findNextLine() {
      var l = pos.line + lineDir;
      if (l < doc.first || l >= doc.first + doc.size) { return false }
      pos = new Pos(l, pos.ch, pos.sticky);
      return lineObj = getLine(doc, l)
    }
    function moveOnce(boundToLine) {
      var next;
      if (unit == "codepoint") {
        var ch = lineObj.text.charCodeAt(pos.ch + (dir > 0 ? 0 : -1));
        if (isNaN(ch)) {
          next = null;
        } else {
          var astral = dir > 0 ? ch >= 0xD800 && ch < 0xDC00 : ch >= 0xDC00 && ch < 0xDFFF;
          next = new Pos(pos.line, Math.max(0, Math.min(lineObj.text.length, pos.ch + dir * (astral ? 2 : 1))), -dir);
        }
      } else if (visually) {
        next = moveVisually(doc.cm, lineObj, pos, dir);
      } else {
        next = moveLogically(lineObj, pos, dir);
      }
      if (next == null) {
        if (!boundToLine && findNextLine())
          { pos = endOfLine(visually, doc.cm, lineObj, pos.line, lineDir); }
        else
          { return false }
      } else {
        pos = next;
      }
      return true
    }

    if (unit == "char" || unit == "codepoint") {
      moveOnce();
    } else if (unit == "column") {
      moveOnce(true);
    } else if (unit == "word" || unit == "group") {
      var sawType = null, group = unit == "group";
      var helper = doc.cm && doc.cm.getHelper(pos, "wordChars");
      for (var first = true;; first = false) {
        if (dir < 0 && !moveOnce(!first)) { break }
        var cur = lineObj.text.charAt(pos.ch) || "\n";
        var type = isWordChar(cur, helper) ? "w"
          : group && cur == "\n" ? "n"
          : !group || /\s/.test(cur) ? null
          : "p";
        if (group && !first && !type) { type = "s"; }
        if (sawType && sawType != type) {
          if (dir < 0) {dir = 1; moveOnce(); pos.sticky = "after";}
          break
        }

        if (type) { sawType = type; }
        if (dir > 0 && !moveOnce(!first)) { break }
      }
    }
    var result = skipAtomic(doc, pos, oldPos, origDir, true);
    if (equalCursorPos(oldPos, result)) { result.hitSide = true; }
    return result
  }

  // For relative vertical movement. Dir may be -1 or 1. Unit can be
  // "page" or "line". The resulting position will have a hitSide=true
  // property if it reached the end of the document.
  function findPosV(cm, pos, dir, unit) {
    var doc = cm.doc, x = pos.left, y;
    if (unit == "page") {
      var pageSize = Math.min(cm.display.wrapper.clientHeight, win(cm).innerHeight || doc(cm).documentElement.clientHeight);
      var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3);
      y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount;

    } else if (unit == "line") {
      y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
    }
    var target;
    for (;;) {
      target = coordsChar(cm, x, y);
      if (!target.outside) { break }
      if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break }
      y += dir * 5;
    }
    return target
  }

  // CONTENTEDITABLE INPUT STYLE

  var ContentEditableInput = function(cm) {
    this.cm = cm;
    this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;
    this.polling = new Delayed();
    this.composing = null;
    this.gracePeriod = false;
    this.readDOMTimeout = null;
  };

  ContentEditableInput.prototype.init = function (display) {
      var this$1 = this;

    var input = this, cm = input.cm;
    var div = input.div = display.lineDiv;
    div.contentEditable = true;
    disableBrowserMagic(div, cm.options.spellcheck, cm.options.autocorrect, cm.options.autocapitalize);

    function belongsToInput(e) {
      for (var t = e.target; t; t = t.parentNode) {
        if (t == div) { return true }
        if (/\bCodeMirror-(?:line)?widget\b/.test(t.className)) { break }
      }
      return false
    }

    on(div, "paste", function (e) {
      if (!belongsToInput(e) || signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
      // IE doesn't fire input events, so we schedule a read for the pasted content in this way
      if (ie_version <= 11) { setTimeout(operation(cm, function () { return this$1.updateFromDOM(); }), 20); }
    });

    on(div, "compositionstart", function (e) {
      this$1.composing = {data: e.data, done: false};
    });
    on(div, "compositionupdate", function (e) {
      if (!this$1.composing) { this$1.composing = {data: e.data, done: false}; }
    });
    on(div, "compositionend", function (e) {
      if (this$1.composing) {
        if (e.data != this$1.composing.data) { this$1.readFromDOMSoon(); }
        this$1.composing.done = true;
      }
    });

    on(div, "touchstart", function () { return input.forceCompositionEnd(); });

    on(div, "input", function () {
      if (!this$1.composing) { this$1.readFromDOMSoon(); }
    });

    function onCopyCut(e) {
      if (!belongsToInput(e) || signalDOMEvent(cm, e)) { return }
      if (cm.somethingSelected()) {
        setLastCopied({lineWise: false, text: cm.getSelections()});
        if (e.type == "cut") { cm.replaceSelection("", null, "cut"); }
      } else if (!cm.options.lineWiseCopyCut) {
        return
      } else {
        var ranges = copyableRanges(cm);
        setLastCopied({lineWise: true, text: ranges.text});
        if (e.type == "cut") {
          cm.operation(function () {
            cm.setSelections(ranges.ranges, 0, sel_dontScroll);
            cm.replaceSelection("", null, "cut");
          });
        }
      }
      if (e.clipboardData) {
        e.clipboardData.clearData();
        var content = lastCopied.text.join("\n");
        // iOS exposes the clipboard API, but seems to discard content inserted into it
        e.clipboardData.setData("Text", content);
        if (e.clipboardData.getData("Text") == content) {
          e.preventDefault();
          return
        }
      }
      // Old-fashioned briefly-focus-a-textarea hack
      var kludge = hiddenTextarea(), te = kludge.firstChild;
      disableBrowserMagic(te);
      cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);
      te.value = lastCopied.text.join("\n");
      var hadFocus = activeElt(div.ownerDocument);
      selectInput(te);
      setTimeout(function () {
        cm.display.lineSpace.removeChild(kludge);
        hadFocus.focus();
        if (hadFocus == div) { input.showPrimarySelection(); }
      }, 50);
    }
    on(div, "copy", onCopyCut);
    on(div, "cut", onCopyCut);
  };

  ContentEditableInput.prototype.screenReaderLabelChanged = function (label) {
    // Label for screenreaders, accessibility
    if(label) {
      this.div.setAttribute('aria-label', label);
    } else {
      this.div.removeAttribute('aria-label');
    }
  };

  ContentEditableInput.prototype.prepareSelection = function () {
    var result = prepareSelection(this.cm, false);
    result.focus = activeElt(this.div.ownerDocument) == this.div;
    return result
  };

  ContentEditableInput.prototype.showSelection = function (info, takeFocus) {
    if (!info || !this.cm.display.view.length) { return }
    if (info.focus || takeFocus) { this.showPrimarySelection(); }
    this.showMultipleSelections(info);
  };

  ContentEditableInput.prototype.getSelection = function () {
    return this.cm.display.wrapper.ownerDocument.getSelection()
  };

  ContentEditableInput.prototype.showPrimarySelection = function () {
    var sel = this.getSelection(), cm = this.cm, prim = cm.doc.sel.primary();
    var from = prim.from(), to = prim.to();

    if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) {
      sel.removeAllRanges();
      return
    }

    var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
    var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset);
    if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
        cmp(minPos(curAnchor, curFocus), from) == 0 &&
        cmp(maxPos(curAnchor, curFocus), to) == 0)
      { return }

    var view = cm.display.view;
    var start = (from.line >= cm.display.viewFrom && posToDOM(cm, from)) ||
        {node: view[0].measure.map[2], offset: 0};
    var end = to.line < cm.display.viewTo && posToDOM(cm, to);
    if (!end) {
      var measure = view[view.length - 1].measure;
      var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;
      end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]};
    }

    if (!start || !end) {
      sel.removeAllRanges();
      return
    }

    var old = sel.rangeCount && sel.getRangeAt(0), rng;
    try { rng = range(start.node, start.offset, end.offset, end.node); }
    catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
    if (rng) {
      if (!gecko && cm.state.focused) {
        sel.collapse(start.node, start.offset);
        if (!rng.collapsed) {
          sel.removeAllRanges();
          sel.addRange(rng);
        }
      } else {
        sel.removeAllRanges();
        sel.addRange(rng);
      }
      if (old && sel.anchorNode == null) { sel.addRange(old); }
      else if (gecko) { this.startGracePeriod(); }
    }
    this.rememberSelection();
  };

  ContentEditableInput.prototype.startGracePeriod = function () {
      var this$1 = this;

    clearTimeout(this.gracePeriod);
    this.gracePeriod = setTimeout(function () {
      this$1.gracePeriod = false;
      if (this$1.selectionChanged())
        { this$1.cm.operation(function () { return this$1.cm.curOp.selectionChanged = true; }); }
    }, 20);
  };

  ContentEditableInput.prototype.showMultipleSelections = function (info) {
    removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
    removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
  };

  ContentEditableInput.prototype.rememberSelection = function () {
    var sel = this.getSelection();
    this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset;
    this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset;
  };

  ContentEditableInput.prototype.selectionInEditor = function () {
    var sel = this.getSelection();
    if (!sel.rangeCount) { return false }
    var node = sel.getRangeAt(0).commonAncestorContainer;
    return contains(this.div, node)
  };

  ContentEditableInput.prototype.focus = function () {
    if (this.cm.options.readOnly != "nocursor") {
      if (!this.selectionInEditor() || activeElt(this.div.ownerDocument) != this.div)
        { this.showSelection(this.prepareSelection(), true); }
      this.div.focus();
    }
  };
  ContentEditableInput.prototype.blur = function () { this.div.blur(); };
  ContentEditableInput.prototype.getField = function () { return this.div };

  ContentEditableInput.prototype.supportsTouch = function () { return true };

  ContentEditableInput.prototype.receivedFocus = function () {
      var this$1 = this;

    var input = this;
    if (this.selectionInEditor())
      { setTimeout(function () { return this$1.pollSelection(); }, 20); }
    else
      { runInOp(this.cm, function () { return input.cm.curOp.selectionChanged = true; }); }

    function poll() {
      if (input.cm.state.focused) {
        input.pollSelection();
        input.polling.set(input.cm.options.pollInterval, poll);
      }
    }
    this.polling.set(this.cm.options.pollInterval, poll);
  };

  ContentEditableInput.prototype.selectionChanged = function () {
    var sel = this.getSelection();
    return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
      sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset
  };

  ContentEditableInput.prototype.pollSelection = function () {
    if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) { return }
    var sel = this.getSelection(), cm = this.cm;
    // On Android Chrome (version 56, at least), backspacing into an
    // uneditable block element will put the cursor in that element,
    // and then, because it's not editable, hide the virtual keyboard.
    // Because Android doesn't allow us to actually detect backspace
    // presses in a sane way, this code checks for when that happens
    // and simulates a backspace press in this case.
    if (android && chrome && this.cm.display.gutterSpecs.length && isInGutter(sel.anchorNode)) {
      this.cm.triggerOnKeyDown({type: "keydown", keyCode: 8, preventDefault: Math.abs});
      this.blur();
      this.focus();
      return
    }
    if (this.composing) { return }
    this.rememberSelection();
    var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
    var head = domToPos(cm, sel.focusNode, sel.focusOffset);
    if (anchor && head) { runInOp(cm, function () {
      setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);
      if (anchor.bad || head.bad) { cm.curOp.selectionChanged = true; }
    }); }
  };

  ContentEditableInput.prototype.pollContent = function () {
    if (this.readDOMTimeout != null) {
      clearTimeout(this.readDOMTimeout);
      this.readDOMTimeout = null;
    }

    var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();
    var from = sel.from(), to = sel.to();
    if (from.ch == 0 && from.line > cm.firstLine())
      { from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length); }
    if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine())
      { to = Pos(to.line + 1, 0); }
    if (from.line < display.viewFrom || to.line > display.viewTo - 1) { return false }

    var fromIndex, fromLine, fromNode;
    if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
      fromLine = lineNo(display.view[0].line);
      fromNode = display.view[0].node;
    } else {
      fromLine = lineNo(display.view[fromIndex].line);
      fromNode = display.view[fromIndex - 1].node.nextSibling;
    }
    var toIndex = findViewIndex(cm, to.line);
    var toLine, toNode;
    if (toIndex == display.view.length - 1) {
      toLine = display.viewTo - 1;
      toNode = display.lineDiv.lastChild;
    } else {
      toLine = lineNo(display.view[toIndex + 1].line) - 1;
      toNode = display.view[toIndex + 1].node.previousSibling;
    }

    if (!fromNode) { return false }
    var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));
    var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));
    while (newText.length > 1 && oldText.length > 1) {
      if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; }
      else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; }
      else { break }
    }

    var cutFront = 0, cutEnd = 0;
    var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);
    while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
      { ++cutFront; }
    var newBot = lst(newText), oldBot = lst(oldText);
    var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
                             oldBot.length - (oldText.length == 1 ? cutFront : 0));
    while (cutEnd < maxCutEnd &&
           newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
      { ++cutEnd; }
    // Try to move start of change to start of selection if ambiguous
    if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) {
      while (cutFront && cutFront > from.ch &&
             newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) {
        cutFront--;
        cutEnd++;
      }
    }

    newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, "");
    newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, "");

    var chFrom = Pos(fromLine, cutFront);
    var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);
    if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
      replaceRange(cm.doc, newText, chFrom, chTo, "+input");
      return true
    }
  };

  ContentEditableInput.prototype.ensurePolled = function () {
    this.forceCompositionEnd();
  };
  ContentEditableInput.prototype.reset = function () {
    this.forceCompositionEnd();
  };
  ContentEditableInput.prototype.forceCompositionEnd = function () {
    if (!this.composing) { return }
    clearTimeout(this.readDOMTimeout);
    this.composing = null;
    this.updateFromDOM();
    this.div.blur();
    this.div.focus();
  };
  ContentEditableInput.prototype.readFromDOMSoon = function () {
      var this$1 = this;

    if (this.readDOMTimeout != null) { return }
    this.readDOMTimeout = setTimeout(function () {
      this$1.readDOMTimeout = null;
      if (this$1.composing) {
        if (this$1.composing.done) { this$1.composing = null; }
        else { return }
      }
      this$1.updateFromDOM();
    }, 80);
  };

  ContentEditableInput.prototype.updateFromDOM = function () {
      var this$1 = this;

    if (this.cm.isReadOnly() || !this.pollContent())
      { runInOp(this.cm, function () { return regChange(this$1.cm); }); }
  };

  ContentEditableInput.prototype.setUneditable = function (node) {
    node.contentEditable = "false";
  };

  ContentEditableInput.prototype.onKeyPress = function (e) {
    if (e.charCode == 0 || this.composing) { return }
    e.preventDefault();
    if (!this.cm.isReadOnly())
      { operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); }
  };

  ContentEditableInput.prototype.readOnlyChanged = function (val) {
    this.div.contentEditable = String(val != "nocursor");
  };

  ContentEditableInput.prototype.onContextMenu = function () {};
  ContentEditableInput.prototype.resetPosition = function () {};

  ContentEditableInput.prototype.needsContentAttribute = true;

  function posToDOM(cm, pos) {
    var view = findViewForLine(cm, pos.line);
    if (!view || view.hidden) { return null }
    var line = getLine(cm.doc, pos.line);
    var info = mapFromLineView(view, line, pos.line);

    var order = getOrder(line, cm.doc.direction), side = "left";
    if (order) {
      var partPos = getBidiPartAt(order, pos.ch);
      side = partPos % 2 ? "right" : "left";
    }
    var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);
    result.offset = result.collapse == "right" ? result.end : result.start;
    return result
  }

  function isInGutter(node) {
    for (var scan = node; scan; scan = scan.parentNode)
      { if (/CodeMirror-gutter-wrapper/.test(scan.className)) { return true } }
    return false
  }

  function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos }

  function domTextBetween(cm, from, to, fromLine, toLine) {
    var text = "", closing = false, lineSep = cm.doc.lineSeparator(), extraLinebreak = false;
    function recognizeMarker(id) { return function (marker) { return marker.id == id; } }
    function close() {
      if (closing) {
        text += lineSep;
        if (extraLinebreak) { text += lineSep; }
        closing = extraLinebreak = false;
      }
    }
    function addText(str) {
      if (str) {
        close();
        text += str;
      }
    }
    function walk(node) {
      if (node.nodeType == 1) {
        var cmText = node.getAttribute("cm-text");
        if (cmText) {
          addText(cmText);
          return
        }
        var markerID = node.getAttribute("cm-marker"), range;
        if (markerID) {
          var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));
          if (found.length && (range = found[0].find(0)))
            { addText(getBetween(cm.doc, range.from, range.to).join(lineSep)); }
          return
        }
        if (node.getAttribute("contenteditable") == "false") { return }
        var isBlock = /^(pre|div|p|li|table|br)$/i.test(node.nodeName);
        if (!/^br$/i.test(node.nodeName) && node.textContent.length == 0) { return }

        if (isBlock) { close(); }
        for (var i = 0; i < node.childNodes.length; i++)
          { walk(node.childNodes[i]); }

        if (/^(pre|p)$/i.test(node.nodeName)) { extraLinebreak = true; }
        if (isBlock) { closing = true; }
      } else if (node.nodeType == 3) {
        addText(node.nodeValue.replace(/\u200b/g, "").replace(/\u00a0/g, " "));
      }
    }
    for (;;) {
      walk(from);
      if (from == to) { break }
      from = from.nextSibling;
      extraLinebreak = false;
    }
    return text
  }

  function domToPos(cm, node, offset) {
    var lineNode;
    if (node == cm.display.lineDiv) {
      lineNode = cm.display.lineDiv.childNodes[offset];
      if (!lineNode) { return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) }
      node = null; offset = 0;
    } else {
      for (lineNode = node;; lineNode = lineNode.parentNode) {
        if (!lineNode || lineNode == cm.display.lineDiv) { return null }
        if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { break }
      }
    }
    for (var i = 0; i < cm.display.view.length; i++) {
      var lineView = cm.display.view[i];
      if (lineView.node == lineNode)
        { return locateNodeInLineView(lineView, node, offset) }
    }
  }

  function locateNodeInLineView(lineView, node, offset) {
    var wrapper = lineView.text.firstChild, bad = false;
    if (!node || !contains(wrapper, node)) { return badPos(Pos(lineNo(lineView.line), 0), true) }
    if (node == wrapper) {
      bad = true;
      node = wrapper.childNodes[offset];
      offset = 0;
      if (!node) {
        var line = lineView.rest ? lst(lineView.rest) : lineView.line;
        return badPos(Pos(lineNo(line), line.text.length), bad)
      }
    }

    var textNode = node.nodeType == 3 ? node : null, topNode = node;
    if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
      textNode = node.firstChild;
      if (offset) { offset = textNode.nodeValue.length; }
    }
    while (topNode.parentNode != wrapper) { topNode = topNode.parentNode; }
    var measure = lineView.measure, maps = measure.maps;

    function find(textNode, topNode, offset) {
      for (var i = -1; i < (maps ? maps.length : 0); i++) {
        var map = i < 0 ? measure.map : maps[i];
        for (var j = 0; j < map.length; j += 3) {
          var curNode = map[j + 2];
          if (curNode == textNode || curNode == topNode) {
            var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);
            var ch = map[j] + offset;
            if (offset < 0 || curNode != textNode) { ch = map[j + (offset ? 1 : 0)]; }
            return Pos(line, ch)
          }
        }
      }
    }
    var found = find(textNode, topNode, offset);
    if (found) { return badPos(found, bad) }

    // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
    for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
      found = find(after, after.firstChild, 0);
      if (found)
        { return badPos(Pos(found.line, found.ch - dist), bad) }
      else
        { dist += after.textContent.length; }
    }
    for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) {
      found = find(before, before.firstChild, -1);
      if (found)
        { return badPos(Pos(found.line, found.ch + dist$1), bad) }
      else
        { dist$1 += before.textContent.length; }
    }
  }

  // TEXTAREA INPUT STYLE

  var TextareaInput = function(cm) {
    this.cm = cm;
    // See input.poll and input.reset
    this.prevInput = "";

    // Flag that indicates whether we expect input to appear real soon
    // now (after some event like 'keypress' or 'input') and are
    // polling intensively.
    this.pollingFast = false;
    // Self-resetting timeout for the poller
    this.polling = new Delayed();
    // Used to work around IE issue with selection being forgotten when focus moves away from textarea
    this.hasSelection = false;
    this.composing = null;
    this.resetting = false;
  };

  TextareaInput.prototype.init = function (display) {
      var this$1 = this;

    var input = this, cm = this.cm;
    this.createField(display);
    var te = this.textarea;

    display.wrapper.insertBefore(this.wrapper, display.wrapper.firstChild);

    // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
    if (ios) { te.style.width = "0px"; }

    on(te, "input", function () {
      if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null; }
      input.poll();
    });

    on(te, "paste", function (e) {
      if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }

      cm.state.pasteIncoming = +new Date;
      input.fastPoll();
    });

    function prepareCopyCut(e) {
      if (signalDOMEvent(cm, e)) { return }
      if (cm.somethingSelected()) {
        setLastCopied({lineWise: false, text: cm.getSelections()});
      } else if (!cm.options.lineWiseCopyCut) {
        return
      } else {
        var ranges = copyableRanges(cm);
        setLastCopied({lineWise: true, text: ranges.text});
        if (e.type == "cut") {
          cm.setSelections(ranges.ranges, null, sel_dontScroll);
        } else {
          input.prevInput = "";
          te.value = ranges.text.join("\n");
          selectInput(te);
        }
      }
      if (e.type == "cut") { cm.state.cutIncoming = +new Date; }
    }
    on(te, "cut", prepareCopyCut);
    on(te, "copy", prepareCopyCut);

    on(display.scroller, "paste", function (e) {
      if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return }
      if (!te.dispatchEvent) {
        cm.state.pasteIncoming = +new Date;
        input.focus();
        return
      }

      // Pass the `paste` event to the textarea so it's handled by its event listener.
      var event = new Event("paste");
      event.clipboardData = e.clipboardData;
      te.dispatchEvent(event);
    });

    // Prevent normal selection in the editor (we handle our own)
    on(display.lineSpace, "selectstart", function (e) {
      if (!eventInWidget(display, e)) { e_preventDefault(e); }
    });

    on(te, "compositionstart", function () {
      var start = cm.getCursor("from");
      if (input.composing) { input.composing.range.clear(); }
      input.composing = {
        start: start,
        range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
      };
    });
    on(te, "compositionend", function () {
      if (input.composing) {
        input.poll();
        input.composing.range.clear();
        input.composing = null;
      }
    });
  };

  TextareaInput.prototype.createField = function (_display) {
    // Wraps and hides input textarea
    this.wrapper = hiddenTextarea();
    // The semihidden textarea that is focused when the editor is
    // focused, and receives input.
    this.textarea = this.wrapper.firstChild;
    var opts = this.cm.options;
    disableBrowserMagic(this.textarea, opts.spellcheck, opts.autocorrect, opts.autocapitalize);
  };

  TextareaInput.prototype.screenReaderLabelChanged = function (label) {
    // Label for screenreaders, accessibility
    if(label) {
      this.textarea.setAttribute('aria-label', label);
    } else {
      this.textarea.removeAttribute('aria-label');
    }
  };

  TextareaInput.prototype.prepareSelection = function () {
    // Redraw the selection and/or cursor
    var cm = this.cm, display = cm.display, doc = cm.doc;
    var result = prepareSelection(cm);

    // Move the hidden textarea near the cursor to prevent scrolling artifacts
    if (cm.options.moveInputWithCursor) {
      var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
      var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
      result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
                                          headPos.top + lineOff.top - wrapOff.top));
      result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
                                           headPos.left + lineOff.left - wrapOff.left));
    }

    return result
  };

  TextareaInput.prototype.showSelection = function (drawn) {
    var cm = this.cm, display = cm.display;
    removeChildrenAndAdd(display.cursorDiv, drawn.cursors);
    removeChildrenAndAdd(display.selectionDiv, drawn.selection);
    if (drawn.teTop != null) {
      this.wrapper.style.top = drawn.teTop + "px";
      this.wrapper.style.left = drawn.teLeft + "px";
    }
  };

  // Reset the input to correspond to the selection (or to be empty,
  // when not typing and nothing is selected)
  TextareaInput.prototype.reset = function (typing) {
    if (this.contextMenuPending || this.composing && typing) { return }
    var cm = this.cm;
    this.resetting = true;
    if (cm.somethingSelected()) {
      this.prevInput = "";
      var content = cm.getSelection();
      this.textarea.value = content;
      if (cm.state.focused) { selectInput(this.textarea); }
      if (ie && ie_version >= 9) { this.hasSelection = content; }
    } else if (!typing) {
      this.prevInput = this.textarea.value = "";
      if (ie && ie_version >= 9) { this.hasSelection = null; }
    }
    this.resetting = false;
  };

  TextareaInput.prototype.getField = function () { return this.textarea };

  TextareaInput.prototype.supportsTouch = function () { return false };

  TextareaInput.prototype.focus = function () {
    if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt(this.textarea.ownerDocument) != this.textarea)) {
      try { this.textarea.focus(); }
      catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
    }
  };

  TextareaInput.prototype.blur = function () { this.textarea.blur(); };

  TextareaInput.prototype.resetPosition = function () {
    this.wrapper.style.top = this.wrapper.style.left = 0;
  };

  TextareaInput.prototype.receivedFocus = function () { this.slowPoll(); };

  // Poll for input changes, using the normal rate of polling. This
  // runs as long as the editor is focused.
  TextareaInput.prototype.slowPoll = function () {
      var this$1 = this;

    if (this.pollingFast) { return }
    this.polling.set(this.cm.options.pollInterval, function () {
      this$1.poll();
      if (this$1.cm.state.focused) { this$1.slowPoll(); }
    });
  };

  // When an event has just come in that is likely to add or change
  // something in the input textarea, we poll faster, to ensure that
  // the change appears on the screen quickly.
  TextareaInput.prototype.fastPoll = function () {
    var missed = false, input = this;
    input.pollingFast = true;
    function p() {
      var changed = input.poll();
      if (!changed && !missed) {missed = true; input.polling.set(60, p);}
      else {input.pollingFast = false; input.slowPoll();}
    }
    input.polling.set(20, p);
  };

  // Read input from the textarea, and update the document to match.
  // When something is selected, it is present in the textarea, and
  // selected (unless it is huge, in which case a placeholder is
  // used). When nothing is selected, the cursor sits after previously
  // seen text (can be empty), which is stored in prevInput (we must
  // not reset the textarea when typing, because that breaks IME).
  TextareaInput.prototype.poll = function () {
      var this$1 = this;

    var cm = this.cm, input = this.textarea, prevInput = this.prevInput;
    // Since this is called a *lot*, try to bail out as cheaply as
    // possible when it is clear that nothing happened. hasSelection
    // will be the case when there is a lot of text in the textarea,
    // in which case reading its value would be expensive.
    if (this.contextMenuPending || this.resetting || !cm.state.focused ||
        (hasSelection(input) && !prevInput && !this.composing) ||
        cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq)
      { return false }

    var text = input.value;
    // If nothing changed, bail.
    if (text == prevInput && !cm.somethingSelected()) { return false }
    // Work around nonsensical selection resetting in IE9/10, and
    // inexplicable appearance of private area unicode characters on
    // some key combos in Mac (#2689).
    if (ie && ie_version >= 9 && this.hasSelection === text ||
        mac && /[\uf700-\uf7ff]/.test(text)) {
      cm.display.input.reset();
      return false
    }

    if (cm.doc.sel == cm.display.selForContextMenu) {
      var first = text.charCodeAt(0);
      if (first == 0x200b && !prevInput) { prevInput = "\u200b"; }
      if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo") }
    }
    // Find the part of the input that is actually new
    var same = 0, l = Math.min(prevInput.length, text.length);
    while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { ++same; }

    runInOp(cm, function () {
      applyTextInput(cm, text.slice(same), prevInput.length - same,
                     null, this$1.composing ? "*compose" : null);

      // Don't leave long text in the textarea, since it makes further polling slow
      if (text.length > 1000 || text.indexOf("\n") > -1) { input.value = this$1.prevInput = ""; }
      else { this$1.prevInput = text; }

      if (this$1.composing) {
        this$1.composing.range.clear();
        this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor("to"),
                                           {className: "CodeMirror-composing"});
      }
    });
    return true
  };

  TextareaInput.prototype.ensurePolled = function () {
    if (this.pollingFast && this.poll()) { this.pollingFast = false; }
  };

  TextareaInput.prototype.onKeyPress = function () {
    if (ie && ie_version >= 9) { this.hasSelection = null; }
    this.fastPoll();
  };

  TextareaInput.prototype.onContextMenu = function (e) {
    var input = this, cm = input.cm, display = cm.display, te = input.textarea;
    if (input.contextMenuPending) { input.contextMenuPending(); }
    var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
    if (!pos || presto) { return } // Opera is difficult.

    // Reset the current text selection only if the click is done outside of the selection
    // and 'resetSelectionOnContextMenu' option is true.
    var reset = cm.options.resetSelectionOnContextMenu;
    if (reset && cm.doc.sel.contains(pos) == -1)
      { operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); }

    var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText;
    var wrapperBox = input.wrapper.offsetParent.getBoundingClientRect();
    input.wrapper.style.cssText = "position: static";
    te.style.cssText = "position: absolute; width: 30px; height: 30px;\n      top: " + (e.clientY - wrapperBox.top - 5) + "px; left: " + (e.clientX - wrapperBox.left - 5) + "px;\n      z-index: 1000; background: " + (ie ? "rgba(255, 255, 255, .05)" : "transparent") + ";\n      outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
    var oldScrollY;
    if (webkit) { oldScrollY = te.ownerDocument.defaultView.scrollY; } // Work around Chrome issue (#2712)
    display.input.focus();
    if (webkit) { te.ownerDocument.defaultView.scrollTo(null, oldScrollY); }
    display.input.reset();
    // Adds "Select all" to context menu in FF
    if (!cm.somethingSelected()) { te.value = input.prevInput = " "; }
    input.contextMenuPending = rehide;
    display.selForContextMenu = cm.doc.sel;
    clearTimeout(display.detectingSelectAll);

    // Select-all will be greyed out if there's nothing to select, so
    // this adds a zero-width space so that we can later check whether
    // it got selected.
    function prepareSelectAllHack() {
      if (te.selectionStart != null) {
        var selected = cm.somethingSelected();
        var extval = "\u200b" + (selected ? te.value : "");
        te.value = "\u21da"; // Used to catch context-menu undo
        te.value = extval;
        input.prevInput = selected ? "" : "\u200b";
        te.selectionStart = 1; te.selectionEnd = extval.length;
        // Re-set this, in case some other handler touched the
        // selection in the meantime.
        display.selForContextMenu = cm.doc.sel;
      }
    }
    function rehide() {
      if (input.contextMenuPending != rehide) { return }
      input.contextMenuPending = false;
      input.wrapper.style.cssText = oldWrapperCSS;
      te.style.cssText = oldCSS;
      if (ie && ie_version < 9) { display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); }

      // Try to detect the user choosing select-all
      if (te.selectionStart != null) {
        if (!ie || (ie && ie_version < 9)) { prepareSelectAllHack(); }
        var i = 0, poll = function () {
          if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
              te.selectionEnd > 0 && input.prevInput == "\u200b") {
            operation(cm, selectAll)(cm);
          } else if (i++ < 10) {
            display.detectingSelectAll = setTimeout(poll, 500);
          } else {
            display.selForContextMenu = null;
            display.input.reset();
          }
        };
        display.detectingSelectAll = setTimeout(poll, 200);
      }
    }

    if (ie && ie_version >= 9) { prepareSelectAllHack(); }
    if (captureRightClick) {
      e_stop(e);
      var mouseup = function () {
        off(window, "mouseup", mouseup);
        setTimeout(rehide, 20);
      };
      on(window, "mouseup", mouseup);
    } else {
      setTimeout(rehide, 50);
    }
  };

  TextareaInput.prototype.readOnlyChanged = function (val) {
    if (!val) { this.reset(); }
    this.textarea.disabled = val == "nocursor";
    this.textarea.readOnly = !!val;
  };

  TextareaInput.prototype.setUneditable = function () {};

  TextareaInput.prototype.needsContentAttribute = false;

  function fromTextArea(textarea, options) {
    options = options ? copyObj(options) : {};
    options.value = textarea.value;
    if (!options.tabindex && textarea.tabIndex)
      { options.tabindex = textarea.tabIndex; }
    if (!options.placeholder && textarea.placeholder)
      { options.placeholder = textarea.placeholder; }
    // Set autofocus to true if this textarea is focused, or if it has
    // autofocus and no other element is focused.
    if (options.autofocus == null) {
      var hasFocus = activeElt(textarea.ownerDocument);
      options.autofocus = hasFocus == textarea ||
        textarea.getAttribute("autofocus") != null && hasFocus == document.body;
    }

    function save() {textarea.value = cm.getValue();}

    var realSubmit;
    if (textarea.form) {
      on(textarea.form, "submit", save);
      // Deplorable hack to make the submit method do the right thing.
      if (!options.leaveSubmitMethodAlone) {
        var form = textarea.form;
        realSubmit = form.submit;
        try {
          var wrappedSubmit = form.submit = function () {
            save();
            form.submit = realSubmit;
            form.submit();
            form.submit = wrappedSubmit;
          };
        } catch(e) {}
      }
    }

    options.finishInit = function (cm) {
      cm.save = save;
      cm.getTextArea = function () { return textarea; };
      cm.toTextArea = function () {
        cm.toTextArea = isNaN; // Prevent this from being ran twice
        save();
        textarea.parentNode.removeChild(cm.getWrapperElement());
        textarea.style.display = "";
        if (textarea.form) {
          off(textarea.form, "submit", save);
          if (!options.leaveSubmitMethodAlone && typeof textarea.form.submit == "function")
            { textarea.form.submit = realSubmit; }
        }
      };
    };

    textarea.style.display = "none";
    var cm = CodeMirror(function (node) { return textarea.parentNode.insertBefore(node, textarea.nextSibling); },
      options);
    return cm
  }

  function addLegacyProps(CodeMirror) {
    CodeMirror.off = off;
    CodeMirror.on = on;
    CodeMirror.wheelEventPixels = wheelEventPixels;
    CodeMirror.Doc = Doc;
    CodeMirror.splitLines = splitLinesAuto;
    CodeMirror.countColumn = countColumn;
    CodeMirror.findColumn = findColumn;
    CodeMirror.isWordChar = isWordCharBasic;
    CodeMirror.Pass = Pass;
    CodeMirror.signal = signal;
    CodeMirror.Line = Line;
    CodeMirror.changeEnd = changeEnd;
    CodeMirror.scrollbarModel = scrollbarModel;
    CodeMirror.Pos = Pos;
    CodeMirror.cmpPos = cmp;
    CodeMirror.modes = modes;
    CodeMirror.mimeModes = mimeModes;
    CodeMirror.resolveMode = resolveMode;
    CodeMirror.getMode = getMode;
    CodeMirror.modeExtensions = modeExtensions;
    CodeMirror.extendMode = extendMode;
    CodeMirror.copyState = copyState;
    CodeMirror.startState = startState;
    CodeMirror.innerMode = innerMode;
    CodeMirror.commands = commands;
    CodeMirror.keyMap = keyMap;
    CodeMirror.keyName = keyName;
    CodeMirror.isModifierKey = isModifierKey;
    CodeMirror.lookupKey = lookupKey;
    CodeMirror.normalizeKeyMap = normalizeKeyMap;
    CodeMirror.StringStream = StringStream;
    CodeMirror.SharedTextMarker = SharedTextMarker;
    CodeMirror.TextMarker = TextMarker;
    CodeMirror.LineWidget = LineWidget;
    CodeMirror.e_preventDefault = e_preventDefault;
    CodeMirror.e_stopPropagation = e_stopPropagation;
    CodeMirror.e_stop = e_stop;
    CodeMirror.addClass = addClass;
    CodeMirror.contains = contains;
    CodeMirror.rmClass = rmClass;
    CodeMirror.keyNames = keyNames;
  }

  // EDITOR CONSTRUCTOR

  defineOptions(CodeMirror);

  addEditorMethods(CodeMirror);

  // Set up methods on CodeMirror's prototype to redirect to the editor's document.
  var dontDelegate = "iter insert remove copy getEditor constructor".split(" ");
  for (var prop in Doc.prototype) { if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
    { CodeMirror.prototype[prop] = (function(method) {
      return function() {return method.apply(this.doc, arguments)}
    })(Doc.prototype[prop]); } }

  eventMixin(Doc);
  CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput};

  // Extra arguments are stored as the mode's dependencies, which is
  // used by (legacy) mechanisms like loadmode.js to automatically
  // load a mode. (Preferred mechanism is the require/define calls.)
  CodeMirror.defineMode = function(name/*, mode, …*/) {
    if (!CodeMirror.defaults.mode && name != "null") { CodeMirror.defaults.mode = name; }
    defineMode.apply(this, arguments);
  };

  CodeMirror.defineMIME = defineMIME;

  // Minimal default mode.
  CodeMirror.defineMode("null", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); });
  CodeMirror.defineMIME("text/plain", "null");

  // EXTENSIONS

  CodeMirror.defineExtension = function (name, func) {
    CodeMirror.prototype[name] = func;
  };
  CodeMirror.defineDocExtension = function (name, func) {
    Doc.prototype[name] = func;
  };

  CodeMirror.fromTextArea = fromTextArea;

  addLegacyProps(CodeMirror);

  CodeMirror.version = "5.65.15";

  return CodeMirror;

})));


/***/ }),

/***/ 629:
/***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {

// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/5/LICENSE

(function(mod) {
  if (true) // CommonJS
    mod(__webpack_require__(631));
  else {}
})(function(CodeMirror) {
"use strict";

CodeMirror.defineMode("css", function(config, parserConfig) {
  var inline = parserConfig.inline
  if (!parserConfig.propertyKeywords) parserConfig = CodeMirror.resolveMode("text/css");

  var indentUnit = config.indentUnit,
      tokenHooks = parserConfig.tokenHooks,
      documentTypes = parserConfig.documentTypes || {},
      mediaTypes = parserConfig.mediaTypes || {},
      mediaFeatures = parserConfig.mediaFeatures || {},
      mediaValueKeywords = parserConfig.mediaValueKeywords || {},
      propertyKeywords = parserConfig.propertyKeywords || {},
      nonStandardPropertyKeywords = parserConfig.nonStandardPropertyKeywords || {},
      fontProperties = parserConfig.fontProperties || {},
      counterDescriptors = parserConfig.counterDescriptors || {},
      colorKeywords = parserConfig.colorKeywords || {},
      valueKeywords = parserConfig.valueKeywords || {},
      allowNested = parserConfig.allowNested,
      lineComment = parserConfig.lineComment,
      supportsAtComponent = parserConfig.supportsAtComponent === true,
      highlightNonStandardPropertyKeywords = config.highlightNonStandardPropertyKeywords !== false;

  var type, override;
  function ret(style, tp) { type = tp; return style; }

  // Tokenizers

  function tokenBase(stream, state) {
    var ch = stream.next();
    if (tokenHooks[ch]) {
      var result = tokenHooks[ch](stream, state);
      if (result !== false) return result;
    }
    if (ch == "@") {
      stream.eatWhile(/[\w\\\-]/);
      return ret("def", stream.current());
    } else if (ch == "=" || (ch == "~" || ch == "|") && stream.eat("=")) {
      return ret(null, "compare");
    } else if (ch == "\"" || ch == "'") {
      state.tokenize = tokenString(ch);
      return state.tokenize(stream, state);
    } else if (ch == "#") {
      stream.eatWhile(/[\w\\\-]/);
      return ret("atom", "hash");
    } else if (ch == "!") {
      stream.match(/^\s*\w*/);
      return ret("keyword", "important");
    } else if (/\d/.test(ch) || ch == "." && stream.eat(/\d/)) {
      stream.eatWhile(/[\w.%]/);
      return ret("number", "unit");
    } else if (ch === "-") {
      if (/[\d.]/.test(stream.peek())) {
        stream.eatWhile(/[\w.%]/);
        return ret("number", "unit");
      } else if (stream.match(/^-[\w\\\-]*/)) {
        stream.eatWhile(/[\w\\\-]/);
        if (stream.match(/^\s*:/, false))
          return ret("variable-2", "variable-definition");
        return ret("variable-2", "variable");
      } else if (stream.match(/^\w+-/)) {
        return ret("meta", "meta");
      }
    } else if (/[,+>*\/]/.test(ch)) {
      return ret(null, "select-op");
    } else if (ch == "." && stream.match(/^-?[_a-z][_a-z0-9-]*/i)) {
      return ret("qualifier", "qualifier");
    } else if (/[:;{}\[\]\(\)]/.test(ch)) {
      return ret(null, ch);
    } else if (stream.match(/^[\w-.]+(?=\()/)) {
      if (/^(url(-prefix)?|domain|regexp)$/i.test(stream.current())) {
        state.tokenize = tokenParenthesized;
      }
      return ret("variable callee", "variable");
    } else if (/[\w\\\-]/.test(ch)) {
      stream.eatWhile(/[\w\\\-]/);
      return ret("property", "word");
    } else {
      return ret(null, null);
    }
  }

  function tokenString(quote) {
    return function(stream, state) {
      var escaped = false, ch;
      while ((ch = stream.next()) != null) {
        if (ch == quote && !escaped) {
          if (quote == ")") stream.backUp(1);
          break;
        }
        escaped = !escaped && ch == "\\";
      }
      if (ch == quote || !escaped && quote != ")") state.tokenize = null;
      return ret("string", "string");
    };
  }

  function tokenParenthesized(stream, state) {
    stream.next(); // Must be '('
    if (!stream.match(/^\s*[\"\')]/, false))
      state.tokenize = tokenString(")");
    else
      state.tokenize = null;
    return ret(null, "(");
  }

  // Context management

  function Context(type, indent, prev) {
    this.type = type;
    this.indent = indent;
    this.prev = prev;
  }

  function pushContext(state, stream, type, indent) {
    state.context = new Context(type, stream.indentation() + (indent === false ? 0 : indentUnit), state.context);
    return type;
  }

  function popContext(state) {
    if (state.context.prev)
      state.context = state.context.prev;
    return state.context.type;
  }

  function pass(type, stream, state) {
    return states[state.context.type](type, stream, state);
  }
  function popAndPass(type, stream, state, n) {
    for (var i = n || 1; i > 0; i--)
      state.context = state.context.prev;
    return pass(type, stream, state);
  }

  // Parser

  function wordAsValue(stream) {
    var word = stream.current().toLowerCase();
    if (valueKeywords.hasOwnProperty(word))
      override = "atom";
    else if (colorKeywords.hasOwnProperty(word))
      override = "keyword";
    else
      override = "variable";
  }

  var states = {};

  states.top = function(type, stream, state) {
    if (type == "{") {
      return pushContext(state, stream, "block");
    } else if (type == "}" && state.context.prev) {
      return popContext(state);
    } else if (supportsAtComponent && /@component/i.test(type)) {
      return pushContext(state, stream, "atComponentBlock");
    } else if (/^@(-moz-)?document$/i.test(type)) {
      return pushContext(state, stream, "documentTypes");
    } else if (/^@(media|supports|(-moz-)?document|import)$/i.test(type)) {
      return pushContext(state, stream, "atBlock");
    } else if (/^@(font-face|counter-style)/i.test(type)) {
      state.stateArg = type;
      return "restricted_atBlock_before";
    } else if (/^@(-(moz|ms|o|webkit)-)?keyframes$/i.test(type)) {
      return "keyframes";
    } else if (type && type.charAt(0) == "@") {
      return pushContext(state, stream, "at");
    } else if (type == "hash") {
      override = "builtin";
    } else if (type == "word") {
      override = "tag";
    } else if (type == "variable-definition") {
      return "maybeprop";
    } else if (type == "interpolation") {
      return pushContext(state, stream, "interpolation");
    } else if (type == ":") {
      return "pseudo";
    } else if (allowNested && type == "(") {
      return pushContext(state, stream, "parens");
    }
    return state.context.type;
  };

  states.block = function(type, stream, state) {
    if (type == "word") {
      var word = stream.current().toLowerCase();
      if (propertyKeywords.hasOwnProperty(word)) {
        override = "property";
        return "maybeprop";
      } else if (nonStandardPropertyKeywords.hasOwnProperty(word)) {
        override = highlightNonStandardPropertyKeywords ? "string-2" : "property";
        return "maybeprop";
      } else if (allowNested) {
        override = stream.match(/^\s*:(?:\s|$)/, false) ? "property" : "tag";
        return "block";
      } else {
        override += " error";
        return "maybeprop";
      }
    } else if (type == "meta") {
      return "block";
    } else if (!allowNested && (type == "hash" || type == "qualifier")) {
      override = "error";
      return "block";
    } else {
      return states.top(type, stream, state);
    }
  };

  states.maybeprop = function(type, stream, state) {
    if (type == ":") return pushContext(state, stream, "prop");
    return pass(type, stream, state);
  };

  states.prop = function(type, stream, state) {
    if (type == ";") return popContext(state);
    if (type == "{" && allowNested) return pushContext(state, stream, "propBlock");
    if (type == "}" || type == "{") return popAndPass(type, stream, state);
    if (type == "(") return pushContext(state, stream, "parens");

    if (type == "hash" && !/^#([0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/.test(stream.current())) {
      override += " error";
    } else if (type == "word") {
      wordAsValue(stream);
    } else if (type == "interpolation") {
      return pushContext(state, stream, "interpolation");
    }
    return "prop";
  };

  states.propBlock = function(type, _stream, state) {
    if (type == "}") return popContext(state);
    if (type == "word") { override = "property"; return "maybeprop"; }
    return state.context.type;
  };

  states.parens = function(type, stream, state) {
    if (type == "{" || type == "}") return popAndPass(type, stream, state);
    if (type == ")") return popContext(state);
    if (type == "(") return pushContext(state, stream, "parens");
    if (type == "interpolation") return pushContext(state, stream, "interpolation");
    if (type == "word") wordAsValue(stream);
    return "parens";
  };

  states.pseudo = function(type, stream, state) {
    if (type == "meta") return "pseudo";

    if (type == "word") {
      override = "variable-3";
      return state.context.type;
    }
    return pass(type, stream, state);
  };

  states.documentTypes = function(type, stream, state) {
    if (type == "word" && documentTypes.hasOwnProperty(stream.current())) {
      override = "tag";
      return state.context.type;
    } else {
      return states.atBlock(type, stream, state);
    }
  };

  states.atBlock = function(type, stream, state) {
    if (type == "(") return pushContext(state, stream, "atBlock_parens");
    if (type == "}" || type == ";") return popAndPass(type, stream, state);
    if (type == "{") return popContext(state) && pushContext(state, stream, allowNested ? "block" : "top");

    if (type == "interpolation") return pushContext(state, stream, "interpolation");

    if (type == "word") {
      var word = stream.current().toLowerCase();
      if (word == "only" || word == "not" || word == "and" || word == "or")
        override = "keyword";
      else if (mediaTypes.hasOwnProperty(word))
        override = "attribute";
      else if (mediaFeatures.hasOwnProperty(word))
        override = "property";
      else if (mediaValueKeywords.hasOwnProperty(word))
        override = "keyword";
      else if (propertyKeywords.hasOwnProperty(word))
        override = "property";
      else if (nonStandardPropertyKeywords.hasOwnProperty(word))
        override = highlightNonStandardPropertyKeywords ? "string-2" : "property";
      else if (valueKeywords.hasOwnProperty(word))
        override = "atom";
      else if (colorKeywords.hasOwnProperty(word))
        override = "keyword";
      else
        override = "error";
    }
    return state.context.type;
  };

  states.atComponentBlock = function(type, stream, state) {
    if (type == "}")
      return popAndPass(type, stream, state);
    if (type == "{")
      return popContext(state) && pushContext(state, stream, allowNested ? "block" : "top", false);
    if (type == "word")
      override = "error";
    return state.context.type;
  };

  states.atBlock_parens = function(type, stream, state) {
    if (type == ")") return popContext(state);
    if (type == "{" || type == "}") return popAndPass(type, stream, state, 2);
    return states.atBlock(type, stream, state);
  };

  states.restricted_atBlock_before = function(type, stream, state) {
    if (type == "{")
      return pushContext(state, stream, "restricted_atBlock");
    if (type == "word" && state.stateArg == "@counter-style") {
      override = "variable";
      return "restricted_atBlock_before";
    }
    return pass(type, stream, state);
  };

  states.restricted_atBlock = function(type, stream, state) {
    if (type == "}") {
      state.stateArg = null;
      return popContext(state);
    }
    if (type == "word") {
      if ((state.stateArg == "@font-face" && !fontProperties.hasOwnProperty(stream.current().toLowerCase())) ||
          (state.stateArg == "@counter-style" && !counterDescriptors.hasOwnProperty(stream.current().toLowerCase())))
        override = "error";
      else
        override = "property";
      return "maybeprop";
    }
    return "restricted_atBlock";
  };

  states.keyframes = function(type, stream, state) {
    if (type == "word") { override = "variable"; return "keyframes"; }
    if (type == "{") return pushContext(state, stream, "top");
    return pass(type, stream, state);
  };

  states.at = function(type, stream, state) {
    if (type == ";") return popContext(state);
    if (type == "{" || type == "}") return popAndPass(type, stream, state);
    if (type == "word") override = "tag";
    else if (type == "hash") override = "builtin";
    return "at";
  };

  states.interpolation = function(type, stream, state) {
    if (type == "}") return popContext(state);
    if (type == "{" || type == ";") return popAndPass(type, stream, state);
    if (type == "word") override = "variable";
    else if (type != "variable" && type != "(" && type != ")") override = "error";
    return "interpolation";
  };

  return {
    startState: function(base) {
      return {tokenize: null,
              state: inline ? "block" : "top",
              stateArg: null,
              context: new Context(inline ? "block" : "top", base || 0, null)};
    },

    token: function(stream, state) {
      if (!state.tokenize && stream.eatSpace()) return null;
      var style = (state.tokenize || tokenBase)(stream, state);
      if (style && typeof style == "object") {
        type = style[1];
        style = style[0];
      }
      override = style;
      if (type != "comment")
        state.state = states[state.state](type, stream, state);
      return override;
    },

    indent: function(state, textAfter) {
      var cx = state.context, ch = textAfter && textAfter.charAt(0);
      var indent = cx.indent;
      if (cx.type == "prop" && (ch == "}" || ch == ")")) cx = cx.prev;
      if (cx.prev) {
        if (ch == "}" && (cx.type == "block" || cx.type == "top" ||
                          cx.type == "interpolation" || cx.type == "restricted_atBlock")) {
          // Resume indentation from parent context.
          cx = cx.prev;
          indent = cx.indent;
        } else if (ch == ")" && (cx.type == "parens" || cx.type == "atBlock_parens") ||
            ch == "{" && (cx.type == "at" || cx.type == "atBlock")) {
          // Dedent relative to current context.
          indent = Math.max(0, cx.indent - indentUnit);
        }
      }
      return indent;
    },

    electricChars: "}",
    blockCommentStart: "/*",
    blockCommentEnd: "*/",
    blockCommentContinue: " * ",
    lineComment: lineComment,
    fold: "brace"
  };
});

  function keySet(array) {
    var keys = {};
    for (var i = 0; i < array.length; ++i) {
      keys[array[i].toLowerCase()] = true;
    }
    return keys;
  }

  var documentTypes_ = [
    "domain", "regexp", "url", "url-prefix"
  ], documentTypes = keySet(documentTypes_);

  var mediaTypes_ = [
    "all", "aural", "braille", "handheld", "print", "projection", "screen",
    "tty", "tv", "embossed"
  ], mediaTypes = keySet(mediaTypes_);

  var mediaFeatures_ = [
    "width", "min-width", "max-width", "height", "min-height", "max-height",
    "device-width", "min-device-width", "max-device-width", "device-height",
    "min-device-height", "max-device-height", "aspect-ratio",
    "min-aspect-ratio", "max-aspect-ratio", "device-aspect-ratio",
    "min-device-aspect-ratio", "max-device-aspect-ratio", "color", "min-color",
    "max-color", "color-index", "min-color-index", "max-color-index",
    "monochrome", "min-monochrome", "max-monochrome", "resolution",
    "min-resolution", "max-resolution", "scan", "grid", "orientation",
    "device-pixel-ratio", "min-device-pixel-ratio", "max-device-pixel-ratio",
    "pointer", "any-pointer", "hover", "any-hover", "prefers-color-scheme",
    "dynamic-range", "video-dynamic-range"
  ], mediaFeatures = keySet(mediaFeatures_);

  var mediaValueKeywords_ = [
    "landscape", "portrait", "none", "coarse", "fine", "on-demand", "hover",
    "interlace", "progressive",
    "dark", "light",
    "standard", "high"
  ], mediaValueKeywords = keySet(mediaValueKeywords_);

  var propertyKeywords_ = [
    "align-content", "align-items", "align-self", "alignment-adjust",
    "alignment-baseline", "all", "anchor-point", "animation", "animation-delay",
    "animation-direction", "animation-duration", "animation-fill-mode",
    "animation-iteration-count", "animation-name", "animation-play-state",
    "animation-timing-function", "appearance", "azimuth", "backdrop-filter",
    "backface-visibility", "background", "background-attachment",
    "background-blend-mode", "background-clip", "background-color",
    "background-image", "background-origin", "background-position",
    "background-position-x", "background-position-y", "background-repeat",
    "background-size", "baseline-shift", "binding", "bleed", "block-size",
    "bookmark-label", "bookmark-level", "bookmark-state", "bookmark-target",
    "border", "border-bottom", "border-bottom-color", "border-bottom-left-radius",
    "border-bottom-right-radius", "border-bottom-style", "border-bottom-width",
    "border-collapse", "border-color", "border-image", "border-image-outset",
    "border-image-repeat", "border-image-slice", "border-image-source",
    "border-image-width", "border-left", "border-left-color", "border-left-style",
    "border-left-width", "border-radius", "border-right", "border-right-color",
    "border-right-style", "border-right-width", "border-spacing", "border-style",
    "border-top", "border-top-color", "border-top-left-radius",
    "border-top-right-radius", "border-top-style", "border-top-width",
    "border-width", "bottom", "box-decoration-break", "box-shadow", "box-sizing",
    "break-after", "break-before", "break-inside", "caption-side", "caret-color",
    "clear", "clip", "color", "color-profile", "column-count", "column-fill",
    "column-gap", "column-rule", "column-rule-color", "column-rule-style",
    "column-rule-width", "column-span", "column-width", "columns", "contain",
    "content", "counter-increment", "counter-reset", "crop", "cue", "cue-after",
    "cue-before", "cursor", "direction", "display", "dominant-baseline",
    "drop-initial-after-adjust", "drop-initial-after-align",
    "drop-initial-before-adjust", "drop-initial-before-align", "drop-initial-size",
    "drop-initial-value", "elevation", "empty-cells", "fit", "fit-content", "fit-position",
    "flex", "flex-basis", "flex-direction", "flex-flow", "flex-grow",
    "flex-shrink", "flex-wrap", "float", "float-offset", "flow-from", "flow-into",
    "font", "font-family", "font-feature-settings", "font-kerning",
    "font-language-override", "font-optical-sizing", "font-size",
    "font-size-adjust", "font-stretch", "font-style", "font-synthesis",
    "font-variant", "font-variant-alternates", "font-variant-caps",
    "font-variant-east-asian", "font-variant-ligatures", "font-variant-numeric",
    "font-variant-position", "font-variation-settings", "font-weight", "gap",
    "grid", "grid-area", "grid-auto-columns", "grid-auto-flow", "grid-auto-rows",
    "grid-column", "grid-column-end", "grid-column-gap", "grid-column-start",
    "grid-gap", "grid-row", "grid-row-end", "grid-row-gap", "grid-row-start",
    "grid-template", "grid-template-areas", "grid-template-columns",
    "grid-template-rows", "hanging-punctuation", "height", "hyphens", "icon",
    "image-orientation", "image-rendering", "image-resolution", "inline-box-align",
    "inset", "inset-block", "inset-block-end", "inset-block-start", "inset-inline",
    "inset-inline-end", "inset-inline-start", "isolation", "justify-content",
    "justify-items", "justify-self", "left", "letter-spacing", "line-break",
    "line-height", "line-height-step", "line-stacking", "line-stacking-ruby",
    "line-stacking-shift", "line-stacking-strategy", "list-style",
    "list-style-image", "list-style-position", "list-style-type", "margin",
    "margin-bottom", "margin-left", "margin-right", "margin-top", "marks",
    "marquee-direction", "marquee-loop", "marquee-play-count", "marquee-speed",
    "marquee-style", "mask-clip", "mask-composite", "mask-image", "mask-mode",
    "mask-origin", "mask-position", "mask-repeat", "mask-size","mask-type",
    "max-block-size", "max-height", "max-inline-size",
    "max-width", "min-block-size", "min-height", "min-inline-size", "min-width",
    "mix-blend-mode", "move-to", "nav-down", "nav-index", "nav-left", "nav-right",
    "nav-up", "object-fit", "object-position", "offset", "offset-anchor",
    "offset-distance", "offset-path", "offset-position", "offset-rotate",
    "opacity", "order", "orphans", "outline", "outline-color", "outline-offset",
    "outline-style", "outline-width", "overflow", "overflow-style",
    "overflow-wrap", "overflow-x", "overflow-y", "padding", "padding-bottom",
    "padding-left", "padding-right", "padding-top", "page", "page-break-after",
    "page-break-before", "page-break-inside", "page-policy", "pause",
    "pause-after", "pause-before", "perspective", "perspective-origin", "pitch",
    "pitch-range", "place-content", "place-items", "place-self", "play-during",
    "position", "presentation-level", "punctuation-trim", "quotes",
    "region-break-after", "region-break-before", "region-break-inside",
    "region-fragment", "rendering-intent", "resize", "rest", "rest-after",
    "rest-before", "richness", "right", "rotate", "rotation", "rotation-point",
    "row-gap", "ruby-align", "ruby-overhang", "ruby-position", "ruby-span",
    "scale", "scroll-behavior", "scroll-margin", "scroll-margin-block",
    "scroll-margin-block-end", "scroll-margin-block-start", "scroll-margin-bottom",
    "scroll-margin-inline", "scroll-margin-inline-end",
    "scroll-margin-inline-start", "scroll-margin-left", "scroll-margin-right",
    "scroll-margin-top", "scroll-padding", "scroll-padding-block",
    "scroll-padding-block-end", "scroll-padding-block-start",
    "scroll-padding-bottom", "scroll-padding-inline", "scroll-padding-inline-end",
    "scroll-padding-inline-start", "scroll-padding-left", "scroll-padding-right",
    "scroll-padding-top", "scroll-snap-align", "scroll-snap-type",
    "shape-image-threshold", "shape-inside", "shape-margin", "shape-outside",
    "size", "speak", "speak-as", "speak-header", "speak-numeral",
    "speak-punctuation", "speech-rate", "stress", "string-set", "tab-size",
    "table-layout", "target", "target-name", "target-new", "target-position",
    "text-align", "text-align-last", "text-combine-upright", "text-decoration",
    "text-decoration-color", "text-decoration-line", "text-decoration-skip",
    "text-decoration-skip-ink", "text-decoration-style", "text-emphasis",
    "text-emphasis-color", "text-emphasis-position", "text-emphasis-style",
    "text-height", "text-indent", "text-justify", "text-orientation",
    "text-outline", "text-overflow", "text-rendering", "text-shadow",
    "text-size-adjust", "text-space-collapse", "text-transform",
    "text-underline-position", "text-wrap", "top", "touch-action", "transform", "transform-origin",
    "transform-style", "transition", "transition-delay", "transition-duration",
    "transition-property", "transition-timing-function", "translate",
    "unicode-bidi", "user-select", "vertical-align", "visibility", "voice-balance",
    "voice-duration", "voice-family", "voice-pitch", "voice-range", "voice-rate",
    "voice-stress", "voice-volume", "volume", "white-space", "widows", "width",
    "will-change", "word-break", "word-spacing", "word-wrap", "writing-mode", "z-index",
    // SVG-specific
    "clip-path", "clip-rule", "mask", "enable-background", "filter", "flood-color",
    "flood-opacity", "lighting-color", "stop-color", "stop-opacity", "pointer-events",
    "color-interpolation", "color-interpolation-filters",
    "color-rendering", "fill", "fill-opacity", "fill-rule", "image-rendering",
    "marker", "marker-end", "marker-mid", "marker-start", "paint-order", "shape-rendering", "stroke",
    "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin",
    "stroke-miterlimit", "stroke-opacity", "stroke-width", "text-rendering",
    "baseline-shift", "dominant-baseline", "glyph-orientation-horizontal",
    "glyph-orientation-vertical", "text-anchor", "writing-mode",
  ], propertyKeywords = keySet(propertyKeywords_);

  var nonStandardPropertyKeywords_ = [
    "accent-color", "aspect-ratio", "border-block", "border-block-color", "border-block-end",
    "border-block-end-color", "border-block-end-style", "border-block-end-width",
    "border-block-start", "border-block-start-color", "border-block-start-style",
    "border-block-start-width", "border-block-style", "border-block-width",
    "border-inline", "border-inline-color", "border-inline-end",
    "border-inline-end-color", "border-inline-end-style",
    "border-inline-end-width", "border-inline-start", "border-inline-start-color",
    "border-inline-start-style", "border-inline-start-width",
    "border-inline-style", "border-inline-width", "content-visibility", "margin-block",
    "margin-block-end", "margin-block-start", "margin-inline", "margin-inline-end",
    "margin-inline-start", "overflow-anchor", "overscroll-behavior", "padding-block", "padding-block-end",
    "padding-block-start", "padding-inline", "padding-inline-end",
    "padding-inline-start", "scroll-snap-stop", "scrollbar-3d-light-color",
    "scrollbar-arrow-color", "scrollbar-base-color", "scrollbar-dark-shadow-color",
    "scrollbar-face-color", "scrollbar-highlight-color", "scrollbar-shadow-color",
    "scrollbar-track-color", "searchfield-cancel-button", "searchfield-decoration",
    "searchfield-results-button", "searchfield-results-decoration", "shape-inside", "zoom"
  ], nonStandardPropertyKeywords = keySet(nonStandardPropertyKeywords_);

  var fontProperties_ = [
    "font-display", "font-family", "src", "unicode-range", "font-variant",
     "font-feature-settings", "font-stretch", "font-weight", "font-style"
  ], fontProperties = keySet(fontProperties_);

  var counterDescriptors_ = [
    "additive-symbols", "fallback", "negative", "pad", "prefix", "range",
    "speak-as", "suffix", "symbols", "system"
  ], counterDescriptors = keySet(counterDescriptors_);

  var colorKeywords_ = [
    "aliceblue", "antiquewhite", "aqua", "aquamarine", "azure", "beige",
    "bisque", "black", "blanchedalmond", "blue", "blueviolet", "brown",
    "burlywood", "cadetblue", "chartreuse", "chocolate", "coral", "cornflowerblue",
    "cornsilk", "crimson", "cyan", "darkblue", "darkcyan", "darkgoldenrod",
    "darkgray", "darkgreen", "darkgrey", "darkkhaki", "darkmagenta", "darkolivegreen",
    "darkorange", "darkorchid", "darkred", "darksalmon", "darkseagreen",
    "darkslateblue", "darkslategray", "darkslategrey", "darkturquoise", "darkviolet",
    "deeppink", "deepskyblue", "dimgray", "dimgrey", "dodgerblue", "firebrick",
    "floralwhite", "forestgreen", "fuchsia", "gainsboro", "ghostwhite",
    "gold", "goldenrod", "gray", "grey", "green", "greenyellow", "honeydew",
    "hotpink", "indianred", "indigo", "ivory", "khaki", "lavender",
    "lavenderblush", "lawngreen", "lemonchiffon", "lightblue", "lightcoral",
    "lightcyan", "lightgoldenrodyellow", "lightgray", "lightgreen", "lightgrey", "lightpink",
    "lightsalmon", "lightseagreen", "lightskyblue", "lightslategray", "lightslategrey",
    "lightsteelblue", "lightyellow", "lime", "limegreen", "linen", "magenta",
    "maroon", "mediumaquamarine", "mediumblue", "mediumorchid", "mediumpurple",
    "mediumseagreen", "mediumslateblue", "mediumspringgreen", "mediumturquoise",
    "mediumvioletred", "midnightblue", "mintcream", "mistyrose", "moccasin",
    "navajowhite", "navy", "oldlace", "olive", "olivedrab", "orange", "orangered",
    "orchid", "palegoldenrod", "palegreen", "paleturquoise", "palevioletred",
    "papayawhip", "peachpuff", "peru", "pink", "plum", "powderblue",
    "purple", "rebeccapurple", "red", "rosybrown", "royalblue", "saddlebrown",
    "salmon", "sandybrown", "seagreen", "seashell", "sienna", "silver", "skyblue",
    "slateblue", "slategray", "slategrey", "snow", "springgreen", "steelblue", "tan",
    "teal", "thistle", "tomato", "turquoise", "violet", "wheat", "white",
    "whitesmoke", "yellow", "yellowgreen"
  ], colorKeywords = keySet(colorKeywords_);

  var valueKeywords_ = [
    "above", "absolute", "activeborder", "additive", "activecaption", "afar",
    "after-white-space", "ahead", "alias", "all", "all-scroll", "alphabetic", "alternate",
    "always", "amharic", "amharic-abegede", "antialiased", "appworkspace",
    "arabic-indic", "armenian", "asterisks", "attr", "auto", "auto-flow", "avoid", "avoid-column", "avoid-page",
    "avoid-region", "axis-pan", "background", "backwards", "baseline", "below", "bidi-override", "binary",
    "bengali", "blink", "block", "block-axis", "blur", "bold", "bolder", "border", "border-box",
    "both", "bottom", "break", "break-all", "break-word", "brightness", "bullets", "button",
    "buttonface", "buttonhighlight", "buttonshadow", "buttontext", "calc", "cambodian",
    "capitalize", "caps-lock-indicator", "caption", "captiontext", "caret",
    "cell", "center", "checkbox", "circle", "cjk-decimal", "cjk-earthly-branch",
    "cjk-heavenly-stem", "cjk-ideographic", "clear", "clip", "close-quote",
    "col-resize", "collapse", "color", "color-burn", "color-dodge", "column", "column-reverse",
    "compact", "condensed", "conic-gradient", "contain", "content", "contents",
    "content-box", "context-menu", "continuous", "contrast", "copy", "counter", "counters", "cover", "crop",
    "cross", "crosshair", "cubic-bezier", "currentcolor", "cursive", "cyclic", "darken", "dashed", "decimal",
    "decimal-leading-zero", "default", "default-button", "dense", "destination-atop",
    "destination-in", "destination-out", "destination-over", "devanagari", "difference",
    "disc", "discard", "disclosure-closed", "disclosure-open", "document",
    "dot-dash", "dot-dot-dash",
    "dotted", "double", "down", "drop-shadow", "e-resize", "ease", "ease-in", "ease-in-out", "ease-out",
    "element", "ellipse", "ellipsis", "embed", "end", "ethiopic", "ethiopic-abegede",
    "ethiopic-abegede-am-et", "ethiopic-abegede-gez", "ethiopic-abegede-ti-er",
    "ethiopic-abegede-ti-et", "ethiopic-halehame-aa-er",
    "ethiopic-halehame-aa-et", "ethiopic-halehame-am-et",
    "ethiopic-halehame-gez", "ethiopic-halehame-om-et",
    "ethiopic-halehame-sid-et", "ethiopic-halehame-so-et",
    "ethiopic-halehame-ti-er", "ethiopic-halehame-ti-et", "ethiopic-halehame-tig",
    "ethiopic-numeric", "ew-resize", "exclusion", "expanded", "extends", "extra-condensed",
    "extra-expanded", "fantasy", "fast", "fill", "fill-box", "fixed", "flat", "flex", "flex-end", "flex-start", "footnotes",
    "forwards", "from", "geometricPrecision", "georgian", "grayscale", "graytext", "grid", "groove",
    "gujarati", "gurmukhi", "hand", "hangul", "hangul-consonant", "hard-light", "hebrew",
    "help", "hidden", "hide", "higher", "highlight", "highlighttext",
    "hiragana", "hiragana-iroha", "horizontal", "hsl", "hsla", "hue", "hue-rotate", "icon", "ignore",
    "inactiveborder", "inactivecaption", "inactivecaptiontext", "infinite",
    "infobackground", "infotext", "inherit", "initial", "inline", "inline-axis",
    "inline-block", "inline-flex", "inline-grid", "inline-table", "inset", "inside", "intrinsic", "invert",
    "italic", "japanese-formal", "japanese-informal", "justify", "kannada",
    "katakana", "katakana-iroha", "keep-all", "khmer",
    "korean-hangul-formal", "korean-hanja-formal", "korean-hanja-informal",
    "landscape", "lao", "large", "larger", "left", "level", "lighter", "lighten",
    "line-through", "linear", "linear-gradient", "lines", "list-item", "listbox", "listitem",
    "local", "logical", "loud", "lower", "lower-alpha", "lower-armenian",
    "lower-greek", "lower-hexadecimal", "lower-latin", "lower-norwegian",
    "lower-roman", "lowercase", "ltr", "luminosity", "malayalam", "manipulation", "match", "matrix", "matrix3d",
    "media-play-button", "media-slider", "media-sliderthumb",
    "media-volume-slider", "media-volume-sliderthumb", "medium",
    "menu", "menulist", "menulist-button",
    "menutext", "message-box", "middle", "min-intrinsic",
    "mix", "mongolian", "monospace", "move", "multiple", "multiple_mask_images", "multiply", "myanmar", "n-resize",
    "narrower", "ne-resize", "nesw-resize", "no-close-quote", "no-drop",
    "no-open-quote", "no-repeat", "none", "normal", "not-allowed", "nowrap",
    "ns-resize", "numbers", "numeric", "nw-resize", "nwse-resize", "oblique", "octal", "opacity", "open-quote",
    "optimizeLegibility", "optimizeSpeed", "oriya", "oromo", "outset",
    "outside", "outside-shape", "overlay", "overline", "padding", "padding-box",
    "painted", "page", "paused", "persian", "perspective", "pinch-zoom", "plus-darker", "plus-lighter",
    "pointer", "polygon", "portrait", "pre", "pre-line", "pre-wrap", "preserve-3d",
    "progress", "push-button", "radial-gradient", "radio", "read-only",
    "read-write", "read-write-plaintext-only", "rectangle", "region",
    "relative", "repeat", "repeating-linear-gradient", "repeating-radial-gradient",
    "repeating-conic-gradient", "repeat-x", "repeat-y", "reset", "reverse",
    "rgb", "rgba", "ridge", "right", "rotate", "rotate3d", "rotateX", "rotateY",
    "rotateZ", "round", "row", "row-resize", "row-reverse", "rtl", "run-in", "running",
    "s-resize", "sans-serif", "saturate", "saturation", "scale", "scale3d", "scaleX", "scaleY", "scaleZ", "screen",
    "scroll", "scrollbar", "scroll-position", "se-resize", "searchfield",
    "searchfield-cancel-button", "searchfield-decoration",
    "searchfield-results-button", "searchfield-results-decoration", "self-start", "self-end",
    "semi-condensed", "semi-expanded", "separate", "sepia", "serif", "show", "sidama",
    "simp-chinese-formal", "simp-chinese-informal", "single",
    "skew", "skewX", "skewY", "skip-white-space", "slide", "slider-horizontal",
    "slider-vertical", "sliderthumb-horizontal", "sliderthumb-vertical", "slow",
    "small", "small-caps", "small-caption", "smaller", "soft-light", "solid", "somali",
    "source-atop", "source-in", "source-out", "source-over", "space", "space-around", "space-between", "space-evenly", "spell-out", "square",
    "square-button", "start", "static", "status-bar", "stretch", "stroke", "stroke-box", "sub",
    "subpixel-antialiased", "svg_masks", "super", "sw-resize", "symbolic", "symbols", "system-ui", "table",
    "table-caption", "table-cell", "table-column", "table-column-group",
    "table-footer-group", "table-header-group", "table-row", "table-row-group",
    "tamil",
    "telugu", "text", "text-bottom", "text-top", "textarea", "textfield", "thai",
    "thick", "thin", "threeddarkshadow", "threedface", "threedhighlight",
    "threedlightshadow", "threedshadow", "tibetan", "tigre", "tigrinya-er",
    "tigrinya-er-abegede", "tigrinya-et", "tigrinya-et-abegede", "to", "top",
    "trad-chinese-formal", "trad-chinese-informal", "transform",
    "translate", "translate3d", "translateX", "translateY", "translateZ",
    "transparent", "ultra-condensed", "ultra-expanded", "underline", "unidirectional-pan", "unset", "up",
    "upper-alpha", "upper-armenian", "upper-greek", "upper-hexadecimal",
    "upper-latin", "upper-norwegian", "upper-roman", "uppercase", "urdu", "url",
    "var", "vertical", "vertical-text", "view-box", "visible", "visibleFill", "visiblePainted",
    "visibleStroke", "visual", "w-resize", "wait", "wave", "wider",
    "window", "windowframe", "windowtext", "words", "wrap", "wrap-reverse", "x-large", "x-small", "xor",
    "xx-large", "xx-small"
  ], valueKeywords = keySet(valueKeywords_);

  var allWords = documentTypes_.concat(mediaTypes_).concat(mediaFeatures_).concat(mediaValueKeywords_)
    .concat(propertyKeywords_).concat(nonStandardPropertyKeywords_).concat(colorKeywords_)
    .concat(valueKeywords_);
  CodeMirror.registerHelper("hintWords", "css", allWords);

  function tokenCComment(stream, state) {
    var maybeEnd = false, ch;
    while ((ch = stream.next()) != null) {
      if (maybeEnd && ch == "/") {
        state.tokenize = null;
        break;
      }
      maybeEnd = (ch == "*");
    }
    return ["comment", "comment"];
  }

  CodeMirror.defineMIME("text/css", {
    documentTypes: documentTypes,
    mediaTypes: mediaTypes,
    mediaFeatures: mediaFeatures,
    mediaValueKeywords: mediaValueKeywords,
    propertyKeywords: propertyKeywords,
    nonStandardPropertyKeywords: nonStandardPropertyKeywords,
    fontProperties: fontProperties,
    counterDescriptors: counterDescriptors,
    colorKeywords: colorKeywords,
    valueKeywords: valueKeywords,
    tokenHooks: {
      "/": function(stream, state) {
        if (!stream.eat("*")) return false;
        state.tokenize = tokenCComment;
        return tokenCComment(stream, state);
      }
    },
    name: "css"
  });

  CodeMirror.defineMIME("text/x-scss", {
    mediaTypes: mediaTypes,
    mediaFeatures: mediaFeatures,
    mediaValueKeywords: mediaValueKeywords,
    propertyKeywords: propertyKeywords,
    nonStandardPropertyKeywords: nonStandardPropertyKeywords,
    colorKeywords: colorKeywords,
    valueKeywords: valueKeywords,
    fontProperties: fontProperties,
    allowNested: true,
    lineComment: "//",
    tokenHooks: {
      "/": function(stream, state) {
        if (stream.eat("/")) {
          stream.skipToEnd();
          return ["comment", "comment"];
        } else if (stream.eat("*")) {
          state.tokenize = tokenCComment;
          return tokenCComment(stream, state);
        } else {
          return ["operator", "operator"];
        }
      },
      ":": function(stream) {
        if (stream.match(/^\s*\{/, false))
          return [null, null]
        return false;
      },
      "$": function(stream) {
        stream.match(/^[\w-]+/);
        if (stream.match(/^\s*:/, false))
          return ["variable-2", "variable-definition"];
        return ["variable-2", "variable"];
      },
      "#": function(stream) {
        if (!stream.eat("{")) return false;
        return [null, "interpolation"];
      }
    },
    name: "css",
    helperType: "scss"
  });

  CodeMirror.defineMIME("text/x-less", {
    mediaTypes: mediaTypes,
    mediaFeatures: mediaFeatures,
    mediaValueKeywords: mediaValueKeywords,
    propertyKeywords: propertyKeywords,
    nonStandardPropertyKeywords: nonStandardPropertyKeywords,
    colorKeywords: colorKeywords,
    valueKeywords: valueKeywords,
    fontProperties: fontProperties,
    allowNested: true,
    lineComment: "//",
    tokenHooks: {
      "/": function(stream, state) {
        if (stream.eat("/")) {
          stream.skipToEnd();
          return ["comment", "comment"];
        } else if (stream.eat("*")) {
          state.tokenize = tokenCComment;
          return tokenCComment(stream, state);
        } else {
          return ["operator", "operator"];
        }
      },
      "@": function(stream) {
        if (stream.eat("{")) return [null, "interpolation"];
        if (stream.match(/^(charset|document|font-face|import|(-(moz|ms|o|webkit)-)?keyframes|media|namespace|page|supports)\b/i, false)) return false;
        stream.eatWhile(/[\w\\\-]/);
        if (stream.match(/^\s*:/, false))
          return ["variable-2", "variable-definition"];
        return ["variable-2", "variable"];
      },
      "&": function() {
        return ["atom", "atom"];
      }
    },
    name: "css",
    helperType: "less"
  });

  CodeMirror.defineMIME("text/x-gss", {
    documentTypes: documentTypes,
    mediaTypes: mediaTypes,
    mediaFeatures: mediaFeatures,
    propertyKeywords: propertyKeywords,
    nonStandardPropertyKeywords: nonStandardPropertyKeywords,
    fontProperties: fontProperties,
    counterDescriptors: counterDescriptors,
    colorKeywords: colorKeywords,
    valueKeywords: valueKeywords,
    supportsAtComponent: true,
    tokenHooks: {
      "/": function(stream, state) {
        if (!stream.eat("*")) return false;
        state.tokenize = tokenCComment;
        return tokenCComment(stream, state);
      }
    },
    name: "css",
    helperType: "gss"
  });

});


/***/ }),

/***/ 531:
/***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {

// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/5/LICENSE

(function(mod) {
  if (true) // CommonJS
    mod(__webpack_require__(631), __webpack_require__(589), __webpack_require__(876), __webpack_require__(629));
  else {}
})(function(CodeMirror) {
  "use strict";

  var defaultTags = {
    script: [
      ["lang", /(javascript|babel)/i, "javascript"],
      ["type", /^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^module$|^$/i, "javascript"],
      ["type", /./, "text/plain"],
      [null, null, "javascript"]
    ],
    style:  [
      ["lang", /^css$/i, "css"],
      ["type", /^(text\/)?(x-)?(stylesheet|css)$/i, "css"],
      ["type", /./, "text/plain"],
      [null, null, "css"]
    ]
  };

  function maybeBackup(stream, pat, style) {
    var cur = stream.current(), close = cur.search(pat);
    if (close > -1) {
      stream.backUp(cur.length - close);
    } else if (cur.match(/<\/?$/)) {
      stream.backUp(cur.length);
      if (!stream.match(pat, false)) stream.match(cur);
    }
    return style;
  }

  var attrRegexpCache = {};
  function getAttrRegexp(attr) {
    var regexp = attrRegexpCache[attr];
    if (regexp) return regexp;
    return attrRegexpCache[attr] = new RegExp("\\s+" + attr + "\\s*=\\s*('|\")?([^'\"]+)('|\")?\\s*");
  }

  function getAttrValue(text, attr) {
    var match = text.match(getAttrRegexp(attr))
    return match ? /^\s*(.*?)\s*$/.exec(match[2])[1] : ""
  }

  function getTagRegexp(tagName, anchored) {
    return new RegExp((anchored ? "^" : "") + "<\/\\s*" + tagName + "\\s*>", "i");
  }

  function addTags(from, to) {
    for (var tag in from) {
      var dest = to[tag] || (to[tag] = []);
      var source = from[tag];
      for (var i = source.length - 1; i >= 0; i--)
        dest.unshift(source[i])
    }
  }

  function findMatchingMode(tagInfo, tagText) {
    for (var i = 0; i < tagInfo.length; i++) {
      var spec = tagInfo[i];
      if (!spec[0] || spec[1].test(getAttrValue(tagText, spec[0]))) return spec[2];
    }
  }

  CodeMirror.defineMode("htmlmixed", function (config, parserConfig) {
    var htmlMode = CodeMirror.getMode(config, {
      name: "xml",
      htmlMode: true,
      multilineTagIndentFactor: parserConfig.multilineTagIndentFactor,
      multilineTagIndentPastTag: parserConfig.multilineTagIndentPastTag,
      allowMissingTagName: parserConfig.allowMissingTagName,
    });

    var tags = {};
    var configTags = parserConfig && parserConfig.tags, configScript = parserConfig && parserConfig.scriptTypes;
    addTags(defaultTags, tags);
    if (configTags) addTags(configTags, tags);
    if (configScript) for (var i = configScript.length - 1; i >= 0; i--)
      tags.script.unshift(["type", configScript[i].matches, configScript[i].mode])

    function html(stream, state) {
      var style = htmlMode.token(stream, state.htmlState), tag = /\btag\b/.test(style), tagName
      if (tag && !/[<>\s\/]/.test(stream.current()) &&
          (tagName = state.htmlState.tagName && state.htmlState.tagName.toLowerCase()) &&
          tags.hasOwnProperty(tagName)) {
        state.inTag = tagName + " "
      } else if (state.inTag && tag && />$/.test(stream.current())) {
        var inTag = /^([\S]+) (.*)/.exec(state.inTag)
        state.inTag = null
        var modeSpec = stream.current() == ">" && findMatchingMode(tags[inTag[1]], inTag[2])
        var mode = CodeMirror.getMode(config, modeSpec)
        var endTagA = getTagRegexp(inTag[1], true), endTag = getTagRegexp(inTag[1], false);
        state.token = function (stream, state) {
          if (stream.match(endTagA, false)) {
            state.token = html;
            state.localState = state.localMode = null;
            return null;
          }
          return maybeBackup(stream, endTag, state.localMode.token(stream, state.localState));
        };
        state.localMode = mode;
        state.localState = CodeMirror.startState(mode, htmlMode.indent(state.htmlState, "", ""));
      } else if (state.inTag) {
        state.inTag += stream.current()
        if (stream.eol()) state.inTag += " "
      }
      return style;
    };

    return {
      startState: function () {
        var state = CodeMirror.startState(htmlMode);
        return {token: html, inTag: null, localMode: null, localState: null, htmlState: state};
      },

      copyState: function (state) {
        var local;
        if (state.localState) {
          local = CodeMirror.copyState(state.localMode, state.localState);
        }
        return {token: state.token, inTag: state.inTag,
                localMode: state.localMode, localState: local,
                htmlState: CodeMirror.copyState(htmlMode, state.htmlState)};
      },

      token: function (stream, state) {
        return state.token(stream, state);
      },

      indent: function (state, textAfter, line) {
        if (!state.localMode || /^\s*<\//.test(textAfter))
          return htmlMode.indent(state.htmlState, textAfter, line);
        else if (state.localMode.indent)
          return state.localMode.indent(state.localState, textAfter, line);
        else
          return CodeMirror.Pass;
      },

      innerMode: function (state) {
        return {state: state.localState || state.htmlState, mode: state.localMode || htmlMode};
      }
    };
  }, "xml", "javascript", "css");

  CodeMirror.defineMIME("text/html", "htmlmixed");
});


/***/ }),

/***/ 876:
/***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {

// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/5/LICENSE

(function(mod) {
  if (true) // CommonJS
    mod(__webpack_require__(631));
  else {}
})(function(CodeMirror) {
"use strict";

CodeMirror.defineMode("javascript", function(config, parserConfig) {
  var indentUnit = config.indentUnit;
  var statementIndent = parserConfig.statementIndent;
  var jsonldMode = parserConfig.jsonld;
  var jsonMode = parserConfig.json || jsonldMode;
  var trackScope = parserConfig.trackScope !== false
  var isTS = parserConfig.typescript;
  var wordRE = parserConfig.wordCharacters || /[\w$\xa1-\uffff]/;

  // Tokenizer

  var keywords = function(){
    function kw(type) {return {type: type, style: "keyword"};}
    var A = kw("keyword a"), B = kw("keyword b"), C = kw("keyword c"), D = kw("keyword d");
    var operator = kw("operator"), atom = {type: "atom", style: "atom"};

    return {
      "if": kw("if"), "while": A, "with": A, "else": B, "do": B, "try": B, "finally": B,
      "return": D, "break": D, "continue": D, "new": kw("new"), "delete": C, "void": C, "throw": C,
      "debugger": kw("debugger"), "var": kw("var"), "const": kw("var"), "let": kw("var"),
      "function": kw("function"), "catch": kw("catch"),
      "for": kw("for"), "switch": kw("switch"), "case": kw("case"), "default": kw("default"),
      "in": operator, "typeof": operator, "instanceof": operator,
      "true": atom, "false": atom, "null": atom, "undefined": atom, "NaN": atom, "Infinity": atom,
      "this": kw("this"), "class": kw("class"), "super": kw("atom"),
      "yield": C, "export": kw("export"), "import": kw("import"), "extends": C,
      "await": C
    };
  }();

  var isOperatorChar = /[+\-*&%=<>!?|~^@]/;
  var isJsonldKeyword = /^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/;

  function readRegexp(stream) {
    var escaped = false, next, inSet = false;
    while ((next = stream.next()) != null) {
      if (!escaped) {
        if (next == "/" && !inSet) return;
        if (next == "[") inSet = true;
        else if (inSet && next == "]") inSet = false;
      }
      escaped = !escaped && next == "\\";
    }
  }

  // Used as scratch variables to communicate multiple values without
  // consing up tons of objects.
  var type, content;
  function ret(tp, style, cont) {
    type = tp; content = cont;
    return style;
  }
  function tokenBase(stream, state) {
    var ch = stream.next();
    if (ch == '"' || ch == "'") {
      state.tokenize = tokenString(ch);
      return state.tokenize(stream, state);
    } else if (ch == "." && stream.match(/^\d[\d_]*(?:[eE][+\-]?[\d_]+)?/)) {
      return ret("number", "number");
    } else if (ch == "." && stream.match("..")) {
      return ret("spread", "meta");
    } else if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
      return ret(ch);
    } else if (ch == "=" && stream.eat(">")) {
      return ret("=>", "operator");
    } else if (ch == "0" && stream.match(/^(?:x[\dA-Fa-f_]+|o[0-7_]+|b[01_]+)n?/)) {
      return ret("number", "number");
    } else if (/\d/.test(ch)) {
      stream.match(/^[\d_]*(?:n|(?:\.[\d_]*)?(?:[eE][+\-]?[\d_]+)?)?/);
      return ret("number", "number");
    } else if (ch == "/") {
      if (stream.eat("*")) {
        state.tokenize = tokenComment;
        return tokenComment(stream, state);
      } else if (stream.eat("/")) {
        stream.skipToEnd();
        return ret("comment", "comment");
      } else if (expressionAllowed(stream, state, 1)) {
        readRegexp(stream);
        stream.match(/^\b(([gimyus])(?![gimyus]*\2))+\b/);
        return ret("regexp", "string-2");
      } else {
        stream.eat("=");
        return ret("operator", "operator", stream.current());
      }
    } else if (ch == "`") {
      state.tokenize = tokenQuasi;
      return tokenQuasi(stream, state);
    } else if (ch == "#" && stream.peek() == "!") {
      stream.skipToEnd();
      return ret("meta", "meta");
    } else if (ch == "#" && stream.eatWhile(wordRE)) {
      return ret("variable", "property")
    } else if (ch == "<" && stream.match("!--") ||
               (ch == "-" && stream.match("->") && !/\S/.test(stream.string.slice(0, stream.start)))) {
      stream.skipToEnd()
      return ret("comment", "comment")
    } else if (isOperatorChar.test(ch)) {
      if (ch != ">" || !state.lexical || state.lexical.type != ">") {
        if (stream.eat("=")) {
          if (ch == "!" || ch == "=") stream.eat("=")
        } else if (/[<>*+\-|&?]/.test(ch)) {
          stream.eat(ch)
          if (ch == ">") stream.eat(ch)
        }
      }
      if (ch == "?" && stream.eat(".")) return ret(".")
      return ret("operator", "operator", stream.current());
    } else if (wordRE.test(ch)) {
      stream.eatWhile(wordRE);
      var word = stream.current()
      if (state.lastType != ".") {
        if (keywords.propertyIsEnumerable(word)) {
          var kw = keywords[word]
          return ret(kw.type, kw.style, word)
        }
        if (word == "async" && stream.match(/^(\s|\/\*([^*]|\*(?!\/))*?\*\/)*[\[\(\w]/, false))
          return ret("async", "keyword", word)
      }
      return ret("variable", "variable", word)
    }
  }

  function tokenString(quote) {
    return function(stream, state) {
      var escaped = false, next;
      if (jsonldMode && stream.peek() == "@" && stream.match(isJsonldKeyword)){
        state.tokenize = tokenBase;
        return ret("jsonld-keyword", "meta");
      }
      while ((next = stream.next()) != null) {
        if (next == quote && !escaped) break;
        escaped = !escaped && next == "\\";
      }
      if (!escaped) state.tokenize = tokenBase;
      return ret("string", "string");
    };
  }

  function tokenComment(stream, state) {
    var maybeEnd = false, ch;
    while (ch = stream.next()) {
      if (ch == "/" && maybeEnd) {
        state.tokenize = tokenBase;
        break;
      }
      maybeEnd = (ch == "*");
    }
    return ret("comment", "comment");
  }

  function tokenQuasi(stream, state) {
    var escaped = false, next;
    while ((next = stream.next()) != null) {
      if (!escaped && (next == "`" || next == "$" && stream.eat("{"))) {
        state.tokenize = tokenBase;
        break;
      }
      escaped = !escaped && next == "\\";
    }
    return ret("quasi", "string-2", stream.current());
  }

  var brackets = "([{}])";
  // This is a crude lookahead trick to try and notice that we're
  // parsing the argument patterns for a fat-arrow function before we
  // actually hit the arrow token. It only works if the arrow is on
  // the same line as the arguments and there's no strange noise
  // (comments) in between. Fallback is to only notice when we hit the
  // arrow, and not declare the arguments as locals for the arrow
  // body.
  function findFatArrow(stream, state) {
    if (state.fatArrowAt) state.fatArrowAt = null;
    var arrow = stream.string.indexOf("=>", stream.start);
    if (arrow < 0) return;

    if (isTS) { // Try to skip TypeScript return type declarations after the arguments
      var m = /:\s*(?:\w+(?:<[^>]*>|\[\])?|\{[^}]*\})\s*$/.exec(stream.string.slice(stream.start, arrow))
      if (m) arrow = m.index
    }

    var depth = 0, sawSomething = false;
    for (var pos = arrow - 1; pos >= 0; --pos) {
      var ch = stream.string.charAt(pos);
      var bracket = brackets.indexOf(ch);
      if (bracket >= 0 && bracket < 3) {
        if (!depth) { ++pos; break; }
        if (--depth == 0) { if (ch == "(") sawSomething = true; break; }
      } else if (bracket >= 3 && bracket < 6) {
        ++depth;
      } else if (wordRE.test(ch)) {
        sawSomething = true;
      } else if (/["'\/`]/.test(ch)) {
        for (;; --pos) {
          if (pos == 0) return
          var next = stream.string.charAt(pos - 1)
          if (next == ch && stream.string.charAt(pos - 2) != "\\") { pos--; break }
        }
      } else if (sawSomething && !depth) {
        ++pos;
        break;
      }
    }
    if (sawSomething && !depth) state.fatArrowAt = pos;
  }

  // Parser

  var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true,
                     "regexp": true, "this": true, "import": true, "jsonld-keyword": true};

  function JSLexical(indented, column, type, align, prev, info) {
    this.indented = indented;
    this.column = column;
    this.type = type;
    this.prev = prev;
    this.info = info;
    if (align != null) this.align = align;
  }

  function inScope(state, varname) {
    if (!trackScope) return false
    for (var v = state.localVars; v; v = v.next)
      if (v.name == varname) return true;
    for (var cx = state.context; cx; cx = cx.prev) {
      for (var v = cx.vars; v; v = v.next)
        if (v.name == varname) return true;
    }
  }

  function parseJS(state, style, type, content, stream) {
    var cc = state.cc;
    // Communicate our context to the combinators.
    // (Less wasteful than consing up a hundred closures on every call.)
    cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc; cx.style = style;

    if (!state.lexical.hasOwnProperty("align"))
      state.lexical.align = true;

    while(true) {
      var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement;
      if (combinator(type, content)) {
        while(cc.length && cc[cc.length - 1].lex)
          cc.pop()();
        if (cx.marked) return cx.marked;
        if (type == "variable" && inScope(state, content)) return "variable-2";
        return style;
      }
    }
  }

  // Combinator utils

  var cx = {state: null, column: null, marked: null, cc: null};
  function pass() {
    for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]);
  }
  function cont() {
    pass.apply(null, arguments);
    return true;
  }
  function inList(name, list) {
    for (var v = list; v; v = v.next) if (v.name == name) return true
    return false;
  }
  function register(varname) {
    var state = cx.state;
    cx.marked = "def";
    if (!trackScope) return
    if (state.context) {
      if (state.lexical.info == "var" && state.context && state.context.block) {
        // FIXME function decls are also not block scoped
        var newContext = registerVarScoped(varname, state.context)
        if (newContext != null) {
          state.context = newContext
          return
        }
      } else if (!inList(varname, state.localVars)) {
        state.localVars = new Var(varname, state.localVars)
        return
      }
    }
    // Fall through means this is global
    if (parserConfig.globalVars && !inList(varname, state.globalVars))
      state.globalVars = new Var(varname, state.globalVars)
  }
  function registerVarScoped(varname, context) {
    if (!context) {
      return null
    } else if (context.block) {
      var inner = registerVarScoped(varname, context.prev)
      if (!inner) return null
      if (inner == context.prev) return context
      return new Context(inner, context.vars, true)
    } else if (inList(varname, context.vars)) {
      return context
    } else {
      return new Context(context.prev, new Var(varname, context.vars), false)
    }
  }

  function isModifier(name) {
    return name == "public" || name == "private" || name == "protected" || name == "abstract" || name == "readonly"
  }

  // Combinators

  function Context(prev, vars, block) { this.prev = prev; this.vars = vars; this.block = block }
  function Var(name, next) { this.name = name; this.next = next }

  var defaultVars = new Var("this", new Var("arguments", null))
  function pushcontext() {
    cx.state.context = new Context(cx.state.context, cx.state.localVars, false)
    cx.state.localVars = defaultVars
  }
  function pushblockcontext() {
    cx.state.context = new Context(cx.state.context, cx.state.localVars, true)
    cx.state.localVars = null
  }
  pushcontext.lex = pushblockcontext.lex = true
  function popcontext() {
    cx.state.localVars = cx.state.context.vars
    cx.state.context = cx.state.context.prev
  }
  popcontext.lex = true
  function pushlex(type, info) {
    var result = function() {
      var state = cx.state, indent = state.indented;
      if (state.lexical.type == "stat") indent = state.lexical.indented;
      else for (var outer = state.lexical; outer && outer.type == ")" && outer.align; outer = outer.prev)
        indent = outer.indented;
      state.lexical = new JSLexical(indent, cx.stream.column(), type, null, state.lexical, info);
    };
    result.lex = true;
    return result;
  }
  function poplex() {
    var state = cx.state;
    if (state.lexical.prev) {
      if (state.lexical.type == ")")
        state.indented = state.lexical.indented;
      state.lexical = state.lexical.prev;
    }
  }
  poplex.lex = true;

  function expect(wanted) {
    function exp(type) {
      if (type == wanted) return cont();
      else if (wanted == ";" || type == "}" || type == ")" || type == "]") return pass();
      else return cont(exp);
    };
    return exp;
  }

  function statement(type, value) {
    if (type == "var") return cont(pushlex("vardef", value), vardef, expect(";"), poplex);
    if (type == "keyword a") return cont(pushlex("form"), parenExpr, statement, poplex);
    if (type == "keyword b") return cont(pushlex("form"), statement, poplex);
    if (type == "keyword d") return cx.stream.match(/^\s*$/, false) ? cont() : cont(pushlex("stat"), maybeexpression, expect(";"), poplex);
    if (type == "debugger") return cont(expect(";"));
    if (type == "{") return cont(pushlex("}"), pushblockcontext, block, poplex, popcontext);
    if (type == ";") return cont();
    if (type == "if") {
      if (cx.state.lexical.info == "else" && cx.state.cc[cx.state.cc.length - 1] == poplex)
        cx.state.cc.pop()();
      return cont(pushlex("form"), parenExpr, statement, poplex, maybeelse);
    }
    if (type == "function") return cont(functiondef);
    if (type == "for") return cont(pushlex("form"), pushblockcontext, forspec, statement, popcontext, poplex);
    if (type == "class" || (isTS && value == "interface")) {
      cx.marked = "keyword"
      return cont(pushlex("form", type == "class" ? type : value), className, poplex)
    }
    if (type == "variable") {
      if (isTS && value == "declare") {
        cx.marked = "keyword"
        return cont(statement)
      } else if (isTS && (value == "module" || value == "enum" || value == "type") && cx.stream.match(/^\s*\w/, false)) {
        cx.marked = "keyword"
        if (value == "enum") return cont(enumdef);
        else if (value == "type") return cont(typename, expect("operator"), typeexpr, expect(";"));
        else return cont(pushlex("form"), pattern, expect("{"), pushlex("}"), block, poplex, poplex)
      } else if (isTS && value == "namespace") {
        cx.marked = "keyword"
        return cont(pushlex("form"), expression, statement, poplex)
      } else if (isTS && value == "abstract") {
        cx.marked = "keyword"
        return cont(statement)
      } else {
        return cont(pushlex("stat"), maybelabel);
      }
    }
    if (type == "switch") return cont(pushlex("form"), parenExpr, expect("{"), pushlex("}", "switch"), pushblockcontext,
                                      block, poplex, poplex, popcontext);
    if (type == "case") return cont(expression, expect(":"));
    if (type == "default") return cont(expect(":"));
    if (type == "catch") return cont(pushlex("form"), pushcontext, maybeCatchBinding, statement, poplex, popcontext);
    if (type == "export") return cont(pushlex("stat"), afterExport, poplex);
    if (type == "import") return cont(pushlex("stat"), afterImport, poplex);
    if (type == "async") return cont(statement)
    if (value == "@") return cont(expression, statement)
    return pass(pushlex("stat"), expression, expect(";"), poplex);
  }
  function maybeCatchBinding(type) {
    if (type == "(") return cont(funarg, expect(")"))
  }
  function expression(type, value) {
    return expressionInner(type, value, false);
  }
  function expressionNoComma(type, value) {
    return expressionInner(type, value, true);
  }
  function parenExpr(type) {
    if (type != "(") return pass()
    return cont(pushlex(")"), maybeexpression, expect(")"), poplex)
  }
  function expressionInner(type, value, noComma) {
    if (cx.state.fatArrowAt == cx.stream.start) {
      var body = noComma ? arrowBodyNoComma : arrowBody;
      if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, expect("=>"), body, popcontext);
      else if (type == "variable") return pass(pushcontext, pattern, expect("=>"), body, popcontext);
    }

    var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma;
    if (atomicTypes.hasOwnProperty(type)) return cont(maybeop);
    if (type == "function") return cont(functiondef, maybeop);
    if (type == "class" || (isTS && value == "interface")) { cx.marked = "keyword"; return cont(pushlex("form"), classExpression, poplex); }
    if (type == "keyword c" || type == "async") return cont(noComma ? expressionNoComma : expression);
    if (type == "(") return cont(pushlex(")"), maybeexpression, expect(")"), poplex, maybeop);
    if (type == "operator" || type == "spread") return cont(noComma ? expressionNoComma : expression);
    if (type == "[") return cont(pushlex("]"), arrayLiteral, poplex, maybeop);
    if (type == "{") return contCommasep(objprop, "}", null, maybeop);
    if (type == "quasi") return pass(quasi, maybeop);
    if (type == "new") return cont(maybeTarget(noComma));
    return cont();
  }
  function maybeexpression(type) {
    if (type.match(/[;\}\)\],]/)) return pass();
    return pass(expression);
  }

  function maybeoperatorComma(type, value) {
    if (type == ",") return cont(maybeexpression);
    return maybeoperatorNoComma(type, value, false);
  }
  function maybeoperatorNoComma(type, value, noComma) {
    var me = noComma == false ? maybeoperatorComma : maybeoperatorNoComma;
    var expr = noComma == false ? expression : expressionNoComma;
    if (type == "=>") return cont(pushcontext, noComma ? arrowBodyNoComma : arrowBody, popcontext);
    if (type == "operator") {
      if (/\+\+|--/.test(value) || isTS && value == "!") return cont(me);
      if (isTS && value == "<" && cx.stream.match(/^([^<>]|<[^<>]*>)*>\s*\(/, false))
        return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, me);
      if (value == "?") return cont(expression, expect(":"), expr);
      return cont(expr);
    }
    if (type == "quasi") { return pass(quasi, me); }
    if (type == ";") return;
    if (type == "(") return contCommasep(expressionNoComma, ")", "call", me);
    if (type == ".") return cont(property, me);
    if (type == "[") return cont(pushlex("]"), maybeexpression, expect("]"), poplex, me);
    if (isTS && value == "as") { cx.marked = "keyword"; return cont(typeexpr, me) }
    if (type == "regexp") {
      cx.state.lastType = cx.marked = "operator"
      cx.stream.backUp(cx.stream.pos - cx.stream.start - 1)
      return cont(expr)
    }
  }
  function quasi(type, value) {
    if (type != "quasi") return pass();
    if (value.slice(value.length - 2) != "${") return cont(quasi);
    return cont(maybeexpression, continueQuasi);
  }
  function continueQuasi(type) {
    if (type == "}") {
      cx.marked = "string-2";
      cx.state.tokenize = tokenQuasi;
      return cont(quasi);
    }
  }
  function arrowBody(type) {
    findFatArrow(cx.stream, cx.state);
    return pass(type == "{" ? statement : expression);
  }
  function arrowBodyNoComma(type) {
    findFatArrow(cx.stream, cx.state);
    return pass(type == "{" ? statement : expressionNoComma);
  }
  function maybeTarget(noComma) {
    return function(type) {
      if (type == ".") return cont(noComma ? targetNoComma : target);
      else if (type == "variable" && isTS) return cont(maybeTypeArgs, noComma ? maybeoperatorNoComma : maybeoperatorComma)
      else return pass(noComma ? expressionNoComma : expression);
    };
  }
  function target(_, value) {
    if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorComma); }
  }
  function targetNoComma(_, value) {
    if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorNoComma); }
  }
  function maybelabel(type) {
    if (type == ":") return cont(poplex, statement);
    return pass(maybeoperatorComma, expect(";"), poplex);
  }
  function property(type) {
    if (type == "variable") {cx.marked = "property"; return cont();}
  }
  function objprop(type, value) {
    if (type == "async") {
      cx.marked = "property";
      return cont(objprop);
    } else if (type == "variable" || cx.style == "keyword") {
      cx.marked = "property";
      if (value == "get" || value == "set") return cont(getterSetter);
      var m // Work around fat-arrow-detection complication for detecting typescript typed arrow params
      if (isTS && cx.state.fatArrowAt == cx.stream.start && (m = cx.stream.match(/^\s*:\s*/, false)))
        cx.state.fatArrowAt = cx.stream.pos + m[0].length
      return cont(afterprop);
    } else if (type == "number" || type == "string") {
      cx.marked = jsonldMode ? "property" : (cx.style + " property");
      return cont(afterprop);
    } else if (type == "jsonld-keyword") {
      return cont(afterprop);
    } else if (isTS && isModifier(value)) {
      cx.marked = "keyword"
      return cont(objprop)
    } else if (type == "[") {
      return cont(expression, maybetype, expect("]"), afterprop);
    } else if (type == "spread") {
      return cont(expressionNoComma, afterprop);
    } else if (value == "*") {
      cx.marked = "keyword";
      return cont(objprop);
    } else if (type == ":") {
      return pass(afterprop)
    }
  }
  function getterSetter(type) {
    if (type != "variable") return pass(afterprop);
    cx.marked = "property";
    return cont(functiondef);
  }
  function afterprop(type) {
    if (type == ":") return cont(expressionNoComma);
    if (type == "(") return pass(functiondef);
  }
  function commasep(what, end, sep) {
    function proceed(type, value) {
      if (sep ? sep.indexOf(type) > -1 : type == ",") {
        var lex = cx.state.lexical;
        if (lex.info == "call") lex.pos = (lex.pos || 0) + 1;
        return cont(function(type, value) {
          if (type == end || value == end) return pass()
          return pass(what)
        }, proceed);
      }
      if (type == end || value == end) return cont();
      if (sep && sep.indexOf(";") > -1) return pass(what)
      return cont(expect(end));
    }
    return function(type, value) {
      if (type == end || value == end) return cont();
      return pass(what, proceed);
    };
  }
  function contCommasep(what, end, info) {
    for (var i = 3; i < arguments.length; i++)
      cx.cc.push(arguments[i]);
    return cont(pushlex(end, info), commasep(what, end), poplex);
  }
  function block(type) {
    if (type == "}") return cont();
    return pass(statement, block);
  }
  function maybetype(type, value) {
    if (isTS) {
      if (type == ":") return cont(typeexpr);
      if (value == "?") return cont(maybetype);
    }
  }
  function maybetypeOrIn(type, value) {
    if (isTS && (type == ":" || value == "in")) return cont(typeexpr)
  }
  function mayberettype(type) {
    if (isTS && type == ":") {
      if (cx.stream.match(/^\s*\w+\s+is\b/, false)) return cont(expression, isKW, typeexpr)
      else return cont(typeexpr)
    }
  }
  function isKW(_, value) {
    if (value == "is") {
      cx.marked = "keyword"
      return cont()
    }
  }
  function typeexpr(type, value) {
    if (value == "keyof" || value == "typeof" || value == "infer" || value == "readonly") {
      cx.marked = "keyword"
      return cont(value == "typeof" ? expressionNoComma : typeexpr)
    }
    if (type == "variable" || value == "void") {
      cx.marked = "type"
      return cont(afterType)
    }
    if (value == "|" || value == "&") return cont(typeexpr)
    if (type == "string" || type == "number" || type == "atom") return cont(afterType);
    if (type == "[") return cont(pushlex("]"), commasep(typeexpr, "]", ","), poplex, afterType)
    if (type == "{") return cont(pushlex("}"), typeprops, poplex, afterType)
    if (type == "(") return cont(commasep(typearg, ")"), maybeReturnType, afterType)
    if (type == "<") return cont(commasep(typeexpr, ">"), typeexpr)
    if (type == "quasi") { return pass(quasiType, afterType); }
  }
  function maybeReturnType(type) {
    if (type == "=>") return cont(typeexpr)
  }
  function typeprops(type) {
    if (type.match(/[\}\)\]]/)) return cont()
    if (type == "," || type == ";") return cont(typeprops)
    return pass(typeprop, typeprops)
  }
  function typeprop(type, value) {
    if (type == "variable" || cx.style == "keyword") {
      cx.marked = "property"
      return cont(typeprop)
    } else if (value == "?" || type == "number" || type == "string") {
      return cont(typeprop)
    } else if (type == ":") {
      return cont(typeexpr)
    } else if (type == "[") {
      return cont(expect("variable"), maybetypeOrIn, expect("]"), typeprop)
    } else if (type == "(") {
      return pass(functiondecl, typeprop)
    } else if (!type.match(/[;\}\)\],]/)) {
      return cont()
    }
  }
  function quasiType(type, value) {
    if (type != "quasi") return pass();
    if (value.slice(value.length - 2) != "${") return cont(quasiType);
    return cont(typeexpr, continueQuasiType);
  }
  function continueQuasiType(type) {
    if (type == "}") {
      cx.marked = "string-2";
      cx.state.tokenize = tokenQuasi;
      return cont(quasiType);
    }
  }
  function typearg(type, value) {
    if (type == "variable" && cx.stream.match(/^\s*[?:]/, false) || value == "?") return cont(typearg)
    if (type == ":") return cont(typeexpr)
    if (type == "spread") return cont(typearg)
    return pass(typeexpr)
  }
  function afterType(type, value) {
    if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType)
    if (value == "|" || type == "." || value == "&") return cont(typeexpr)
    if (type == "[") return cont(typeexpr, expect("]"), afterType)
    if (value == "extends" || value == "implements") { cx.marked = "keyword"; return cont(typeexpr) }
    if (value == "?") return cont(typeexpr, expect(":"), typeexpr)
  }
  function maybeTypeArgs(_, value) {
    if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType)
  }
  function typeparam() {
    return pass(typeexpr, maybeTypeDefault)
  }
  function maybeTypeDefault(_, value) {
    if (value == "=") return cont(typeexpr)
  }
  function vardef(_, value) {
    if (value == "enum") {cx.marked = "keyword"; return cont(enumdef)}
    return pass(pattern, maybetype, maybeAssign, vardefCont);
  }
  function pattern(type, value) {
    if (isTS && isModifier(value)) { cx.marked = "keyword"; return cont(pattern) }
    if (type == "variable") { register(value); return cont(); }
    if (type == "spread") return cont(pattern);
    if (type == "[") return contCommasep(eltpattern, "]");
    if (type == "{") return contCommasep(proppattern, "}");
  }
  function proppattern(type, value) {
    if (type == "variable" && !cx.stream.match(/^\s*:/, false)) {
      register(value);
      return cont(maybeAssign);
    }
    if (type == "variable") cx.marked = "property";
    if (type == "spread") return cont(pattern);
    if (type == "}") return pass();
    if (type == "[") return cont(expression, expect(']'), expect(':'), proppattern);
    return cont(expect(":"), pattern, maybeAssign);
  }
  function eltpattern() {
    return pass(pattern, maybeAssign)
  }
  function maybeAssign(_type, value) {
    if (value == "=") return cont(expressionNoComma);
  }
  function vardefCont(type) {
    if (type == ",") return cont(vardef);
  }
  function maybeelse(type, value) {
    if (type == "keyword b" && value == "else") return cont(pushlex("form", "else"), statement, poplex);
  }
  function forspec(type, value) {
    if (value == "await") return cont(forspec);
    if (type == "(") return cont(pushlex(")"), forspec1, poplex);
  }
  function forspec1(type) {
    if (type == "var") return cont(vardef, forspec2);
    if (type == "variable") return cont(forspec2);
    return pass(forspec2)
  }
  function forspec2(type, value) {
    if (type == ")") return cont()
    if (type == ";") return cont(forspec2)
    if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression, forspec2) }
    return pass(expression, forspec2)
  }
  function functiondef(type, value) {
    if (value == "*") {cx.marked = "keyword"; return cont(functiondef);}
    if (type == "variable") {register(value); return cont(functiondef);}
    if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, mayberettype, statement, popcontext);
    if (isTS && value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, functiondef)
  }
  function functiondecl(type, value) {
    if (value == "*") {cx.marked = "keyword"; return cont(functiondecl);}
    if (type == "variable") {register(value); return cont(functiondecl);}
    if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, mayberettype, popcontext);
    if (isTS && value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, functiondecl)
  }
  function typename(type, value) {
    if (type == "keyword" || type == "variable") {
      cx.marked = "type"
      return cont(typename)
    } else if (value == "<") {
      return cont(pushlex(">"), commasep(typeparam, ">"), poplex)
    }
  }
  function funarg(type, value) {
    if (value == "@") cont(expression, funarg)
    if (type == "spread") return cont(funarg);
    if (isTS && isModifier(value)) { cx.marked = "keyword"; return cont(funarg); }
    if (isTS && type == "this") return cont(maybetype, maybeAssign)
    return pass(pattern, maybetype, maybeAssign);
  }
  function classExpression(type, value) {
    // Class expressions may have an optional name.
    if (type == "variable") return className(type, value);
    return classNameAfter(type, value);
  }
  function className(type, value) {
    if (type == "variable") {register(value); return cont(classNameAfter);}
  }
  function classNameAfter(type, value) {
    if (value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, classNameAfter)
    if (value == "extends" || value == "implements" || (isTS && type == ",")) {
      if (value == "implements") cx.marked = "keyword";
      return cont(isTS ? typeexpr : expression, classNameAfter);
    }
    if (type == "{") return cont(pushlex("}"), classBody, poplex);
  }
  function classBody(type, value) {
    if (type == "async" ||
        (type == "variable" &&
         (value == "static" || value == "get" || value == "set" || (isTS && isModifier(value))) &&
         cx.stream.match(/^\s+#?[\w$\xa1-\uffff]/, false))) {
      cx.marked = "keyword";
      return cont(classBody);
    }
    if (type == "variable" || cx.style == "keyword") {
      cx.marked = "property";
      return cont(classfield, classBody);
    }
    if (type == "number" || type == "string") return cont(classfield, classBody);
    if (type == "[")
      return cont(expression, maybetype, expect("]"), classfield, classBody)
    if (value == "*") {
      cx.marked = "keyword";
      return cont(classBody);
    }
    if (isTS && type == "(") return pass(functiondecl, classBody)
    if (type == ";" || type == ",") return cont(classBody);
    if (type == "}") return cont();
    if (value == "@") return cont(expression, classBody)
  }
  function classfield(type, value) {
    if (value == "!") return cont(classfield)
    if (value == "?") return cont(classfield)
    if (type == ":") return cont(typeexpr, maybeAssign)
    if (value == "=") return cont(expressionNoComma)
    var context = cx.state.lexical.prev, isInterface = context && context.info == "interface"
    return pass(isInterface ? functiondecl : functiondef)
  }
  function afterExport(type, value) {
    if (value == "*") { cx.marked = "keyword"; return cont(maybeFrom, expect(";")); }
    if (value == "default") { cx.marked = "keyword"; return cont(expression, expect(";")); }
    if (type == "{") return cont(commasep(exportField, "}"), maybeFrom, expect(";"));
    return pass(statement);
  }
  function exportField(type, value) {
    if (value == "as") { cx.marked = "keyword"; return cont(expect("variable")); }
    if (type == "variable") return pass(expressionNoComma, exportField);
  }
  function afterImport(type) {
    if (type == "string") return cont();
    if (type == "(") return pass(expression);
    if (type == ".") return pass(maybeoperatorComma);
    return pass(importSpec, maybeMoreImports, maybeFrom);
  }
  function importSpec(type, value) {
    if (type == "{") return contCommasep(importSpec, "}");
    if (type == "variable") register(value);
    if (value == "*") cx.marked = "keyword";
    return cont(maybeAs);
  }
  function maybeMoreImports(type) {
    if (type == ",") return cont(importSpec, maybeMoreImports)
  }
  function maybeAs(_type, value) {
    if (value == "as") { cx.marked = "keyword"; return cont(importSpec); }
  }
  function maybeFrom(_type, value) {
    if (value == "from") { cx.marked = "keyword"; return cont(expression); }
  }
  function arrayLiteral(type) {
    if (type == "]") return cont();
    return pass(commasep(expressionNoComma, "]"));
  }
  function enumdef() {
    return pass(pushlex("form"), pattern, expect("{"), pushlex("}"), commasep(enummember, "}"), poplex, poplex)
  }
  function enummember() {
    return pass(pattern, maybeAssign);
  }

  function isContinuedStatement(state, textAfter) {
    return state.lastType == "operator" || state.lastType == "," ||
      isOperatorChar.test(textAfter.charAt(0)) ||
      /[,.]/.test(textAfter.charAt(0));
  }

  function expressionAllowed(stream, state, backUp) {
    return state.tokenize == tokenBase &&
      /^(?:operator|sof|keyword [bcd]|case|new|export|default|spread|[\[{}\(,;:]|=>)$/.test(state.lastType) ||
      (state.lastType == "quasi" && /\{\s*$/.test(stream.string.slice(0, stream.pos - (backUp || 0))))
  }

  // Interface

  return {
    startState: function(basecolumn) {
      var state = {
        tokenize: tokenBase,
        lastType: "sof",
        cc: [],
        lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false),
        localVars: parserConfig.localVars,
        context: parserConfig.localVars && new Context(null, null, false),
        indented: basecolumn || 0
      };
      if (parserConfig.globalVars && typeof parserConfig.globalVars == "object")
        state.globalVars = parserConfig.globalVars;
      return state;
    },

    token: function(stream, state) {
      if (stream.sol()) {
        if (!state.lexical.hasOwnProperty("align"))
          state.lexical.align = false;
        state.indented = stream.indentation();
        findFatArrow(stream, state);
      }
      if (state.tokenize != tokenComment && stream.eatSpace()) return null;
      var style = state.tokenize(stream, state);
      if (type == "comment") return style;
      state.lastType = type == "operator" && (content == "++" || content == "--") ? "incdec" : type;
      return parseJS(state, style, type, content, stream);
    },

    indent: function(state, textAfter) {
      if (state.tokenize == tokenComment || state.tokenize == tokenQuasi) return CodeMirror.Pass;
      if (state.tokenize != tokenBase) return 0;
      var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical, top
      // Kludge to prevent 'maybelse' from blocking lexical scope pops
      if (!/^\s*else\b/.test(textAfter)) for (var i = state.cc.length - 1; i >= 0; --i) {
        var c = state.cc[i];
        if (c == poplex) lexical = lexical.prev;
        else if (c != maybeelse && c != popcontext) break;
      }
      while ((lexical.type == "stat" || lexical.type == "form") &&
             (firstChar == "}" || ((top = state.cc[state.cc.length - 1]) &&
                                   (top == maybeoperatorComma || top == maybeoperatorNoComma) &&
                                   !/^[,\.=+\-*:?[\(]/.test(textAfter))))
        lexical = lexical.prev;
      if (statementIndent && lexical.type == ")" && lexical.prev.type == "stat")
        lexical = lexical.prev;
      var type = lexical.type, closing = firstChar == type;

      if (type == "vardef") return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? lexical.info.length + 1 : 0);
      else if (type == "form" && firstChar == "{") return lexical.indented;
      else if (type == "form") return lexical.indented + indentUnit;
      else if (type == "stat")
        return lexical.indented + (isContinuedStatement(state, textAfter) ? statementIndent || indentUnit : 0);
      else if (lexical.info == "switch" && !closing && parserConfig.doubleIndentSwitch != false)
        return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit);
      else if (lexical.align) return lexical.column + (closing ? 0 : 1);
      else return lexical.indented + (closing ? 0 : indentUnit);
    },

    electricInput: /^\s*(?:case .*?:|default:|\{|\})$/,
    blockCommentStart: jsonMode ? null : "/*",
    blockCommentEnd: jsonMode ? null : "*/",
    blockCommentContinue: jsonMode ? null : " * ",
    lineComment: jsonMode ? null : "//",
    fold: "brace",
    closeBrackets: "()[]{}''\"\"``",

    helperType: jsonMode ? "json" : "javascript",
    jsonldMode: jsonldMode,
    jsonMode: jsonMode,

    expressionAllowed: expressionAllowed,

    skipExpression: function(state) {
      parseJS(state, "atom", "atom", "true", new CodeMirror.StringStream("", 2, null))
    }
  };
});

CodeMirror.registerHelper("wordChars", "javascript", /[\w$]/);

CodeMirror.defineMIME("text/javascript", "javascript");
CodeMirror.defineMIME("text/ecmascript", "javascript");
CodeMirror.defineMIME("application/javascript", "javascript");
CodeMirror.defineMIME("application/x-javascript", "javascript");
CodeMirror.defineMIME("application/ecmascript", "javascript");
CodeMirror.defineMIME("application/json", { name: "javascript", json: true });
CodeMirror.defineMIME("application/x-json", { name: "javascript", json: true });
CodeMirror.defineMIME("application/manifest+json", { name: "javascript", json: true })
CodeMirror.defineMIME("application/ld+json", { name: "javascript", jsonld: true });
CodeMirror.defineMIME("text/typescript", { name: "javascript", typescript: true });
CodeMirror.defineMIME("application/typescript", { name: "javascript", typescript: true });

});


/***/ }),

/***/ 589:
/***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {

// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/5/LICENSE

(function(mod) {
  if (true) // CommonJS
    mod(__webpack_require__(631));
  else {}
})(function(CodeMirror) {
"use strict";

var htmlConfig = {
  autoSelfClosers: {'area': true, 'base': true, 'br': true, 'col': true, 'command': true,
                    'embed': true, 'frame': true, 'hr': true, 'img': true, 'input': true,
                    'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true,
                    'track': true, 'wbr': true, 'menuitem': true},
  implicitlyClosed: {'dd': true, 'li': true, 'optgroup': true, 'option': true, 'p': true,
                     'rp': true, 'rt': true, 'tbody': true, 'td': true, 'tfoot': true,
                     'th': true, 'tr': true},
  contextGrabbers: {
    'dd': {'dd': true, 'dt': true},
    'dt': {'dd': true, 'dt': true},
    'li': {'li': true},
    'option': {'option': true, 'optgroup': true},
    'optgroup': {'optgroup': true},
    'p': {'address': true, 'article': true, 'aside': true, 'blockquote': true, 'dir': true,
          'div': true, 'dl': true, 'fieldset': true, 'footer': true, 'form': true,
          'h1': true, 'h2': true, 'h3': true, 'h4': true, 'h5': true, 'h6': true,
          'header': true, 'hgroup': true, 'hr': true, 'menu': true, 'nav': true, 'ol': true,
          'p': true, 'pre': true, 'section': true, 'table': true, 'ul': true},
    'rp': {'rp': true, 'rt': true},
    'rt': {'rp': true, 'rt': true},
    'tbody': {'tbody': true, 'tfoot': true},
    'td': {'td': true, 'th': true},
    'tfoot': {'tbody': true},
    'th': {'td': true, 'th': true},
    'thead': {'tbody': true, 'tfoot': true},
    'tr': {'tr': true}
  },
  doNotIndent: {"pre": true},
  allowUnquoted: true,
  allowMissing: true,
  caseFold: true
}

var xmlConfig = {
  autoSelfClosers: {},
  implicitlyClosed: {},
  contextGrabbers: {},
  doNotIndent: {},
  allowUnquoted: false,
  allowMissing: false,
  allowMissingTagName: false,
  caseFold: false
}

CodeMirror.defineMode("xml", function(editorConf, config_) {
  var indentUnit = editorConf.indentUnit
  var config = {}
  var defaults = config_.htmlMode ? htmlConfig : xmlConfig
  for (var prop in defaults) config[prop] = defaults[prop]
  for (var prop in config_) config[prop] = config_[prop]

  // Return variables for tokenizers
  var type, setStyle;

  function inText(stream, state) {
    function chain(parser) {
      state.tokenize = parser;
      return parser(stream, state);
    }

    var ch = stream.next();
    if (ch == "<") {
      if (stream.eat("!")) {
        if (stream.eat("[")) {
          if (stream.match("CDATA[")) return chain(inBlock("atom", "]]>"));
          else return null;
        } else if (stream.match("--")) {
          return chain(inBlock("comment", "-->"));
        } else if (stream.match("DOCTYPE", true, true)) {
          stream.eatWhile(/[\w\._\-]/);
          return chain(doctype(1));
        } else {
          return null;
        }
      } else if (stream.eat("?")) {
        stream.eatWhile(/[\w\._\-]/);
        state.tokenize = inBlock("meta", "?>");
        return "meta";
      } else {
        type = stream.eat("/") ? "closeTag" : "openTag";
        state.tokenize = inTag;
        return "tag bracket";
      }
    } else if (ch == "&") {
      var ok;
      if (stream.eat("#")) {
        if (stream.eat("x")) {
          ok = stream.eatWhile(/[a-fA-F\d]/) && stream.eat(";");
        } else {
          ok = stream.eatWhile(/[\d]/) && stream.eat(";");
        }
      } else {
        ok = stream.eatWhile(/[\w\.\-:]/) && stream.eat(";");
      }
      return ok ? "atom" : "error";
    } else {
      stream.eatWhile(/[^&<]/);
      return null;
    }
  }
  inText.isInText = true;

  function inTag(stream, state) {
    var ch = stream.next();
    if (ch == ">" || (ch == "/" && stream.eat(">"))) {
      state.tokenize = inText;
      type = ch == ">" ? "endTag" : "selfcloseTag";
      return "tag bracket";
    } else if (ch == "=") {
      type = "equals";
      return null;
    } else if (ch == "<") {
      state.tokenize = inText;
      state.state = baseState;
      state.tagName = state.tagStart = null;
      var next = state.tokenize(stream, state);
      return next ? next + " tag error" : "tag error";
    } else if (/[\'\"]/.test(ch)) {
      state.tokenize = inAttribute(ch);
      state.stringStartCol = stream.column();
      return state.tokenize(stream, state);
    } else {
      stream.match(/^[^\s\u00a0=<>\"\']*[^\s\u00a0=<>\"\'\/]/);
      return "word";
    }
  }

  function inAttribute(quote) {
    var closure = function(stream, state) {
      while (!stream.eol()) {
        if (stream.next() == quote) {
          state.tokenize = inTag;
          break;
        }
      }
      return "string";
    };
    closure.isInAttribute = true;
    return closure;
  }

  function inBlock(style, terminator) {
    return function(stream, state) {
      while (!stream.eol()) {
        if (stream.match(terminator)) {
          state.tokenize = inText;
          break;
        }
        stream.next();
      }
      return style;
    }
  }

  function doctype(depth) {
    return function(stream, state) {
      var ch;
      while ((ch = stream.next()) != null) {
        if (ch == "<") {
          state.tokenize = doctype(depth + 1);
          return state.tokenize(stream, state);
        } else if (ch == ">") {
          if (depth == 1) {
            state.tokenize = inText;
            break;
          } else {
            state.tokenize = doctype(depth - 1);
            return state.tokenize(stream, state);
          }
        }
      }
      return "meta";
    };
  }

  function lower(tagName) {
    return tagName && tagName.toLowerCase();
  }

  function Context(state, tagName, startOfLine) {
    this.prev = state.context;
    this.tagName = tagName || "";
    this.indent = state.indented;
    this.startOfLine = startOfLine;
    if (config.doNotIndent.hasOwnProperty(tagName) || (state.context && state.context.noIndent))
      this.noIndent = true;
  }
  function popContext(state) {
    if (state.context) state.context = state.context.prev;
  }
  function maybePopContext(state, nextTagName) {
    var parentTagName;
    while (true) {
      if (!state.context) {
        return;
      }
      parentTagName = state.context.tagName;
      if (!config.contextGrabbers.hasOwnProperty(lower(parentTagName)) ||
          !config.contextGrabbers[lower(parentTagName)].hasOwnProperty(lower(nextTagName))) {
        return;
      }
      popContext(state);
    }
  }

  function baseState(type, stream, state) {
    if (type == "openTag") {
      state.tagStart = stream.column();
      return tagNameState;
    } else if (type == "closeTag") {
      return closeTagNameState;
    } else {
      return baseState;
    }
  }
  function tagNameState(type, stream, state) {
    if (type == "word") {
      state.tagName = stream.current();
      setStyle = "tag";
      return attrState;
    } else if (config.allowMissingTagName && type == "endTag") {
      setStyle = "tag bracket";
      return attrState(type, stream, state);
    } else {
      setStyle = "error";
      return tagNameState;
    }
  }
  function closeTagNameState(type, stream, state) {
    if (type == "word") {
      var tagName = stream.current();
      if (state.context && state.context.tagName != tagName &&
          config.implicitlyClosed.hasOwnProperty(lower(state.context.tagName)))
        popContext(state);
      if ((state.context && state.context.tagName == tagName) || config.matchClosing === false) {
        setStyle = "tag";
        return closeState;
      } else {
        setStyle = "tag error";
        return closeStateErr;
      }
    } else if (config.allowMissingTagName && type == "endTag") {
      setStyle = "tag bracket";
      return closeState(type, stream, state);
    } else {
      setStyle = "error";
      return closeStateErr;
    }
  }

  function closeState(type, _stream, state) {
    if (type != "endTag") {
      setStyle = "error";
      return closeState;
    }
    popContext(state);
    return baseState;
  }
  function closeStateErr(type, stream, state) {
    setStyle = "error";
    return closeState(type, stream, state);
  }

  function attrState(type, _stream, state) {
    if (type == "word") {
      setStyle = "attribute";
      return attrEqState;
    } else if (type == "endTag" || type == "selfcloseTag") {
      var tagName = state.tagName, tagStart = state.tagStart;
      state.tagName = state.tagStart = null;
      if (type == "selfcloseTag" ||
          config.autoSelfClosers.hasOwnProperty(lower(tagName))) {
        maybePopContext(state, tagName);
      } else {
        maybePopContext(state, tagName);
        state.context = new Context(state, tagName, tagStart == state.indented);
      }
      return baseState;
    }
    setStyle = "error";
    return attrState;
  }
  function attrEqState(type, stream, state) {
    if (type == "equals") return attrValueState;
    if (!config.allowMissing) setStyle = "error";
    return attrState(type, stream, state);
  }
  function attrValueState(type, stream, state) {
    if (type == "string") return attrContinuedState;
    if (type == "word" && config.allowUnquoted) {setStyle = "string"; return attrState;}
    setStyle = "error";
    return attrState(type, stream, state);
  }
  function attrContinuedState(type, stream, state) {
    if (type == "string") return attrContinuedState;
    return attrState(type, stream, state);
  }

  return {
    startState: function(baseIndent) {
      var state = {tokenize: inText,
                   state: baseState,
                   indented: baseIndent || 0,
                   tagName: null, tagStart: null,
                   context: null}
      if (baseIndent != null) state.baseIndent = baseIndent
      return state
    },

    token: function(stream, state) {
      if (!state.tagName && stream.sol())
        state.indented = stream.indentation();

      if (stream.eatSpace()) return null;
      type = null;
      var style = state.tokenize(stream, state);
      if ((style || type) && style != "comment") {
        setStyle = null;
        state.state = state.state(type || style, stream, state);
        if (setStyle)
          style = setStyle == "error" ? style + " error" : setStyle;
      }
      return style;
    },

    indent: function(state, textAfter, fullLine) {
      var context = state.context;
      // Indent multi-line strings (e.g. css).
      if (state.tokenize.isInAttribute) {
        if (state.tagStart == state.indented)
          return state.stringStartCol + 1;
        else
          return state.indented + indentUnit;
      }
      if (context && context.noIndent) return CodeMirror.Pass;
      if (state.tokenize != inTag && state.tokenize != inText)
        return fullLine ? fullLine.match(/^(\s*)/)[0].length : 0;
      // Indent the starts of attribute names.
      if (state.tagName) {
        if (config.multilineTagIndentPastTag !== false)
          return state.tagStart + state.tagName.length + 2;
        else
          return state.tagStart + indentUnit * (config.multilineTagIndentFactor || 1);
      }
      if (config.alignCDATA && /<!\[CDATA\[/.test(textAfter)) return 0;
      var tagAfter = textAfter && /^<(\/)?([\w_:\.-]*)/.exec(textAfter);
      if (tagAfter && tagAfter[1]) { // Closing tag spotted
        while (context) {
          if (context.tagName == tagAfter[2]) {
            context = context.prev;
            break;
          } else if (config.implicitlyClosed.hasOwnProperty(lower(context.tagName))) {
            context = context.prev;
          } else {
            break;
          }
        }
      } else if (tagAfter) { // Opening tag spotted
        while (context) {
          var grabbers = config.contextGrabbers[lower(context.tagName)];
          if (grabbers && grabbers.hasOwnProperty(lower(tagAfter[2])))
            context = context.prev;
          else
            break;
        }
      }
      while (context && context.prev && !context.startOfLine)
        context = context.prev;
      if (context) return context.indent + indentUnit;
      else return state.baseIndent || 0;
    },

    electricInput: /<\/[\s\w:]+>$/,
    blockCommentStart: "<!--",
    blockCommentEnd: "-->",

    configuration: config.htmlMode ? "html" : "xml",
    helperType: config.htmlMode ? "html" : "xml",

    skipAttribute: function(state) {
      if (state.state == attrValueState)
        state.state = attrState
    },

    xmlCurrentTag: function(state) {
      return state.tagName ? {name: state.tagName, close: state.type == "closeTag"} : null
    },

    xmlCurrentContext: function(state) {
      var context = []
      for (var cx = state.context; cx; cx = cx.prev)
        context.push(cx.tagName)
      return context.reverse()
    }
  };
});

CodeMirror.defineMIME("text/xml", "xml");
CodeMirror.defineMIME("application/xml", "xml");
if (!CodeMirror.mimeModes.hasOwnProperty("text/html"))
  CodeMirror.defineMIME("text/html", {name: "xml", htmlMode: true});

});


/***/ }),

/***/ 642:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Z: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _common__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(346);
var __extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();

var ModuleModel = /** @class */ (function (_super) {
    __extends(ModuleModel, _super);
    function ModuleModel(module, attributes, options) {
        var _this = _super.call(this, attributes, options) || this;
        _this._module = module;
        return _this;
    }
    Object.defineProperty(ModuleModel.prototype, "module", {
        get: function () {
            return this._module;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ModuleModel.prototype, "config", {
        get: function () {
            return this._module.config;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ModuleModel.prototype, "em", {
        get: function () {
            return this._module.em;
        },
        enumerable: false,
        configurable: true
    });
    return ModuleModel;
}(_common__WEBPACK_IMPORTED_MODULE_0__/* .Model */ .Hn));
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (ModuleModel);


/***/ }),

/***/ 675:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Z: () => (__WEBPACK_DEFAULT_EXPORT__),
/* harmony export */   q: () => (/* binding */ CanvasSpotBuiltInTypes)
/* harmony export */ });
/* harmony import */ var _abstract__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(642);
var __extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();

var CanvasSpotBuiltInTypes;
(function (CanvasSpotBuiltInTypes) {
    CanvasSpotBuiltInTypes["Select"] = "select";
    CanvasSpotBuiltInTypes["Hover"] = "hover";
    CanvasSpotBuiltInTypes["Spacing"] = "spacing";
    CanvasSpotBuiltInTypes["Target"] = "target";
    CanvasSpotBuiltInTypes["Resize"] = "resize";
})(CanvasSpotBuiltInTypes || (CanvasSpotBuiltInTypes = {}));
/**
 * Canvas spots are elements drawn on top of the canvas. They can be used to represent anything you
 * might need but the most common use case of canvas spots is rendering information and managing
 * components rendered in the canvas.
 * Read here for more information about [Canvas Spots](https://grapesjs.com/docs/modules/Canvas.html#canvas-spots)
 *
 * [Component]: component.html
 *
 * @property {String} id Spot ID.
 * @property {String} type Spot type.
 * @property {[Component]} [component] Component to which the spot will be attached.
 * @property {ComponentView} [componentView] ComponentView to which the spot will be attached.
 * @property {Object} [boxRect] Fixed box rect of the spot, eg. `{ width: 100, height: 100, x: 0, y: 0 }`.
 *
 */
var CanvasSpot = /** @class */ (function (_super) {
    __extends(CanvasSpot, _super);
    function CanvasSpot() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    CanvasSpot.prototype.defaults = function () {
        return {
            id: '',
            type: '',
        };
    };
    Object.defineProperty(CanvasSpot.prototype, "type", {
        get: function () {
            return this.get('type') || '';
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(CanvasSpot.prototype, "component", {
        get: function () {
            var _a;
            var cmp = this.get('component');
            return cmp || ((_a = this.get('componentView')) === null || _a === void 0 ? void 0 : _a.model);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(CanvasSpot.prototype, "componentView", {
        get: function () {
            var _a;
            var cmpView = this.get('componentView');
            return cmpView || ((_a = this.get('component')) === null || _a === void 0 ? void 0 : _a.getView());
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(CanvasSpot.prototype, "el", {
        get: function () {
            var _a;
            return (_a = this.componentView) === null || _a === void 0 ? void 0 : _a.el;
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Get the box rect of the spot.
     * @param {Object} [opts={}]
     * @returns {Object} The box rect object
     * @example
     * canvasSpot.getBoxRect();
     * // { width: 100, height: 50, x: 0, y: 0 }
     */
    CanvasSpot.prototype.getBoxRect = function (opts) {
        var _a = this, el = _a.el, em = _a.em;
        var cvView = em.Canvas.getCanvasView();
        var boxRect = this.get('boxRect');
        if (boxRect) {
            return boxRect;
        }
        else if (el && cvView) {
            return cvView.getElBoxRect(el, opts);
        }
        return {
            x: 0,
            y: 0,
            width: 0,
            height: 0,
        };
    };
    /**
     * Get the style object of the spot.
     * @param {Object} [opts={}]
     * @returns {CSSStyleDeclaration} [opts]
     * @example
     * canvasSpot.getStyle();
     * // { width: '100px', height: '...', ... }
     */
    CanvasSpot.prototype.getStyle = function (opts) {
        if (opts === void 0) { opts = {}; }
        var _a = opts.boxRect || this.getBoxRect(opts), width = _a.width, height = _a.height, x = _a.x, y = _a.y;
        return {
            width: "".concat(width, "px"),
            height: "".concat(height, "px"),
            top: '0',
            left: '0',
            position: 'absolute',
            translate: "".concat(x, "px ").concat(y, "px"),
        };
    };
    /**
     * Check the spot type.
     * @param {String} type
     * @returns {Boolean}
     * @example
     * canvasSpot.isType('select');
     */
    CanvasSpot.prototype.isType = function (type) {
        return this.type === type;
    };
    return CanvasSpot;
}(_abstract__WEBPACK_IMPORTED_MODULE_0__/* ["default"] */ .Z));
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (CanvasSpot);


/***/ }),

/***/ 713:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Z: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* unused harmony export CommandsEvents */
/**{START_EVENTS}*/
var CommandsEvents;
(function (CommandsEvents) {
    /**
     * @event `command:run` Triggered on run of any command.
     * @example
     * editor.on('command:run', ({ id, result, options }) => {
     *  console.log('Command id', id, 'command result', result);
     * });
     */
    CommandsEvents["run"] = "command:run";
    CommandsEvents["_run"] = "run";
    /**
     * @event `command:run:COMMAND_ID` Triggered on run of a specific command.
     * @example
     * editor.on('command:run:my-command', ({ result, options }) => { ... });
     */
    CommandsEvents["runCommand"] = "command:run:";
    CommandsEvents["_runCommand"] = "run:";
    /**
     * @event `command:run:before:COMMAND_ID` Triggered before the command is called.
     * @example
     * editor.on('command:run:before:my-command', ({ options }) => { ... });
     */
    CommandsEvents["runBeforeCommand"] = "command:run:before:";
    /**
     * @event `command:abort:COMMAND_ID` Triggered when the command execution is aborted.
     * @example
     * editor.on('command:abort:my-command', ({ options }) => { ... });
     *
     * // The command could be aborted during the before event
     * editor.on('command:run:before:my-command', ({ options }) => {
     *  if (someCondition) {
     *    options.abort = true;
     *  }
     * });
     */
    CommandsEvents["abort"] = "command:abort:";
    CommandsEvents["_abort"] = "abort:";
    /**
     * @event `command:stop` Triggered on stop of any command.
     * @example
     * editor.on('command:stop', ({ id, result, options }) => {
     *  console.log('Command id', id, 'command result', result);
     * });
     */
    CommandsEvents["stop"] = "command:stop";
    CommandsEvents["_stop"] = "stop";
    /**
     * @event `command:stop:COMMAND_ID` Triggered on stop of a specific command.
     * @example
     * editor.on('command:run:my-command', ({ result, options }) => { ... });
     */
    CommandsEvents["stopCommand"] = "command:stop:";
    CommandsEvents["_stopCommand"] = "stop:";
    /**
     * @event `command:stop:before:COMMAND_ID` Triggered before the command is called to stop.
     * @example
     * editor.on('command:stop:before:my-command', ({ options }) => { ... });
     */
    CommandsEvents["stopBeforeCommand"] = "command:stop:before:";
})(CommandsEvents || (CommandsEvents = {}));
/**{END_EVENTS}*/
// need this to avoid the TS documentation generator to break
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (CommandsEvents);


/***/ }),

/***/ 858:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({
    run: function (ed) {
        ed.Components.clear();
        ed.Css.clear();
    },
});


/***/ }),

/***/ 884:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var underscore__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(50);
/* harmony import */ var _utils_Dragger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(668);
/* harmony import */ var _utils_dom__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(491);



/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({
    run: function (ed) {
        (0,underscore__WEBPACK_IMPORTED_MODULE_0__.bindAll)(this, 'onKeyUp', 'enableDragger', 'disableDragger');
        this.editor = ed;
        this.canvasModel = this.canvas.getCanvasView().model;
        this.toggleMove(1);
    },
    stop: function (ed) {
        this.toggleMove();
        this.disableDragger();
    },
    onKeyUp: function (ev) {
        if ((0,_utils_dom__WEBPACK_IMPORTED_MODULE_1__/* .getKeyChar */ .sN)(ev) === ' ') {
            this.editor.stopCommand(this.id);
        }
    },
    enableDragger: function (ev) {
        this.toggleDragger(1, ev);
    },
    disableDragger: function (ev) {
        this.toggleDragger(0, ev);
    },
    toggleDragger: function (enable, ev) {
        var _a = this, canvasModel = _a.canvasModel, em = _a.em;
        var dragger = this.dragger;
        var methodCls = enable ? 'add' : 'remove';
        this.getCanvas().classList[methodCls]("".concat(this.ppfx, "is__grabbing"));
        if (!dragger) {
            dragger = new _utils_Dragger__WEBPACK_IMPORTED_MODULE_2__/* ["default"] */ .Z({
                getPosition: function () {
                    return {
                        x: canvasModel.get('x'),
                        y: canvasModel.get('y'),
                    };
                },
                setPosition: function (_a) {
                    var x = _a.x, y = _a.y;
                    canvasModel.set({ x: x, y: y });
                },
                onStart: function (ev, dragger) {
                    em.trigger('canvas:move:start', dragger);
                },
                onDrag: function (ev, dragger) {
                    em.trigger('canvas:move', dragger);
                },
                onEnd: function (ev, dragger) {
                    em.trigger('canvas:move:end', dragger);
                },
            });
            this.dragger = dragger;
        }
        enable ? dragger.start(ev) : dragger.stop();
    },
    toggleMove: function (enable) {
        var ppfx = this.ppfx;
        var methodCls = enable ? 'add' : 'remove';
        var methodEv = enable ? 'on' : 'off';
        var methodsEv = { on: _utils_dom__WEBPACK_IMPORTED_MODULE_1__.on, off: _utils_dom__WEBPACK_IMPORTED_MODULE_1__/* .off */ .S1 };
        var canvas = this.getCanvas();
        var classes = ["".concat(ppfx, "is__grab")];
        !enable && classes.push("".concat(ppfx, "is__grabbing"));
        classes.forEach(function (cls) { return canvas.classList[methodCls](cls); });
        methodsEv[methodEv](document, 'keyup', this.onKeyUp);
        methodsEv[methodEv](canvas, 'mousedown', this.enableDragger);
        methodsEv[methodEv](document, 'mouseup', this.disableDragger);
    },
});


/***/ }),

/***/ 790:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__),
/* harmony export */   defineCommand: () => (/* binding */ defineCommand)
/* harmony export */ });
/* harmony import */ var _common__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(346);
/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(713);
var __extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();


function defineCommand(def) {
    return def;
}
var CommandAbstract = /** @class */ (function (_super) {
    __extends(CommandAbstract, _super);
    function CommandAbstract(o) {
        var _this = _super.call(this, 0) || this;
        _this.config = o || {};
        _this.em = _this.config.em || {};
        var pfx = _this.config.stylePrefix;
        _this.pfx = pfx;
        _this.ppfx = _this.config.pStylePrefix;
        _this.hoverClass = "".concat(pfx, "hover");
        _this.badgeClass = "".concat(pfx, "badge");
        _this.plhClass = "".concat(pfx, "placeholder");
        _this.freezClass = "".concat(_this.ppfx, "freezed");
        _this.canvas = _this.em.Canvas;
        _this.init(_this.config);
        return _this;
    }
    /**
     * On frame scroll callback
     * @param  {[type]} e [description]
     * @return {[type]}   [description]
     */
    CommandAbstract.prototype.onFrameScroll = function (e) { };
    /**
     * Returns canval element
     * @return {HTMLElement}
     */
    CommandAbstract.prototype.getCanvas = function () {
        return this.canvas.getElement();
    };
    /**
     * Get canvas body element
     * @return {HTMLElement}
     */
    CommandAbstract.prototype.getCanvasBody = function () {
        return this.canvas.getBody();
    };
    /**
     * Get canvas wrapper element
     * @return {HTMLElement}
     */
    CommandAbstract.prototype.getCanvasTools = function () {
        return this.canvas.getToolsEl();
    };
    /**
     * Get the offset of the element
     * @param  {HTMLElement} el
     * @return {Object}
     */
    CommandAbstract.prototype.offset = function (el) {
        var rect = el.getBoundingClientRect();
        return {
            top: rect.top + el.ownerDocument.body.scrollTop,
            left: rect.left + el.ownerDocument.body.scrollLeft,
        };
    };
    /**
     * Callback triggered after initialize
     * @param  {Object}  o   Options
     * @private
     * */
    CommandAbstract.prototype.init = function (o) { };
    /**
     * Method that run command
     * @param  {Object}  editor Editor instance
     * @param  {Object}  [options={}] Options
     * @private
     * */
    CommandAbstract.prototype.callRun = function (editor, options) {
        if (options === void 0) { options = {}; }
        var id = this.id;
        editor.trigger("".concat(_types__WEBPACK_IMPORTED_MODULE_0__/* ["default"] */ .Z.runBeforeCommand).concat(id), { options: options });
        editor.trigger("".concat(_types__WEBPACK_IMPORTED_MODULE_0__/* ["default"] */ .Z._runCommand).concat(id, ":before"), options);
        if (options.abort) {
            editor.trigger("".concat(_types__WEBPACK_IMPORTED_MODULE_0__/* ["default"] */ .Z.abort).concat(id), { options: options });
            editor.trigger("".concat(_types__WEBPACK_IMPORTED_MODULE_0__/* ["default"] */ .Z._abort).concat(id), options);
            return;
        }
        var sender = options.sender || editor;
        var result = this.run(editor, sender, options);
        var data = { id: id, result: result, options: options };
        editor.trigger("".concat(_types__WEBPACK_IMPORTED_MODULE_0__/* ["default"] */ .Z.runCommand).concat(id), data);
        editor.trigger(_types__WEBPACK_IMPORTED_MODULE_0__/* ["default"] */ .Z.run, data);
        // deprecated
        editor.trigger("".concat(_types__WEBPACK_IMPORTED_MODULE_0__/* ["default"] */ .Z._runCommand).concat(id), result, options);
        editor.trigger(_types__WEBPACK_IMPORTED_MODULE_0__/* ["default"] */ .Z._run, id, result, options);
        return result;
    };
    /**
     * Method that run command
     * @param  {Object}  editor Editor instance
     * @param  {Object}  [options={}] Options
     * @private
     * */
    CommandAbstract.prototype.callStop = function (editor, options) {
        if (options === void 0) { options = {}; }
        var id = this.id;
        var sender = options.sender || editor;
        editor.trigger("".concat(_types__WEBPACK_IMPORTED_MODULE_0__/* ["default"] */ .Z.stopBeforeCommand).concat(id), { options: options });
        editor.trigger("".concat(_types__WEBPACK_IMPORTED_MODULE_0__/* ["default"] */ .Z._stopCommand).concat(id, ":before"), options);
        var result = this.stop(editor, sender, options);
        var data = { id: id, result: result, options: options };
        editor.trigger("".concat(_types__WEBPACK_IMPORTED_MODULE_0__/* ["default"] */ .Z.stopCommand).concat(id), data);
        editor.trigger(_types__WEBPACK_IMPORTED_MODULE_0__/* ["default"] */ .Z.stop, data);
        // deprecated
        editor.trigger("".concat(_types__WEBPACK_IMPORTED_MODULE_0__/* ["default"] */ .Z._stopCommand).concat(id), result, options);
        editor.trigger(_types__WEBPACK_IMPORTED_MODULE_0__/* ["default"] */ .Z._stop, id, result, options);
        return result;
    };
    /**
     * Stop current command
     */
    CommandAbstract.prototype.stopCommand = function (opts) {
        this.em.Commands.stop(this.id, opts);
    };
    /**
     * Method that run command
     * @param  {Object}  em     Editor model
     * @param  {Object}  sender  Button sender
     * @private
     * */
    CommandAbstract.prototype.run = function (em, sender, options) { };
    /**
     * Method that stop command
     * @param  {Object}  em Editor model
     * @param  {Object}  sender  Button sender
     * @private
     * */
    CommandAbstract.prototype.stop = function (em, sender, options) { };
    return CommandAbstract;
}(_common__WEBPACK_IMPORTED_MODULE_1__/* .Model */ .Hn));
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (CommandAbstract);


/***/ }),

/***/ 180:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var underscore__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(50);
var __spreadArray = (undefined && undefined.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};

var command = {
    run: function (ed, s, opts) {
        var _this = this;
        if (opts === void 0) { opts = {}; }
        var removed = [];
        var components = opts.component || ed.getSelectedAll();
        components = (0,underscore__WEBPACK_IMPORTED_MODULE_0__.isArray)(components) ? __spreadArray([], components, true) : [components];
        components.filter(Boolean).forEach(function (component) {
            var _a, _b;
            if (!component.get('removable')) {
                return _this.em.logWarning('The element is not removable', {
                    component: component,
                });
            }
            removed.push(component);
            var cmp = ((_b = (_a = component.delegate) === null || _a === void 0 ? void 0 : _a.remove) === null || _b === void 0 ? void 0 : _b.call(_a, component)) || component;
            cmp.remove();
        });
        ed.selectRemove(removed);
        return removed;
    },
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (command);


/***/ }),

/***/ 544:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var underscore__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(50);
/* harmony import */ var _utils_Dragger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(668);
var __assign = (undefined && undefined.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};


var evName = 'dmode';
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({
    run: function (editor, sender, opts) {
        var _this = this;
        if (opts === void 0) { opts = {}; }
        (0,underscore__WEBPACK_IMPORTED_MODULE_0__.bindAll)(this, 'setPosition', 'onStart', 'onDrag', 'onEnd', 'getPosition', 'getGuidesStatic', 'renderGuide', 'getGuidesTarget');
        var target = opts.target, event = opts.event, mode = opts.mode, _a = opts.dragger, dragger = _a === void 0 ? {} : _a;
        var el = target.getEl();
        var config = __assign({ doc: el.ownerDocument, onStart: this.onStart, onEnd: this.onEnd, onDrag: this.onDrag, getPosition: this.getPosition, setPosition: this.setPosition, guidesStatic: function () { return _this.guidesStatic; }, guidesTarget: function () { return _this.guidesTarget; } }, dragger);
        this.setupGuides();
        this.opts = opts;
        this.editor = editor;
        this.em = editor.getModel();
        this.target = target;
        this.isTran = mode == 'translate';
        this.guidesContainer = this.getGuidesContainer();
        this.guidesTarget = this.getGuidesTarget();
        this.guidesStatic = this.getGuidesStatic();
        var drg = this.dragger;
        if (!drg) {
            drg = new _utils_Dragger__WEBPACK_IMPORTED_MODULE_1__/* ["default"] */ .Z(config);
            this.dragger = drg;
        }
        else {
            drg.setOptions(config);
        }
        event && drg.start(event);
        this.toggleDrag(1);
        this.em.trigger("".concat(evName, ":start"), this.getEventOpts());
        return drg;
    },
    getEventOpts: function () {
        return {
            mode: this.opts.mode,
            target: this.target,
            guidesTarget: this.guidesTarget,
            guidesStatic: this.guidesStatic,
        };
    },
    stop: function () {
        this.toggleDrag();
    },
    setupGuides: function () {
        (this.guides || []).forEach(function (item) {
            var guide = item.guide;
            guide && guide.parentNode.removeChild(guide);
        });
        this.guides = [];
    },
    getGuidesContainer: function () {
        var _this = this;
        var guidesEl = this.guidesEl;
        if (!guidesEl) {
            var _a = this, editor = _a.editor, em = _a.em, opts_1 = _a.opts;
            var pfx = editor.getConfig().stylePrefix;
            var elInfoX = document.createElement('div');
            var elInfoY = document.createElement('div');
            var guideContent = "<div class=\"".concat(pfx, "guide-info__line ").concat(pfx, "danger-bg\">\n        <div class=\"").concat(pfx, "guide-info__content ").concat(pfx, "danger-color\"></div>\n      </div>");
            guidesEl = document.createElement('div');
            guidesEl.className = "".concat(pfx, "guides");
            elInfoX.className = "".concat(pfx, "guide-info ").concat(pfx, "guide-info__x");
            elInfoY.className = "".concat(pfx, "guide-info ").concat(pfx, "guide-info__y");
            elInfoX.innerHTML = guideContent;
            elInfoY.innerHTML = guideContent;
            guidesEl.appendChild(elInfoX);
            guidesEl.appendChild(elInfoY);
            editor.Canvas.getGlobalToolsEl().appendChild(guidesEl);
            this.guidesEl = guidesEl;
            this.elGuideInfoX = elInfoX;
            this.elGuideInfoY = elInfoY;
            this.elGuideInfoContentX = elInfoX.querySelector(".".concat(pfx, "guide-info__content"));
            this.elGuideInfoContentY = elInfoY.querySelector(".".concat(pfx, "guide-info__content"));
            em.on('canvas:update frame:scroll', (0,underscore__WEBPACK_IMPORTED_MODULE_0__.debounce)(function () {
                var _a;
                _this.updateGuides();
                opts_1.debug && ((_a = _this.guides) === null || _a === void 0 ? void 0 : _a.forEach(function (item) { return _this.renderGuide(item); }));
            }, 200));
        }
        return guidesEl;
    },
    getGuidesStatic: function () {
        var _this = this;
        var result = [];
        var el = this.target.getEl();
        var _a = el.parentNode, parentNode = _a === void 0 ? {} : _a;
        (0,underscore__WEBPACK_IMPORTED_MODULE_0__.each)(parentNode.children, function (item) { return (result = result.concat(el !== item ? _this.getElementGuides(item) : [])); });
        return result.concat(this.getElementGuides(parentNode));
    },
    getGuidesTarget: function () {
        return this.getElementGuides(this.target.getEl());
    },
    updateGuides: function (guides) {
        var _this = this;
        var lastEl;
        var lastPos;
        (guides || this.guides).forEach(function (item) {
            var origin = item.origin;
            var pos = lastEl === origin ? lastPos : _this.getElementPos(origin);
            lastEl = origin;
            lastPos = pos;
            (0,underscore__WEBPACK_IMPORTED_MODULE_0__.each)(_this.getGuidePosUpdate(item, pos), function (val, key) { return (item[key] = val); });
            item.originRect = pos;
        });
    },
    getGuidePosUpdate: function (item, rect) {
        var result = {};
        var top = rect.top, height = rect.height, left = rect.left, width = rect.width;
        switch (item.type) {
            case 't':
                result.y = top;
                break;
            case 'b':
                result.y = top + height;
                break;
            case 'l':
                result.x = left;
                break;
            case 'r':
                result.x = left + width;
                break;
            case 'x':
                result.x = left + width / 2;
                break;
            case 'y':
                result.y = top + height / 2;
                break;
        }
        return result;
    },
    renderGuide: function (item) {
        if (item === void 0) { item = {}; }
        var el = item.guide || document.createElement('div');
        var un = 'px';
        var guideSize = item.active ? 2 : 1;
        var numEl = el.children[0];
        el.style = "position: absolute; background-color: ".concat(item.active ? 'green' : 'red', ";");
        if (!el.children.length) {
            numEl = document.createElement('div');
            numEl.style = 'position: absolute; color: red; padding: 5px; top: 0; left: 0;';
            el.appendChild(numEl);
        }
        if (item.y) {
            el.style.width = '100%';
            el.style.height = "".concat(guideSize).concat(un);
            el.style.top = "".concat(item.y).concat(un);
            el.style.left = 0;
        }
        else {
            el.style.width = "".concat(guideSize).concat(un);
            el.style.height = '100%';
            el.style.left = "".concat(item.x).concat(un);
            el.style.top = "0".concat(un);
        }
        !item.guide && this.guidesContainer.appendChild(el);
        return el;
    },
    getElementPos: function (el) {
        return this.editor.Canvas.getElementPos(el, { noScroll: 1 });
    },
    getElementGuides: function (el) {
        var _this = this;
        var opts = this.opts;
        var originRect = this.getElementPos(el);
        var top = originRect.top, height = originRect.height, left = originRect.left, width = originRect.width;
        // @ts-ignore
        var guides = [
            { type: 't', y: top },
            { type: 'b', y: top + height },
            { type: 'l', x: left },
            { type: 'r', x: left + width },
            { type: 'x', x: left + width / 2 },
            { type: 'y', y: top + height / 2 }, // Mid y
        ].map(function (item) { return (__assign(__assign({}, item), { origin: el, originRect: originRect, guide: opts.debug && _this.renderGuide(item) })); });
        guides.forEach(function (item) { var _a; return (_a = _this.guides) === null || _a === void 0 ? void 0 : _a.push(item); });
        return guides;
    },
    getTranslate: function (transform, axis) {
        if (axis === void 0) { axis = 'x'; }
        var result = 0;
        (transform || '').split(' ').forEach(function (item) {
            var itemStr = item.trim();
            var fn = "translate".concat(axis.toUpperCase(), "(");
            if (itemStr.indexOf(fn) === 0)
                result = parseFloat(itemStr.replace(fn, ''));
        });
        return result;
    },
    setTranslate: function (transform, axis, value) {
        var fn = "translate".concat(axis.toUpperCase(), "(");
        var val = "".concat(fn).concat(value, ")");
        var result = (transform || '')
            .split(' ')
            .map(function (item) {
            var itemStr = item.trim();
            if (itemStr.indexOf(fn) === 0)
                item = val;
            return item;
        })
            .join(' ');
        if (result.indexOf(fn) < 0)
            result += " ".concat(val);
        return result;
    },
    getPosition: function () {
        var _a = this, target = _a.target, isTran = _a.isTran;
        var _b = target.getStyle(), left = _b.left, top = _b.top, transform = _b.transform;
        var x = 0;
        var y = 0;
        if (isTran) {
            x = this.getTranslate(transform);
            y = this.getTranslate(transform, 'y');
        }
        else {
            x = parseFloat(left || 0);
            y = parseFloat(top || 0);
        }
        return { x: x, y: y };
    },
    setPosition: function (_a) {
        var x = _a.x, y = _a.y, end = _a.end, position = _a.position, width = _a.width, height = _a.height;
        var _b = this, target = _b.target, isTran = _b.isTran, em = _b.em;
        var unit = 'px';
        var __p = !end; // Indicate if partial change
        var left = "".concat(parseInt(x, 10)).concat(unit);
        var top = "".concat(parseInt(y, 10)).concat(unit);
        var styleUp = {};
        if (isTran) {
            var transform = target.getStyle()['transform'] || '';
            transform = this.setTranslate(transform, 'x', left);
            transform = this.setTranslate(transform, 'y', top);
            styleUp = { transform: transform, __p: __p };
            target.addStyle(styleUp, { avoidStore: !end });
        }
        else {
            var adds_1 = { position: position, width: width, height: height };
            var style_1 = { left: left, top: top, __p: __p };
            (0,underscore__WEBPACK_IMPORTED_MODULE_0__.keys)(adds_1).forEach(function (add) {
                var prop = adds_1[add];
                if (prop)
                    style_1[add] = prop;
            });
            styleUp = style_1;
            target.addStyle(styleUp, { avoidStore: !end });
        }
        em === null || em === void 0 ? void 0 : em.Styles.__emitCmpStyleUpdate(styleUp, { components: em.getSelected() });
    },
    _getDragData: function () {
        var target = this.target;
        return {
            target: target,
            parent: target.parent(),
            index: target.index(),
        };
    },
    onStart: function (event) {
        var _a = this, target = _a.target, editor = _a.editor, isTran = _a.isTran, opts = _a.opts;
        var center = opts.center, onStart = opts.onStart;
        var Canvas = editor.Canvas;
        var style = target.getStyle();
        var position = 'absolute';
        var relPos = [position, 'relative'];
        onStart && onStart(this._getDragData());
        if (isTran)
            return;
        if (style.position !== position) {
            var _b = Canvas.offset(target.getEl()), left = _b.left, top_1 = _b.top, width = _b.width, height = _b.height;
            var parent_1 = target.parent();
            var parentRel = void 0;
            // Check for the relative parent
            do {
                var pStyle = parent_1.getStyle();
                parentRel = relPos.indexOf(pStyle.position) >= 0 ? parent_1 : null;
                parent_1 = parent_1.parent();
            } while (parent_1 && !parentRel);
            // Center the target to the pointer position (used in Droppable for Blocks)
            if (center) {
                var _c = Canvas.getMouseRelativeCanvas(event), x = _c.x, y = _c.y;
                left = x;
                top_1 = y;
            }
            else if (parentRel) {
                var offsetP = Canvas.offset(parentRel.getEl());
                left = left - offsetP.left;
                top_1 = top_1 - offsetP.top;
            }
            this.setPosition({
                x: left,
                y: top_1,
                width: "".concat(width, "px"),
                height: "".concat(height, "px"),
                position: position,
            });
        }
    },
    onDrag: function () {
        var _this = this;
        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            args[_i] = arguments[_i];
        }
        var _a = this, guidesTarget = _a.guidesTarget, opts = _a.opts;
        var onDrag = opts.onDrag;
        this.updateGuides(guidesTarget);
        opts.debug && guidesTarget.forEach(function (item) { return _this.renderGuide(item); });
        opts.guidesInfo && this.renderGuideInfo(guidesTarget.filter(function (item) { return item.active; }));
        onDrag && onDrag(this._getDragData());
    },
    onEnd: function (ev, dragger, opt) {
        if (opt === void 0) { opt = {}; }
        var _a = this, editor = _a.editor, opts = _a.opts, id = _a.id;
        var onEnd = opts.onEnd;
        onEnd && onEnd(ev, opt, __assign(__assign({ event: ev }, opt), this._getDragData()));
        editor.stopCommand(id);
        this.hideGuidesInfo();
        this.em.trigger("".concat(evName, ":end"), this.getEventOpts());
    },
    hideGuidesInfo: function () {
        var _this = this;
        ['X', 'Y'].forEach(function (item) {
            var guide = _this["elGuideInfo".concat(item)];
            if (guide)
                guide.style.display = 'none';
        });
    },
    /**
     * Render guides with spacing information
     */
    renderGuideInfo: function (guides) {
        var _this = this;
        if (guides === void 0) { guides = []; }
        var guidesStatic = this.guidesStatic;
        this.hideGuidesInfo();
        guides.forEach(function (item) {
            var origin = item.origin, x = item.x;
            var rectOrigin = _this.getElementPos(origin);
            var axis = (0,underscore__WEBPACK_IMPORTED_MODULE_0__.isUndefined)(x) ? 'y' : 'x';
            var isY = axis === 'y';
            var origEdge1 = rectOrigin[isY ? 'left' : 'top'];
            var origEdge1Raw = rectOrigin.rect[isY ? 'left' : 'top'];
            var origEdge2 = isY ? origEdge1 + rectOrigin.width : origEdge1 + rectOrigin.height;
            var origEdge2Raw = isY ? origEdge1Raw + rectOrigin.rect.width : origEdge1Raw + rectOrigin.rect.height;
            var elGuideInfo = _this["elGuideInfo".concat(axis.toUpperCase())];
            var elGuideInfoCnt = _this["elGuideInfoContent".concat(axis.toUpperCase())];
            var guideInfoStyle = elGuideInfo.style;
            // Find the nearest element
            var res = guidesStatic === null || guidesStatic === void 0 ? void 0 : guidesStatic.filter(function (stat) { return stat.type === item.type; }).map(function (stat) {
                var _a = stat.originRect, left = _a.left, width = _a.width, top = _a.top, height = _a.height;
                var statEdge1 = isY ? left : top;
                var statEdge2 = isY ? left + width : top + height;
                return {
                    gap: statEdge2 < origEdge1 ? origEdge1 - statEdge2 : statEdge1 - origEdge2,
                    guide: stat,
                };
            }).filter(function (item) { return item.gap > 0; }).sort(function (a, b) { return a.gap - b.gap; }).map(function (item) { return item.guide; })[0];
            if (res) {
                var _a = res.originRect, left = _a.left, width = _a.width, top_2 = _a.top, height = _a.height, rect = _a.rect;
                var isEdge1 = isY ? left < rectOrigin.left : top_2 < rectOrigin.top;
                var statEdge1 = isY ? left : top_2;
                var statEdge1Raw = isY ? rect.left : rect.top;
                var statEdge2 = isY ? left + width : top_2 + height;
                var statEdge2Raw = isY ? rect.left + rect.width : rect.top + rect.height;
                var posFirst = isY ? item.y : item.x;
                var posSecond = isEdge1 ? statEdge2 : origEdge2;
                var pos2 = "".concat(posFirst, "px");
                var size = isEdge1 ? origEdge1 - statEdge2 : statEdge1 - origEdge2;
                var sizeRaw = isEdge1 ? origEdge1Raw - statEdge2Raw : statEdge1Raw - origEdge2Raw;
                guideInfoStyle.display = '';
                guideInfoStyle[isY ? 'top' : 'left'] = pos2;
                guideInfoStyle[isY ? 'left' : 'top'] = "".concat(posSecond, "px");
                guideInfoStyle[isY ? 'width' : 'height'] = "".concat(size, "px");
                elGuideInfoCnt.innerHTML = "".concat(Math.round(sizeRaw), "px");
                _this.em.trigger("".concat(evName, ":active"), __assign(__assign({}, _this.getEventOpts()), { guide: item, guidesStatic: guidesStatic, matched: res, posFirst: posFirst, posSecond: posSecond, size: size, sizeRaw: sizeRaw, elGuideInfo: elGuideInfo, elGuideInfoCnt: elGuideInfoCnt }));
            }
        });
    },
    toggleDrag: function (enable) {
        var _a = this, ppfx = _a.ppfx, editor = _a.editor;
        var methodCls = enable ? 'add' : 'remove';
        var classes = ["".concat(ppfx, "is__grabbing")];
        var Canvas = editor.Canvas;
        var body = Canvas.getBody();
        classes.forEach(function (cls) { return body.classList[methodCls](cls); });
        Canvas[enable ? 'startAutoscroll' : 'stopAutoscroll']();
    },
});


/***/ }),

/***/ 236:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({
    run: function (ed) {
        if (!ed.Canvas.hasFocus())
            return;
        var toSelect = [];
        ed.getSelectedAll().forEach(function (component) {
            var coll = component.components();
            var next = coll && coll.filter(function (c) { return c.get('selectable'); })[0];
            next && toSelect.push(next);
        });
        toSelect.length && ed.select(toSelect);
    },
});


/***/ }),

/***/ 368:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({
    run: function (ed, snd, opts) {
        if (opts === void 0) { opts = {}; }
        if (!ed.Canvas.hasFocus() && !opts.force)
            return;
        var toSelect = [];
        ed.getSelectedAll().forEach(function (component) {
            var next = component.parent();
            // Recurse through the parent() chain until a selectable parent is found
            while (next && !next.get('selectable')) {
                next = next.parent();
            }
            next && toSelect.push(next);
        });
        toSelect.length && ed.select(toSelect);
    },
});


/***/ }),

/***/ 243:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({
    run: function (ed) {
        if (!ed.Canvas.hasFocus())
            return;
        var toSelect = [];
        ed.getSelectedAll().forEach(function (cmp) {
            var parent = cmp.parent();
            if (!parent)
                return;
            var len = parent.components().length;
            var incr = 0;
            var at = 0;
            var next;
            // Get the next selectable component
            do {
                incr++;
                at = cmp.index() + incr;
                next = at <= len ? parent.getChildAt(at) : null;
            } while (next && !next.get('selectable'));
            toSelect.push(next || cmp);
        });
        toSelect.length && ed.select(toSelect);
    },
});


/***/ }),

/***/ 400:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({
    run: function (ed) {
        if (!ed.Canvas.hasFocus())
            return;
        var toSelect = [];
        ed.getSelectedAll().forEach(function (cmp) {
            var parent = cmp.parent();
            if (!parent)
                return;
            var incr = 0;
            var at = 0;
            var next;
            // Get the first selectable component
            do {
                incr++;
                at = cmp.index() - incr;
                next = at >= 0 ? parent.getChildAt(at) : null;
            } while (next && !next.get('selectable'));
            toSelect.push(next || cmp);
        });
        toSelect.length && ed.select(toSelect);
    },
});


/***/ }),

/***/ 910:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var underscore__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(50);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({
    run: function (ed, s, opts) {
        if (opts === void 0) { opts = {}; }
        var target = opts.target;
        var toRemove = [];
        if (!target.get('styles'))
            return toRemove;
        // Find all components in the project, of the target component type
        var type = target.get('type');
        var wrappers = ed.Pages.getAllWrappers();
        var len = (0,underscore__WEBPACK_IMPORTED_MODULE_0__.flatten)(wrappers.map(function (wrp) { return wrp.findType(type); })).length;
        // Remove component related styles only if there are no more components
        // of that type in the project
        if (!len) {
            var rules = ed.CssComposer.getAll();
            toRemove = rules.filter(function (rule) { return rule.get('group') === "cmp:".concat(type); });
            rules.remove(toRemove);
        }
        return toRemove;
    },
});


/***/ }),

/***/ 744:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
var __spreadArray = (undefined && undefined.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({
    run: function (ed) {
        var em = ed.getModel();
        var models = __spreadArray([], ed.getSelectedAll(), true).map(function (md) { var _a, _b; return ((_b = (_a = md.delegate) === null || _a === void 0 ? void 0 : _a.copy) === null || _b === void 0 ? void 0 : _b.call(_a, md)) || md; }).filter(Boolean);
        models.length && em.set('clipboard', models);
    },
});


/***/ }),

/***/ 457:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _utils_dom__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(491);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({
    run: function (editor, sender, opts) {
        var _this = this;
        if (opts === void 0) { opts = {}; }
        sender && sender.set && sender.set('active', 0);
        var config = editor.getConfig();
        var modal = editor.Modal;
        var pfx = config.stylePrefix;
        this.cm = editor.CodeManager || null;
        if (!this.editors) {
            var oHtmlEd = this.buildEditor('htmlmixed', 'hopscotch', 'HTML');
            var oCsslEd = this.buildEditor('css', 'hopscotch', 'CSS');
            this.htmlEditor = oHtmlEd.model;
            this.cssEditor = oCsslEd.model;
            var editors = (0,_utils_dom__WEBPACK_IMPORTED_MODULE_0__/* .createEl */ .ut)('div', { class: "".concat(pfx, "export-dl") });
            editors.appendChild(oHtmlEd.el);
            editors.appendChild(oCsslEd.el);
            this.editors = editors;
        }
        modal
            .open({
            title: config.textViewCode,
            content: this.editors,
        })
            .getModel()
            .once('change:open', function () { return editor.stopCommand("".concat(_this.id)); });
        this.htmlEditor.setContent(editor.getHtml(opts.optsHtml));
        this.cssEditor.setContent(editor.getCss(opts.optsCss));
    },
    stop: function (editor) {
        var modal = editor.Modal;
        modal && modal.close();
    },
    buildEditor: function (codeName, theme, label) {
        var cm = this.em.CodeManager;
        var model = cm.createViewer({
            label: label,
            codeName: codeName,
            theme: theme,
        });
        var el = new cm.EditorView({
            model: model,
            config: cm.getConfig(),
        }).render().el;
        return { model: model, el: el };
    },
});


/***/ }),

/***/ 975:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var underscore__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(50);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({
    /**
     * Check if fullscreen mode is enabled
     * @return {Boolean}
     */
    isEnabled: function () {
        var d = document;
        // @ts-ignore
        if (d.fullscreenElement || d.webkitFullscreenElement || d.mozFullScreenElement) {
            return true;
        }
        return false;
    },
    /**
     * Enable fullscreen mode and return browser prefix
     * @param  {HTMLElement} el
     * @return {string}
     */
    enable: function (el) {
        var pfx = '';
        if (el.requestFullscreen) {
            el.requestFullscreen();
        }
        else if (el.webkitRequestFullscreen) {
            pfx = 'webkit';
            el.webkitRequestFullscreen();
        }
        else if (el.mozRequestFullScreen) {
            pfx = 'moz';
            el.mozRequestFullScreen();
        }
        else if (el.msRequestFullscreen) {
            el.msRequestFullscreen();
        }
        return pfx;
    },
    /**
     * Disable fullscreen mode
     */
    disable: function () {
        var d = document;
        if (this.isEnabled()) {
            if (d.exitFullscreen)
                d.exitFullscreen();
            else if (d.webkitExitFullscreen)
                d.webkitExitFullscreen();
            else if (d.mozCancelFullScreen)
                d.mozCancelFullScreen();
            else if (d.msExitFullscreen)
                d.msExitFullscreen();
        }
    },
    /**
     * Triggered when the state of the fullscreen is changed. Inside detects if
     * it's enabled
     * @param  {strinf} pfx Browser prefix
     * @param  {Event} e
     */
    fsChanged: function (pfx) {
        if (!this.isEnabled()) {
            this.stopCommand({ sender: this.sender });
            document.removeEventListener("".concat(pfx || '', "fullscreenchange"), this.fsChanged);
        }
    },
    run: function (editor, sender, opts) {
        if (opts === void 0) { opts = {}; }
        this.sender = sender;
        var target = opts.target;
        var targetEl = (0,underscore__WEBPACK_IMPORTED_MODULE_0__.isElement)(target) ? target : document.querySelector(target);
        var pfx = this.enable(targetEl || editor.getContainer());
        this.fsChanged = this.fsChanged.bind(this, pfx);
        document.addEventListener(pfx + 'fullscreenchange', this.fsChanged);
    },
    stop: function (editor, sender) {
        if (sender && sender.set)
            sender.set('active', false);
        this.disable();
    },
});


/***/ }),

/***/ 191:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var underscore__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(50);
/* harmony import */ var _common__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(895);
/* harmony import */ var _utils_dom__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(491);
/* harmony import */ var _SelectComponent__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(407);
/* harmony import */ var _SelectPosition__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(189);





/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ((0,underscore__WEBPACK_IMPORTED_MODULE_0__.extend)({}, _SelectPosition__WEBPACK_IMPORTED_MODULE_1__["default"], _SelectComponent__WEBPACK_IMPORTED_MODULE_2__["default"], {
    init: function (o) {
        _SelectComponent__WEBPACK_IMPORTED_MODULE_2__["default"].init.apply(this, arguments);
        (0,underscore__WEBPACK_IMPORTED_MODULE_0__.bindAll)(this, 'initSorter', 'rollback', 'onEndMove');
        this.opt = o;
        this.hoverClass = this.ppfx + 'highlighter-warning';
        this.badgeClass = this.ppfx + 'badge-warning';
        this.noSelClass = this.ppfx + 'no-select';
    },
    enable: function () {
        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            args[_i] = arguments[_i];
        }
        _SelectComponent__WEBPACK_IMPORTED_MODULE_2__["default"].enable.apply(this, args);
        this.getBadgeEl().addClass(this.badgeClass);
        this.getHighlighterEl().addClass(this.hoverClass);
        var wp = this.$wrapper;
        wp.css('cursor', 'move');
        wp.on('mousedown', this.initSorter);
        // Avoid strange moving behavior
        wp.addClass(this.noSelClass);
    },
    /**
     * Overwrite for doing nothing
     * @private
     */
    toggleClipboard: function () { },
    /**
     * Delegate sorting
     * @param  {Event} e
     * @private
     * */
    initSorter: function (e) {
        var el = (0,_common__WEBPACK_IMPORTED_MODULE_3__["default"])(e.target).data('model');
        var drag = el.get('draggable');
        if (!drag)
            return;
        // Avoid badge showing on move
        this.cacheEl = null;
        this.startSelectPosition(e.target, this.frameEl.contentDocument);
        this.sorter.draggable = drag;
        this.sorter.onEndMove = this.onEndMove.bind(this);
        this.stopSelectComponent();
        this.$wrapper.off('mousedown', this.initSorter);
        (0,_utils_dom__WEBPACK_IMPORTED_MODULE_4__.on)(this.getContentWindow(), 'keydown', this.rollback);
    },
    /**
     * Init sorter from model
     * @param  {Object} model
     * @private
     */
    initSorterFromModel: function (model) {
        var drag = model.get('draggable');
        if (!drag)
            return;
        // Avoid badge showing on move
        this.cacheEl = null;
        // @ts-ignore
        var el = model.view.el;
        this.startSelectPosition(el, this.frameEl.contentDocument);
        this.sorter.draggable = drag;
        this.sorter.onEndMove = this.onEndMoveFromModel.bind(this);
        /*
        this.sorter.setDragHelper(el);
        var dragHelper = this.sorter.dragHelper;
        dragHelper.className = this.ppfx + 'drag-helper';
        dragHelper.innerHTML = '';
        dragHelper.backgroundColor = 'white';
        */
        this.stopSelectComponent();
        (0,_utils_dom__WEBPACK_IMPORTED_MODULE_4__.on)(this.getContentWindow(), 'keydown', this.rollback);
    },
    /**
     * Init sorter from models
     * @param  {Object} model
     * @private
     */
    initSorterFromModels: function (models) {
        // TODO: if one only check for `draggable`
        // Avoid badge showing on move
        this.cacheEl = null;
        var lastModel = models[models.length - 1];
        var frameView = this.em.getCurrentFrame();
        var el = lastModel.getEl(frameView === null || frameView === void 0 ? void 0 : frameView.model);
        var doc = el.ownerDocument;
        this.startSelectPosition(el, doc, { onStart: this.onStart });
        this.sorter.draggable = lastModel.get('draggable');
        this.sorter.toMove = models;
        this.sorter.onMoveClb = this.onDrag;
        this.sorter.onEndMove = this.onEndMoveFromModel.bind(this);
        this.stopSelectComponent();
        (0,_utils_dom__WEBPACK_IMPORTED_MODULE_4__.on)(this.getContentWindow(), 'keydown', this.rollback);
    },
    onEndMoveFromModel: function () {
        (0,_utils_dom__WEBPACK_IMPORTED_MODULE_4__/* .off */ .S1)(this.getContentWindow(), 'keydown', this.rollback);
    },
    /**
     * Callback after sorting
     * @private
     */
    onEndMove: function () {
        this.enable();
        (0,_utils_dom__WEBPACK_IMPORTED_MODULE_4__/* .off */ .S1)(this.getContentWindow(), 'keydown', this.rollback);
    },
    /**
     * Say what to do after the component was selected (selectComponent)
     * @param {Event} e
     * @param {Object} Selected element
     * @private
     * */
    onSelect: function (e, el) { },
    /**
     * Used to bring the previous situation before start moving the component
     * @param {Event} e
     * @param {Boolean} Indicates if rollback in anycase
     * @private
     * */
    rollback: function (e, force) {
        var key = e.which || e.keyCode;
        if (key == 27 || force) {
            this.sorter.moved = false;
            this.sorter.endMove();
        }
        return;
    },
    /**
     * Returns badge element
     * @return {HTMLElement}
     * @private
     */
    getBadgeEl: function () {
        if (!this.$badge)
            this.$badge = (0,_common__WEBPACK_IMPORTED_MODULE_3__["default"])(this.getBadge());
        return this.$badge;
    },
    /**
     * Returns highlighter element
     * @return {HTMLElement}
     * @private
     */
    getHighlighterEl: function () {
        if (!this.$hl)
            this.$hl = (0,_common__WEBPACK_IMPORTED_MODULE_3__["default"])(this.canvas.getHighlighter());
        return this.$hl;
    },
    stop: function () {
        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            args[_i] = arguments[_i];
        }
        // @ts-ignore
        _SelectComponent__WEBPACK_IMPORTED_MODULE_2__["default"].stop.apply(this, args);
        this.getBadgeEl().removeClass(this.badgeClass);
        this.getHighlighterEl().removeClass(this.hoverClass);
        var wp = this.$wrapper;
        wp.css('cursor', '').unbind().removeClass(this.noSelClass);
    },
}));


/***/ }),

/***/ 912:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var underscore__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(50);
/* harmony import */ var _utils_dom__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(491);


/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({
    open: function (content) {
        var _this = this;
        var _a = this, editor = _a.editor, title = _a.title, config = _a.config, am = _a.am;
        var custom = config.custom;
        if ((0,underscore__WEBPACK_IMPORTED_MODULE_0__.isFunction)(custom.open)) {
            return custom.open(am.__customData());
        }
        var Modal = editor.Modal;
        Modal.open({ title: title, content: content }).onceClose(function () { return editor.stopCommand(_this.id); });
    },
    close: function () {
        var custom = this.config.custom;
        if ((0,underscore__WEBPACK_IMPORTED_MODULE_0__.isFunction)(custom.close)) {
            return custom.close(this.am.__customData());
        }
        var Modal = this.editor.Modal;
        Modal && Modal.close();
    },
    run: function (editor, sender, opts) {
        if (opts === void 0) { opts = {}; }
        var am = editor.AssetManager;
        var config = am.getConfig();
        var _a = opts.types, types = _a === void 0 ? [] : _a, accept = opts.accept, select = opts.select;
        this.title = opts.modalTitle || editor.t('assetManager.modalTitle') || '';
        this.editor = editor;
        this.config = config;
        this.am = am;
        am.setTarget(opts.target);
        am.onClick(opts.onClick);
        am.onDblClick(opts.onDblClick);
        am.onSelect(opts.onSelect);
        am.__behaviour({
            select: select,
            types: types,
            options: opts,
        });
        if (config.custom) {
            this.rendered = this.rendered || (0,_utils_dom__WEBPACK_IMPORTED_MODULE_1__/* .createEl */ .ut)('div');
            this.rendered.className = "".concat(config.stylePrefix, "custom-wrp");
            am.__behaviour({ container: this.rendered });
            am.__trgCustom();
        }
        else {
            if (!this.rendered || types) {
                var assets = am.getAll().filter(function (i) { return i; });
                if (types && types.length) {
                    assets = assets.filter(function (a) { return types.indexOf(a.get('type')) !== -1; });
                }
                am.render(assets);
                this.rendered = am.getContainer();
            }
            if (accept) {
                var uploadEl = this.rendered.querySelector("input#".concat(config.stylePrefix, "uploadFile"));
                uploadEl && uploadEl.setAttribute('accept', accept);
            }
        }
        this.open(this.rendered);
        return this;
    },
    stop: function (editor) {
        this.editor = editor;
        this.close(this.rendered);
    },
});


/***/ }),

/***/ 117:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var underscore__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(50);
/* harmony import */ var _utils_dom__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(491);


/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({
    open: function () {
        var _a = this, container = _a.container, editor = _a.editor, bm = _a.bm, config = _a.config;
        var custom = config.custom, appendTo = config.appendTo;
        if ((0,underscore__WEBPACK_IMPORTED_MODULE_0__.isFunction)(custom.open)) {
            return custom.open(bm.__customData());
        }
        if (this.firstRender && !appendTo) {
            var id = 'views-container';
            var pn = editor.Panels;
            var panels = pn.getPanel(id) || pn.addPanel({ id: id });
            panels.set('appendContent', container).trigger('change:appendContent');
            if (!custom)
                container.appendChild(bm.render());
        }
        if (container)
            container.style.display = 'block';
    },
    close: function () {
        var _a = this, container = _a.container, config = _a.config;
        var custom = config.custom;
        if ((0,underscore__WEBPACK_IMPORTED_MODULE_0__.isFunction)(custom.close)) {
            return custom.close(this.bm.__customData());
        }
        if (container)
            container.style.display = 'none';
    },
    run: function (editor) {
        var bm = editor.Blocks;
        this.config = bm.getConfig();
        this.firstRender = !this.container;
        this.container = this.container || (0,_utils_dom__WEBPACK_IMPORTED_MODULE_1__/* .createEl */ .ut)('div');
        this.editor = editor;
        this.bm = bm;
        var container = this.container;
        bm.__behaviour({
            container: container,
        });
        if (this.config.custom) {
            bm.__trgCustom();
        }
        this.open();
    },
    stop: function () {
        this.close();
    },
});


/***/ }),

/***/ 614:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({
    run: function (editor) {
        var lm = editor.LayerManager;
        var pn = editor.Panels;
        var lmConfig = lm.getConfig();
        if (lmConfig.appendTo)
            return;
        if (!this.layers) {
            var id = 'views-container';
            var layers = document.createElement('div');
            // @ts-ignore
            var panels = pn.getPanel(id) || pn.addPanel({ id: id });
            if (lmConfig.custom) {
                lm.__trgCustom({ container: layers });
            }
            else {
                layers.appendChild(lm.render());
            }
            panels.set('appendContent', layers).trigger('change:appendContent');
            this.layers = layers;
        }
        this.layers.style.display = 'block';
    },
    stop: function () {
        var layers = this.layers;
        layers && (layers.style.display = 'none');
    },
});


/***/ }),

/***/ 801:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _common__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(895);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({
    run: function (editor, sender) {
        this.sender = sender;
        if (!this.$cnt) {
            var config = editor.getConfig();
            var Panels = editor.Panels, DeviceManager = editor.DeviceManager, SelectorManager = editor.SelectorManager, StyleManager = editor.StyleManager;
            var trgEvCnt = 'change:appendContent';
            var $cnt = (0,_common__WEBPACK_IMPORTED_MODULE_0__["default"])('<div></div>');
            var $cntInner = (0,_common__WEBPACK_IMPORTED_MODULE_0__["default"])('<div></div>');
            var $cntSlm = (0,_common__WEBPACK_IMPORTED_MODULE_0__["default"])('<div></div>');
            var $cntSm = (0,_common__WEBPACK_IMPORTED_MODULE_0__["default"])('<div></div>');
            this.$cnt = $cnt;
            this.$cntInner = $cntInner;
            $cntInner.append($cntSlm);
            $cntInner.append($cntSm);
            $cnt.append($cntInner);
            // Device Manager
            if (DeviceManager && config.showDevices) {
                var devicePanel = Panels.addPanel({ id: 'devices-c' });
                var dvEl = DeviceManager.render();
                devicePanel.set('appendContent', dvEl).trigger(trgEvCnt);
            }
            // Selector Manager container
            var slmConfig = SelectorManager.getConfig();
            if (slmConfig.custom) {
                SelectorManager.__trgCustom({ container: $cntSlm.get(0) });
            }
            else if (!slmConfig.appendTo) {
                $cntSlm.append(SelectorManager.render([]));
            }
            // Style Manager
            this.sm = StyleManager;
            var smConfig = StyleManager.getConfig();
            var pfx = smConfig.stylePrefix;
            this.$header = (0,_common__WEBPACK_IMPORTED_MODULE_0__["default"])("<div class=\"".concat(pfx, "header\">").concat(editor.t('styleManager.empty'), "</div>"));
            $cnt.append(this.$header);
            if (smConfig.custom) {
                StyleManager.__trgCustom({ container: $cntSm.get(0) });
            }
            else if (!smConfig.appendTo) {
                $cntSm.append(StyleManager.render());
            }
            // Create panel if not exists
            var pnCnt = 'views-container';
            var pnl = Panels.getPanel(pnCnt) || Panels.addPanel({ id: pnCnt });
            // Add all containers to the panel
            pnl.set('appendContent', $cnt).trigger(trgEvCnt);
            // Toggle Style Manager on target selection
            var em = editor.getModel();
            this.listenTo(em, StyleManager.events.target, this.toggleSm);
        }
        this.toggleSm();
    },
    /**
     * Toggle Style Manager visibility
     * @private
     */
    toggleSm: function () {
        var _a = this, sender = _a.sender, sm = _a.sm, $cntInner = _a.$cntInner, $header = _a.$header;
        if ((sender && sender.get && !sender.get('active')) || !sm)
            return;
        if (sm.getSelected()) {
            $cntInner === null || $cntInner === void 0 ? void 0 : $cntInner.show();
            $header === null || $header === void 0 ? void 0 : $header.hide();
        }
        else {
            $cntInner === null || $cntInner === void 0 ? void 0 : $cntInner.hide();
            $header === null || $header === void 0 ? void 0 : $header.show();
        }
    },
    stop: function () {
        var _a, _b;
        (_a = this.$cntInner) === null || _a === void 0 ? void 0 : _a.hide();
        (_b = this.$header) === null || _b === void 0 ? void 0 : _b.hide();
    },
});


/***/ }),

/***/ 395:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _common__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(895);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({
    run: function (editor, sender) {
        this.sender = sender;
        var em = editor.getModel();
        var config = editor.Config;
        var pfx = config.stylePrefix;
        var tm = editor.TraitManager;
        var confTm = tm.getConfig();
        var panelC;
        if (confTm.appendTo)
            return;
        if (!this.$cn) {
            this.$cn = (0,_common__WEBPACK_IMPORTED_MODULE_0__["default"])('<div></div>');
            this.$cn2 = (0,_common__WEBPACK_IMPORTED_MODULE_0__["default"])('<div></div>');
            this.$cn.append(this.$cn2);
            this.$header = (0,_common__WEBPACK_IMPORTED_MODULE_0__["default"])('<div>').append("<div class=\"".concat(confTm.stylePrefix, "header\">").concat(em.t('traitManager.empty'), "</div>"));
            this.$cn.append(this.$header);
            if (confTm.custom) {
                tm.__trgCustom({ container: this.$cn2.get(0) });
            }
            else {
                this.$cn2.append("<div class=\"".concat(pfx, "traits-label\">").concat(em.t('traitManager.label'), "</div>"));
                this.$cn2.append(tm.render());
            }
            var panels = editor.Panels;
            if (!panels.getPanel('views-container')) {
                // @ts-ignore
                panelC = panels.addPanel({ id: 'views-container' });
            }
            else {
                panelC = panels.getPanel('views-container');
            }
            panelC === null || panelC === void 0 ? void 0 : panelC.set('appendContent', this.$cn.get(0)).trigger('change:appendContent');
            this.target = editor.getModel();
            this.listenTo(this.target, 'component:toggled', this.toggleTm);
        }
        this.toggleTm();
    },
    /**
     * Toggle Trait Manager visibility
     * @private
     */
    toggleTm: function () {
        var sender = this.sender;
        if (sender && sender.get && !sender.get('active'))
            return;
        if (this.target.getSelectedAll().length === 1) {
            this.$cn2.show();
            this.$header.hide();
        }
        else {
            this.$cn2.hide();
            this.$header.show();
        }
    },
    stop: function () {
        this.$cn2 && this.$cn2.hide();
        this.$header && this.$header.hide();
    },
});


/***/ }),

/***/ 98:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var underscore__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(50);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({
    run: function (ed, s, opts) {
        if (opts === void 0) { opts = {}; }
        var em = ed.getModel();
        var clp = em.get('clipboard');
        var lastSelected = ed.getSelected();
        if ((clp === null || clp === void 0 ? void 0 : clp.length) && lastSelected) {
            ed.getSelectedAll().forEach(function (sel) {
                var _a, _b, _c;
                var selected = ((_b = (_a = sel.delegate) === null || _a === void 0 ? void 0 : _a.copy) === null || _b === void 0 ? void 0 : _b.call(_a, sel)) || sel;
                var collection = selected.collection;
                var added;
                if (collection) {
                    var at = selected.index() + 1;
                    var addOpts = { at: at, action: opts.action || 'paste-component' };
                    if ((0,underscore__WEBPACK_IMPORTED_MODULE_0__.contains)(clp, selected) && selected.get('copyable')) {
                        added = collection.add(selected.clone(), addOpts);
                    }
                    else {
                        added = doAdd(ed, clp, selected.parent(), addOpts);
                    }
                }
                else {
                    // Page body is selected
                    // Paste at the end of the body
                    var pageBody = (_c = em.Pages.getSelected()) === null || _c === void 0 ? void 0 : _c.getMainComponent();
                    var addOpts = { at: (pageBody === null || pageBody === void 0 ? void 0 : pageBody.components().length) || 0, action: opts.action || 'paste-component' };
                    added = doAdd(ed, clp, pageBody, addOpts);
                }
                added = (0,underscore__WEBPACK_IMPORTED_MODULE_0__.isArray)(added) ? added : [added];
                added.forEach(function (add) { return ed.trigger('component:paste', add); });
            });
            lastSelected.emitUpdate();
        }
    },
});
function doAdd(ed, clp, parent, addOpts) {
    var copyable = clp.filter(function (cop) { return cop.get('copyable'); });
    var pasteable = copyable.filter(function (cop) { return ed.Components.canMove(parent, cop).result; });
    return parent.components().add(pasteable.map(function (cop) { return cop.clone(); }), addOpts);
}


/***/ }),

/***/ 129:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var underscore__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(50);
var __spreadArray = (undefined && undefined.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};

var cmdOutline = 'core:component-outline';
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({
    getPanels: function (editor) {
        if (!this.panels) {
            this.panels = editor.Panels.getPanels();
        }
        return this.panels;
    },
    preventDrag: function (opts) {
        opts.abort = 1;
    },
    tglEffects: function (on) {
        var em = this.em;
        var mthEv = on ? 'on' : 'off';
        if (em) {
            var canvas = em.Canvas;
            var body = canvas.getBody();
            var tlb = canvas.getToolbarEl();
            tlb && (tlb.style.display = on ? 'none' : '');
            var elP = body.querySelectorAll(".".concat(this.ppfx, "no-pointer"));
            (0,underscore__WEBPACK_IMPORTED_MODULE_0__.each)(elP, function (item) { return (item.style.pointerEvents = on ? 'all' : ''); });
            em[mthEv]('run:tlb-move:before', this.preventDrag);
        }
    },
    run: function (editor, sender) {
        var _this = this;
        this.sender = sender;
        this.selected = __spreadArray([], editor.getSelectedAll(), true);
        editor.select();
        if (!this.shouldRunSwVisibility) {
            this.shouldRunSwVisibility = editor.Commands.isActive(cmdOutline);
        }
        this.shouldRunSwVisibility && editor.stopCommand(cmdOutline);
        editor.getModel().stopDefault();
        var panels = this.getPanels(editor);
        var canvas = editor.Canvas.getElement();
        var editorEl = editor.getEl();
        var pfx = editor.Config.stylePrefix;
        if (!this.helper) {
            var helper = document.createElement('span');
            helper.className = "".concat(pfx, "off-prv fa fa-eye-slash");
            editorEl.appendChild(helper);
            helper.onclick = function () { return _this.stopCommand(); };
            this.helper = helper;
        }
        this.helper.style.display = 'inline-block';
        panels.forEach(function (panel) { return panel.set('visible', false); });
        var canvasS = canvas.style;
        canvasS.width = '100%';
        canvasS.height = '100%';
        canvasS.top = '0';
        canvasS.left = '0';
        canvasS.padding = '0';
        canvasS.margin = '0';
        editor.refresh();
        this.tglEffects(1);
    },
    stop: function (editor) {
        var _a = this, _b = _a.sender, sender = _b === void 0 ? {} : _b, selected = _a.selected;
        sender.set && sender.set('active', 0);
        var panels = this.getPanels(editor);
        if (this.shouldRunSwVisibility) {
            editor.runCommand(cmdOutline);
            this.shouldRunSwVisibility = false;
        }
        editor.getModel().runDefault();
        panels.forEach(function (panel) { return panel.set('visible', true); });
        var canvas = editor.Canvas.getElement();
        canvas.setAttribute('style', '');
        selected && editor.select(selected);
        delete this.selected;
        if (this.helper) {
            this.helper.style.display = 'none';
        }
        editor.refresh();
        this.tglEffects();
    },
});


/***/ }),

/***/ 116:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
var __assign = (undefined && undefined.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({
    run: function (editor, sender, opts) {
        var opt = opts || {};
        var canvas = editor.Canvas;
        var canvasView = canvas.getCanvasView();
        var options = __assign({ appendTo: canvas.getResizerEl(), prefix: editor.getConfig().stylePrefix, posFetcher: canvasView.getElementPos.bind(canvasView), mousePosFetcher: canvas.getMouseRelativePos.bind(canvas) }, (opt.options || {}));
        var canvasResizer = this.canvasResizer;
        // Create the resizer for the canvas if not yet created
        if (!canvasResizer || opt.forceNew) {
            this.canvasResizer = new editor.Utils.Resizer(options);
            canvasResizer = this.canvasResizer;
        }
        canvasResizer.setOptions(options, true);
        canvasResizer.blur();
        canvasResizer.focus(opt.el);
        return canvasResizer;
    },
    stop: function () {
        var _a;
        (_a = this.canvasResizer) === null || _a === void 0 ? void 0 : _a.blur();
    },
});


/***/ }),

/***/ 407:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  "default": () => (/* binding */ SelectComponent)
});

// EXTERNAL MODULE: ./node_modules/underscore/modules/index-all.js + 160 modules
var index_all = __webpack_require__(50);
// EXTERNAL MODULE: ./src/common/index.ts
var common = __webpack_require__(346);
;// CONCATENATED MODULE: ./src/dom_components/model/ToolbarButton.ts
var __extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();

var ToolbarButton = /** @class */ (function (_super) {
    __extends(ToolbarButton, _super);
    function ToolbarButton() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    ToolbarButton.prototype.defaults = function () {
        return {
            command: '',
            attributes: {},
        };
    };
    return ToolbarButton;
}(common/* Model */.Hn));
/* harmony default export */ const model_ToolbarButton = (ToolbarButton);

;// CONCATENATED MODULE: ./src/dom_components/model/Toolbar.ts
var Toolbar_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();


var Toolbar = /** @class */ (function (_super) {
    Toolbar_extends(Toolbar, _super);
    function Toolbar() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    return Toolbar;
}(common/* Collection */.FE));
/* harmony default export */ const model_Toolbar = (Toolbar);
Toolbar.prototype.model = model_ToolbarButton;

// EXTERNAL MODULE: ./src/domain_abstract/view/DomainViews.ts
var DomainViews = __webpack_require__(330);
;// CONCATENATED MODULE: ./src/dom_components/view/ToolbarButtonView.ts
var ToolbarButtonView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __assign = (undefined && undefined.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};


var ToolbarButtonView = /** @class */ (function (_super) {
    ToolbarButtonView_extends(ToolbarButtonView, _super);
    function ToolbarButtonView(props) {
        var _this = _super.call(this, props) || this;
        _this.em = props.config.em;
        return _this;
    }
    ToolbarButtonView.prototype.events = function () {
        return (this.model.get('events') || {
            mousedown: 'handleClick',
        });
    };
    // @ts-ignore
    ToolbarButtonView.prototype.attributes = function () {
        return this.model.get('attributes');
    };
    ToolbarButtonView.prototype.handleClick = function (event) {
        event.preventDefault();
        event.stopPropagation();
        /*
         * Since the toolbar lives outside the canvas frame, the event's
         * generated on it have clientX and clientY relative to the page.
         *
         * This causes issues during events like dragging, where they depend
         * on the clientX and clientY.
         *
         * This makes sure the offsets are calculated.
         *
         * More information on
         * https://github.com/GrapesJS/grapesjs/issues/2372
         * https://github.com/GrapesJS/grapesjs/issues/2207
         */
        var em = this.em;
        var _a = em.Canvas.getFrameEl().getBoundingClientRect(), left = _a.left, top = _a.top;
        var ev = __assign(__assign({}, event), { clientX: event.clientX - left, clientY: event.clientY - top });
        em.trigger('toolbar:run:before', { event: ev });
        this.execCommand(ev);
    };
    ToolbarButtonView.prototype.execCommand = function (event) {
        var _a = this, em = _a.em, model = _a.model;
        var opts = { event: event };
        var command = model.get('command');
        var editor = em.Editor;
        if ((0,index_all.isFunction)(command)) {
            command(editor, null, opts);
        }
        if ((0,index_all.isString)(command)) {
            editor.runCommand(command, opts);
        }
    };
    ToolbarButtonView.prototype.render = function () {
        var _a = this, em = _a.em, $el = _a.$el, model = _a.model;
        var id = model.get('id');
        var label = model.get('label');
        var pfx = em.getConfig().stylePrefix;
        $el.addClass("".concat(pfx, "toolbar-item"));
        id && $el.addClass("".concat(pfx, "toolbar-item__").concat(id));
        label && $el.append(label);
        return this;
    };
    return ToolbarButtonView;
}(common/* View */.G7));
/* harmony default export */ const view_ToolbarButtonView = (ToolbarButtonView);

;// CONCATENATED MODULE: ./src/dom_components/view/ToolbarView.ts
var ToolbarView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();


var ToolbarView = /** @class */ (function (_super) {
    ToolbarView_extends(ToolbarView, _super);
    function ToolbarView(opts) {
        var _this = _super.call(this, opts) || this;
        var em = opts.em;
        _this.em = em;
        _this.config = { em: em };
        _this.listenTo(_this.collection, 'reset', _this.render);
        return _this;
    }
    ToolbarView.prototype.onRender = function () {
        var pfx = this.em.config.stylePrefix;
        this.el.className = "".concat(pfx, "toolbar-items");
    };
    return ToolbarView;
}(DomainViews/* default */.Z));
/* harmony default export */ const view_ToolbarView = (ToolbarView);
// @ts-ignore
ToolbarView.prototype.itemView = view_ToolbarButtonView;

// EXTERNAL MODULE: ./src/utils/dom.ts
var dom = __webpack_require__(491);
// EXTERNAL MODULE: ./src/utils/mixins.ts
var mixins = __webpack_require__(163);
// EXTERNAL MODULE: ./src/canvas/model/CanvasSpot.ts
var CanvasSpot = __webpack_require__(675);
;// CONCATENATED MODULE: ./src/commands/view/SelectComponent.ts
var SelectComponent_assign = (undefined && undefined.__assign) || function () {
    SelectComponent_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return SelectComponent_assign.apply(this, arguments);
};
var __rest = (undefined && undefined.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};






var showOffsets;
/**
 * This command is responsible for show selecting components and displaying
 * all the necessary tools around (component toolbar, badge, highlight box, etc.)
 *
 * The command manages different boxes to display tools and when something in
 * the canvas is updated, the command triggers the appropriate method to update
 * their position (across multiple frames/components):
 * - Global Tools (updateToolsGlobal/updateGlobalPos)
 * This box contains tools intended to be displayed only on ONE component per time,
 * like Component Toolbar (updated by updateToolbar/updateToolbarPos), this means
 * you won't be able to see more than one Component Toolbar (even with multiple
 * frames or multiple selected components)
 * - Local Tools (updateToolsLocal/updateLocalPos)
 * Each frame in the canvas has its own local box, so we're able to see more than
 * one active container at the same time. When you put a mouse over an element
 * you can see stuff like the highlight box, badge, margins/paddings offsets, etc.
 * so those elements are inside the Local Tools box
 *
 *
 */
/* harmony default export */ const SelectComponent = ({
    activeResizer: false,
    init: function () {
        this.onSelect = (0,index_all.debounce)(this.onSelect, 0);
        (0,index_all.bindAll)(this, 'onHover', 'onOut', 'onClick', 'onFrameScroll', 'onFrameResize', 'onFrameUpdated', 'onContainerChange');
    },
    enable: function () {
        this.frameOff = this.canvasOff = this.adjScroll = null;
        this.startSelectComponent();
        showOffsets = true;
    },
    /**
     * Start select component event
     * @private
     * */
    startSelectComponent: function () {
        this.toggleSelectComponent(1);
        this.em.getSelected() && this.onSelect();
    },
    /**
     * Stop select component event
     * @private
     * */
    stopSelectComponent: function () {
        this.toggleSelectComponent();
    },
    /**
     * Toggle select component event
     * @private
     * */
    toggleSelectComponent: function (enable) {
        var _this = this;
        var em = this.em;
        var listenToEl = em.getConfig().listenToEl;
        var parentNode = em.getContainer().parentNode;
        var method = enable ? 'on' : 'off';
        var methods = { on: dom.on, off: dom/* off */.S1 };
        !listenToEl.length && parentNode && listenToEl.push(parentNode);
        var trigger = function (win, body) {
            methods[method](body, 'mouseover', _this.onHover);
            methods[method](body, 'mouseleave', _this.onOut);
            methods[method](body, 'click', _this.onClick);
            methods[method](win, 'scroll', _this.onFrameScroll, true);
            methods[method](win, 'resize', _this.onFrameResize);
        };
        methods[method](window, 'resize', this.onFrameUpdated);
        methods[method](listenToEl, 'scroll', this.onContainerChange);
        em[method]('component:toggled component:update undo redo', this.onSelect, this);
        em[method]('change:componentHovered', this.onHovered, this);
        em[method]('component:resize styleable:change component:input', this.updateGlobalPos, this);
        em[method]('component:update:toolbar', this._upToolbar, this);
        em[method]('frame:updated', this.onFrameUpdated, this);
        em[method]('canvas:updateTools', this.onFrameUpdated, this);
        em[method](em.Canvas.events.refresh, this.updateAttached, this);
        em.Canvas.getFrames().forEach(function (frame) {
            var view = frame.view;
            var win = view === null || view === void 0 ? void 0 : view.getWindow();
            win && trigger(win, view === null || view === void 0 ? void 0 : view.getBody());
        });
    },
    /**
     * Hover command
     * @param {Object}  e
     * @private
     */
    onHover: function (ev) {
        ev.stopPropagation();
        var em = this.em;
        var el = ev.target;
        var view = (0,mixins.getComponentView)(el);
        var frameView = view === null || view === void 0 ? void 0 : view.frameView;
        var model = view === null || view === void 0 ? void 0 : view.model;
        // Get first valid model
        if (!model) {
            var parentEl = el.parentNode;
            while (!model && parentEl && !(0,dom/* isDoc */.Mx)(parentEl)) {
                model = (0,mixins.getComponentModel)(parentEl);
                parentEl = parentEl.parentNode;
            }
        }
        this.currentDoc = el.ownerDocument;
        em.setHovered(model, { useValid: true });
        frameView && em.setCurrentFrame(frameView);
    },
    onFrameUpdated: function () {
        this.updateLocalPos();
        this.updateGlobalPos();
    },
    onHovered: function (em, component) {
        var _this = this;
        var _a;
        var result = {};
        if (component) {
            (_a = component.views) === null || _a === void 0 ? void 0 : _a.forEach(function (view) {
                var el = view.el;
                var pos = _this.getElementPos(el);
                result = { el: el, pos: pos, component: component, view: (0,mixins.getViewEl)(el) };
                if (el.ownerDocument === _this.currentDoc) {
                    _this.elHovered = result;
                }
                _this.updateToolsLocal(result);
            });
        }
        else {
            this.currentDoc = null;
            this.elHovered = 0;
            this.updateToolsLocal();
            this.canvas.getFrames().forEach(function (frame) {
                var view = frame.view;
                var el = view && view.getToolsEl();
                el && _this.toggleToolsEl(0, 0, { el: el });
            });
        }
    },
    /**
     * Say what to do after the component was selected
     * @param {Object}  e
     * @param {Object}  el
     * @private
     * */
    onSelect: function () {
        var em = this.em;
        var component = em.getSelected();
        var currentFrame = em.getCurrentFrame();
        var view = component && component.getView(currentFrame === null || currentFrame === void 0 ? void 0 : currentFrame.model);
        var el = view && view.el;
        var result = {};
        if (el && (0,dom/* isVisible */.pn)(el)) {
            var pos = this.getElementPos(el);
            result = { el: el, pos: pos, component: component, view: (0,mixins.getViewEl)(el) };
        }
        this.elSelected = result;
        this.updateToolsGlobal();
        // This will hide some elements from the select component
        this.updateLocalPos(result);
        this.initResize(component);
    },
    updateGlobalPos: function () {
        var sel = this.getElSelected();
        if (!sel.el)
            return;
        sel.pos = this.getElementPos(sel.el);
        this.updateToolsGlobal();
    },
    updateLocalPos: function (data) {
        var sel = this.getElHovered();
        if (!sel.el)
            return;
        sel.pos = this.getElementPos(sel.el);
        this.updateToolsLocal(data);
    },
    getElHovered: function () {
        return this.elHovered || {};
    },
    getElSelected: function () {
        return this.elSelected || {};
    },
    onOut: function () {
        this.em.setHovered();
    },
    toggleToolsEl: function (on, view, opts) {
        if (opts === void 0) { opts = {}; }
        var el = opts.el || this.canvas.getToolsEl(view);
        el && (el.style.display = on ? '' : 'none');
        return el || {};
    },
    /**
     * Show element offset viewer
     * @param {HTMLElement}  el
     * @param {Object} pos
     */
    showElementOffset: function (el, pos, opts) {
        if (opts === void 0) { opts = {}; }
        if (!showOffsets)
            return;
        this.editor.runCommand('show-offset', {
            el: el,
            elPos: pos,
            view: opts.view,
            force: 1,
            top: 0,
            left: 0,
        });
    },
    /**
     * Hide element offset viewer
     * @param {HTMLElement}  el
     * @param {Object} pos
     */
    hideElementOffset: function (view) {
        this.editor.stopCommand('show-offset', {
            view: view,
        });
    },
    /**
     * Show fixed element offset viewer
     * @param {HTMLElement}  el
     * @param {Object} pos
     */
    showFixedElementOffset: function (el, pos) {
        this.editor.runCommand('show-offset', {
            el: el,
            elPos: pos,
            state: 'Fixed',
        });
    },
    /**
     * Hide fixed element offset viewer
     * @param {HTMLElement}  el
     * @param {Object} pos
     */
    hideFixedElementOffset: function () {
        if (this.editor)
            this.editor.stopCommand('show-offset', { state: 'Fixed' });
    },
    /**
     * Hide Highlighter element
     */
    hideHighlighter: function (view) {
        this.canvas.getHighlighter(view).style.opacity = 0;
    },
    /**
     * On element click
     * @param {Event}  e
     * @private
     */
    onClick: function (ev) {
        ev.stopPropagation();
        ev.preventDefault();
        var em = this.em;
        if (em.get('_cmpDrag'))
            return em.set('_cmpDrag');
        var el = ev.target;
        var model = (0,mixins.getComponentModel)(el);
        if (!model) {
            var parentEl = el.parentNode;
            while (!model && parentEl && !(0,dom/* isDoc */.Mx)(parentEl)) {
                model = (0,mixins.getComponentModel)(parentEl);
                parentEl = parentEl.parentNode;
            }
        }
        if (model) {
            // Avoid selection of inner text components during editing
            if (em.isEditing() && !model.get('textable') && model.isChildOf('text')) {
                return;
            }
            this.select(model, ev);
        }
    },
    /**
     * Select component
     * @param  {Component} model
     * @param  {Event} event
     */
    select: function (model, event) {
        if (event === void 0) { event = {}; }
        if (!model)
            return;
        this.editor.select(model, { event: event, useValid: true });
        this.initResize(model);
    },
    /**
     * Update badge for the component
     * @param {Object} Component
     * @param {Object} pos Position object
     * @private
     * */
    updateBadge: function (el, pos, opts) {
        if (opts === void 0) { opts = {}; }
        var canvas = this.canvas;
        var model = (0,mixins.getComponentModel)(el);
        var badge = this.getBadge(opts);
        var bStyle = badge.style;
        if (!model || !model.get('badgable')) {
            bStyle.display = 'none';
            return;
        }
        if (!opts.posOnly) {
            var config = this.canvas.getConfig();
            var icon = model.getIcon();
            var ppfx = config.pStylePrefix || '';
            var clsBadge = "".concat(ppfx, "badge");
            var customeLabel = config.customBadgeLabel;
            var badgeLabel = "".concat(icon ? "<div class=\"".concat(clsBadge, "__icon\">").concat(icon, "</div>") : '', "\n        <div class=\"").concat(clsBadge, "__name\">").concat(model.getName(), "</div>");
            badge.innerHTML = customeLabel ? customeLabel(model) : badgeLabel;
        }
        var un = 'px';
        bStyle.display = 'block';
        var targetToElem = canvas.getTargetToElementFixed(el, badge, {
            pos: pos,
        });
        var top = targetToElem.top; //opts.topOff - badgeH < 0 ? -opts.topOff : posTop;
        var left = opts.leftOff < 0 ? -opts.leftOff : 0;
        bStyle.top = top + un;
        bStyle.left = left + un;
    },
    /**
     * Update highlighter element
     * @param {HTMLElement} el
     * @param {Object} pos Position object
     * @private
     */
    showHighlighter: function (view) {
        this.canvas.getHighlighter(view).style.opacity = '';
    },
    /**
     * Init resizer on the element if possible
     * @param  {HTMLElement|Component} elem
     * @private
     */
    initResize: function (elem) {
        var _a = this, em = _a.em, canvas = _a.canvas;
        var editor = em.Editor;
        var model = !(0,index_all.isElement)(elem) && (0,dom/* isTaggableNode */.o5)(elem) ? elem : em.getSelected();
        var resizable = model === null || model === void 0 ? void 0 : model.get('resizable');
        var spotTypeResize = CanvasSpot/* CanvasSpotBuiltInTypes */.q.Resize;
        var hasCustomResize = canvas.hasCustomSpot(spotTypeResize);
        canvas.removeSpots({ type: spotTypeResize });
        if (model && resizable) {
            canvas.addSpot({ type: spotTypeResize, component: model });
            var el = (0,index_all.isElement)(elem) ? elem : model.getEl();
            var _b = (0,mixins.isObject)(resizable) ? resizable : {}, _c = _b.onStart, onStart_1 = _c === void 0 ? function () { } : _c, _d = _b.onMove, onMove_1 = _d === void 0 ? function () { } : _d, _e = _b.onEnd, onEnd_1 = _e === void 0 ? function () { } : _e, _f = _b.updateTarget, updateTarget_1 = _f === void 0 ? function () { } : _f, resizableOpts = __rest(_b, ["onStart", "onMove", "onEnd", "updateTarget"]);
            if (hasCustomResize || !el || this.activeResizer)
                return;
            var modelToStyle_1;
            var config = em.config;
            var pfx = config.stylePrefix || '';
            var resizeClass_1 = "".concat(pfx, "resizing");
            var self_1 = this;
            var resizeEventOpts_1 = {
                component: model,
                el: el,
            };
            var toggleBodyClass_1 = function (method, e, opts) {
                var docs = opts.docs;
                docs &&
                    docs.forEach(function (doc) {
                        var body = doc.body;
                        var cls = body.className || '';
                        body.className = (method == 'add' ? "".concat(cls, " ").concat(resizeClass_1) : cls.replace(resizeClass_1, '')).trim();
                    });
            };
            var options = SelectComponent_assign({ 
                // Here the resizer is updated with the current element height and width
                onStart: function (ev, opts) {
                    onStart_1(ev, opts);
                    var el = opts.el, config = opts.config, resizer = opts.resizer;
                    var keyHeight = config.keyHeight, keyWidth = config.keyWidth, currentUnit = config.currentUnit, keepAutoHeight = config.keepAutoHeight, keepAutoWidth = config.keepAutoWidth;
                    toggleBodyClass_1('add', ev, opts);
                    modelToStyle_1 = em.Styles.getModelToStyle(model);
                    canvas.toggleFramesEvents(false);
                    var computedStyle = getComputedStyle(el);
                    var modelStyle = modelToStyle_1.getStyle();
                    var currentWidth = modelStyle[keyWidth];
                    config.autoWidth = keepAutoWidth && currentWidth === 'auto';
                    if (isNaN(parseFloat(currentWidth))) {
                        currentWidth = computedStyle[keyWidth];
                    }
                    var currentHeight = modelStyle[keyHeight];
                    config.autoHeight = keepAutoHeight && currentHeight === 'auto';
                    if (isNaN(parseFloat(currentHeight))) {
                        currentHeight = computedStyle[keyHeight];
                    }
                    resizer.startDim.w = parseFloat(currentWidth);
                    resizer.startDim.h = parseFloat(currentHeight);
                    showOffsets = false;
                    if (currentUnit) {
                        config.unitHeight = (0,mixins.getUnitFromValue)(currentHeight);
                        config.unitWidth = (0,mixins.getUnitFromValue)(currentWidth);
                    }
                    self_1.activeResizer = true;
                    editor.trigger('component:resize', SelectComponent_assign(SelectComponent_assign({}, resizeEventOpts_1), { type: 'start' }));
                }, 
                // Update all positioned elements (eg. component toolbar)
                onMove: function (ev) {
                    onMove_1(ev);
                    editor.trigger('component:resize', SelectComponent_assign(SelectComponent_assign({}, resizeEventOpts_1), { type: 'move' }));
                }, onEnd: function (ev, opts) {
                    onEnd_1(ev, opts);
                    toggleBodyClass_1('remove', ev, opts);
                    editor.trigger('component:resize', SelectComponent_assign(SelectComponent_assign({}, resizeEventOpts_1), { type: 'end' }));
                    canvas.toggleFramesEvents(true);
                    showOffsets = true;
                    self_1.activeResizer = false;
                }, updateTarget: function (el, rect, options) {
                    updateTarget_1(el, rect, options);
                    if (!modelToStyle_1) {
                        return;
                    }
                    var store = options.store, selectedHandler = options.selectedHandler, config = options.config;
                    var keyHeight = config.keyHeight, keyWidth = config.keyWidth, autoHeight = config.autoHeight, autoWidth = config.autoWidth, unitWidth = config.unitWidth, unitHeight = config.unitHeight;
                    var onlyHeight = ['tc', 'bc'].indexOf(selectedHandler) >= 0;
                    var onlyWidth = ['cl', 'cr'].indexOf(selectedHandler) >= 0;
                    var style = {};
                    if (!onlyHeight) {
                        var bodyw = canvas.getBody().offsetWidth;
                        var width = rect.w < bodyw ? rect.w : bodyw;
                        style[keyWidth] = autoWidth ? 'auto' : "".concat(width).concat(unitWidth);
                    }
                    if (!onlyWidth) {
                        style[keyHeight] = autoHeight ? 'auto' : "".concat(rect.h).concat(unitHeight);
                    }
                    if (em.getDragMode(model)) {
                        style.top = "".concat(rect.t).concat(unitHeight);
                        style.left = "".concat(rect.l).concat(unitWidth);
                    }
                    var finalStyle = SelectComponent_assign(SelectComponent_assign({}, style), { 
                        // value for the partial update
                        __p: !store });
                    modelToStyle_1.addStyle(finalStyle, { avoidStore: !store });
                    em.Styles.__emitCmpStyleUpdate(finalStyle, { components: em.getSelected() });
                } }, resizableOpts);
            this.resizer = editor.runCommand('resize', { el: el, options: options, force: 1 });
        }
        else {
            if (hasCustomResize)
                return;
            editor.stopCommand('resize');
            this.resizer = null;
        }
    },
    /**
     * Update toolbar if the component has one
     * @param {Object} mod
     */
    updateToolbar: function (mod) {
        var canvas = this.canvas;
        var em = this.config.em;
        var model = mod === em ? em.getSelected() : mod;
        var toolbarEl = canvas.getToolbarEl();
        var toolbarStyle = toolbarEl.style;
        var toolbar = model.get('toolbar');
        var showToolbar = em.config.showToolbar;
        var noCustomSpotSelect = !canvas.hasCustomSpot(CanvasSpot/* CanvasSpotBuiltInTypes */.q.Select);
        if (model && showToolbar && toolbar && toolbar.length && noCustomSpotSelect) {
            toolbarStyle.display = '';
            if (!this.toolbar) {
                toolbarEl.innerHTML = '';
                this.toolbar = new model_Toolbar(toolbar);
                // @ts-ignore
                var toolbarView = new view_ToolbarView({ collection: this.toolbar, em: em });
                toolbarEl.appendChild(toolbarView.render().el);
            }
            this.toolbar.reset(toolbar);
            toolbarStyle.top = '-100px';
            toolbarStyle.left = '0';
        }
        else {
            toolbarStyle.display = 'none';
        }
    },
    /**
     * Update toolbar positions
     * @param {HTMLElement} el
     * @param {Object} pos
     */
    updateToolbarPos: function (pos) {
        var unit = 'px';
        var style = this.canvas.getToolbarEl().style;
        style.top = "".concat(pos.top).concat(unit);
        style.left = "".concat(pos.left).concat(unit);
        style.opacity = '';
    },
    /**
     * Return canvas dimensions and positions
     * @return {Object}
     */
    getCanvasPosition: function () {
        return this.canvas.getCanvasView().getPosition();
    },
    /**
     * Returns badge element
     * @return {HTMLElement}
     * @private
     */
    getBadge: function (opts) {
        if (opts === void 0) { opts = {}; }
        return this.canvas.getBadgeEl(opts.view);
    },
    /**
     * On frame scroll callback
     * @private
     */
    onFrameScroll: function () {
        this.updateTools();
        this.canvas.refreshSpots();
    },
    onFrameResize: function () {
        this.canvas.refresh({ all: true });
    },
    updateTools: function () {
        this.updateLocalPos();
        this.updateGlobalPos();
    },
    isCompSelected: function (comp) {
        return comp && comp.get('status') === 'selected';
    },
    /**
     * Update tools visible on hover
     * @param {HTMLElement} el
     * @param {Object} pos
     */
    updateToolsLocal: function (data) {
        var config = this.em.getConfig();
        var _a = data || this.getElHovered(), el = _a.el, pos = _a.pos, view = _a.view, component = _a.component;
        if (!el) {
            this.lastHovered = 0;
            return;
        }
        var isHoverEn = component.get('hoverable');
        var isNewEl = this.lastHovered !== el;
        var badgeOpts = isNewEl ? {} : { posOnly: 1 };
        var customHoverSpot = this.canvas.hasCustomSpot(CanvasSpot/* CanvasSpotBuiltInTypes */.q.Hover);
        if (isNewEl && isHoverEn) {
            this.lastHovered = el;
            customHoverSpot ? this.hideHighlighter(view) : this.showHighlighter(view);
            this.showElementOffset(el, pos, { view: view });
        }
        if (this.isCompSelected(component)) {
            this.hideHighlighter(view);
            !config.showOffsetsSelected && this.hideElementOffset(view);
        }
        var unit = 'px';
        var toolsEl = this.toggleToolsEl(1, view);
        var style = toolsEl.style;
        var frameOff = this.canvas.canvasRectOffset(el, pos);
        var topOff = frameOff.top;
        var leftOff = frameOff.left;
        !customHoverSpot &&
            this.updateBadge(el, pos, SelectComponent_assign(SelectComponent_assign({}, badgeOpts), { view: view, topOff: topOff, leftOff: leftOff }));
        style.top = topOff + unit;
        style.left = leftOff + unit;
        style.width = pos.width + unit;
        style.height = pos.height + unit;
        this._trgToolUp('local', {
            component: component,
            el: toolsEl,
            top: topOff,
            left: leftOff,
            width: pos.width,
            height: pos.height,
        });
    },
    _upToolbar: (0,index_all.debounce)(function () {
        // @ts-ignore
        this.updateToolsGlobal({ force: 1 });
    }, 0),
    _trgToolUp: function (type, opts) {
        if (opts === void 0) { opts = {}; }
        this.em.trigger('canvas:tools:update', SelectComponent_assign({ type: type }, opts));
    },
    updateToolsGlobal: function (opts) {
        if (opts === void 0) { opts = {}; }
        var _a = this.getElSelected(), el = _a.el, pos = _a.pos, component = _a.component;
        if (!el) {
            this.toggleToolsEl(); // Hides toolbar
            this.lastSelected = 0;
            return;
        }
        var canvas = this.canvas;
        var isNewEl = this.lastSelected !== el;
        if (isNewEl || opts.force) {
            this.lastSelected = el;
            this.updateToolbar(component);
        }
        var unit = 'px';
        var toolsEl = this.toggleToolsEl(1);
        var style = toolsEl.style;
        var targetToElem = canvas.getTargetToElementFixed(el, canvas.getToolbarEl(), { pos: pos });
        var topOff = targetToElem.canvasOffsetTop;
        var leftOff = targetToElem.canvasOffsetLeft;
        style.top = topOff + unit;
        style.left = leftOff + unit;
        style.width = pos.width + unit;
        style.height = pos.height + unit;
        this.updateToolbarPos({ top: targetToElem.top, left: targetToElem.left });
        this._trgToolUp('global', {
            component: component,
            el: toolsEl,
            top: topOff,
            left: leftOff,
            width: pos.width,
            height: pos.height,
        });
    },
    /**
     * Update attached elements, eg. component toolbar
     */
    updateAttached: (0,index_all.debounce)(function () {
        // @ts-ignore
        this.updateGlobalPos();
    }, 0),
    onContainerChange: (0,index_all.debounce)(function () {
        // @ts-ignore
        this.em.refreshCanvas();
    }, 150),
    /**
     * Returns element's data info
     * @param {HTMLElement} el
     * @return {Object}
     * @private
     */
    getElementPos: function (el) {
        return this.canvas.getCanvasView().getElementPos(el, { noScroll: true });
    },
    /**
     * Hide badge
     * @private
     * */
    hideBadge: function () {
        this.getBadge().style.display = 'none';
    },
    /**
     * Clean previous model from different states
     * @param {Component} model
     * @private
     */
    cleanPrevious: function (model) {
        model &&
            model.set({
                status: '',
                state: '',
            });
    },
    /**
     * Returns content window
     * @private
     */
    getContentWindow: function () {
        return this.canvas.getWindow();
    },
    run: function (editor) {
        if (!(0,mixins.hasWin)())
            return;
        // @ts-ignore
        this.editor = editor && editor.get('Editor');
        this.enable();
    },
    stop: function (ed, sender, opts) {
        if (opts === void 0) { opts = {}; }
        if (!(0,mixins.hasWin)())
            return;
        var _a = this, em = _a.em, editor = _a.editor;
        this.onHovered(); // force to hide toolbar
        this.stopSelectComponent();
        !opts.preserveSelected && em.setSelected();
        this.toggleToolsEl();
        editor && editor.stopCommand('resize');
    },
});


/***/ }),

/***/ 189:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _common__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(895);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({
    /**
     * Start select position event
     * @param {HTMLElement} trg
     * @private
     * */
    startSelectPosition: function (trg, doc, opts) {
        var _this = this;
        if (opts === void 0) { opts = {}; }
        this.isPointed = false;
        var utils = this.em.Utils;
        var container = trg.ownerDocument.body;
        if (utils && !this.sorter)
            this.sorter = new utils.Sorter({
                // @ts-ignore
                container: container,
                placer: this.canvas.getPlacerEl(),
                containerSel: '*',
                itemSel: '*',
                pfx: this.ppfx,
                direction: 'a',
                document: doc,
                wmargin: 1,
                nested: 1,
                em: this.em,
                canvasRelative: 1,
                scale: function () { return _this.em.getZoomDecimal(); },
            });
        if (opts.onStart)
            this.sorter.onStart = opts.onStart;
        trg && this.sorter.startSort(trg, { container: container });
    },
    /**
     * Get frame position
     * @return {Object}
     * @private
     */
    getOffsetDim: function () {
        var frameOff = this.offset(this.canvas.getFrameEl());
        var canvasOff = this.offset(this.canvas.getElement());
        var top = frameOff.top - canvasOff.top;
        var left = frameOff.left - canvasOff.left;
        return { top: top, left: left };
    },
    /**
     * Stop select position event
     * @private
     * */
    stopSelectPosition: function () {
        this.posTargetCollection = null;
        this.posIndex = this.posMethod == 'after' && this.cDim.length !== 0 ? this.posIndex + 1 : this.posIndex; //Normalize
        if (this.sorter) {
            this.sorter.moved = 0;
            this.sorter.endMove();
        }
        if (this.cDim) {
            this.posIsLastEl = this.cDim.length !== 0 && this.posMethod == 'after' && this.posIndex == this.cDim.length;
            this.posTargetEl =
                this.cDim.length === 0
                    ? (0,_common__WEBPACK_IMPORTED_MODULE_0__["default"])(this.outsideElem)
                    : !this.posIsLastEl && this.cDim[this.posIndex]
                        ? (0,_common__WEBPACK_IMPORTED_MODULE_0__["default"])(this.cDim[this.posIndex][5]).parent()
                        : (0,_common__WEBPACK_IMPORTED_MODULE_0__["default"])(this.outsideElem);
            this.posTargetModel = this.posTargetEl.data('model');
            this.posTargetCollection = this.posTargetEl.data('model-comp');
        }
    },
    /**
     * Enabel select position
     * @private
     */
    enable: function () {
        this.startSelectPosition();
    },
    /**
     * Check if the pointer is near to the float component
     * @param {number} index
     * @param {string} method
     * @param {Array<Array>} dims
     * @return {Boolean}
     * @private
     * */
    nearFloat: function (index, method, dims) {
        var i = index || 0;
        var m = method || 'before';
        var len = dims.length;
        var isLast = len !== 0 && m == 'after' && i == len;
        if (len !== 0 && ((!isLast && !dims[i][4]) || (dims[i - 1] && !dims[i - 1][4]) || (isLast && !dims[i - 1][4])))
            return 1;
        return 0;
    },
    run: function () {
        this.enable();
    },
    stop: function () {
        this.stopSelectPosition();
        this.$wrapper.css('cursor', '');
        this.$wrapper.unbind();
    },
});


/***/ }),

/***/ 804:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var underscore__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(50);
/* harmony import */ var _canvas_model_CanvasSpot__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(675);
/* harmony import */ var _common__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(895);
/* harmony import */ var _utils_dom__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(491);
var __assign = (undefined && undefined.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};




/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({
    getOffsetMethod: function (state) {
        var method = state || '';
        return 'get' + method + 'OffsetViewerEl';
    },
    run: function (editor, sender, opts) {
        var canvas = this.canvas;
        var opt = opts || {};
        var state = opt.state || '';
        var config = editor.getConfig();
        var zoom = this.em.getZoomDecimal();
        var el = opt.el;
        if (!config.showOffsets || !el || (0,_utils_dom__WEBPACK_IMPORTED_MODULE_1__/* .isTextNode */ .BM)(el) || (!config.showOffsetsSelected && state == 'Fixed')) {
            editor.stopCommand("".concat(this.id), opts);
            return;
        }
        if (canvas.hasCustomSpot(_canvas_model_CanvasSpot__WEBPACK_IMPORTED_MODULE_2__/* .CanvasSpotBuiltInTypes */ .q.Spacing)) {
            return;
        }
        var pos = __assign({}, (opt.elPos || canvas.getElementPos(el)));
        if (!(0,underscore__WEBPACK_IMPORTED_MODULE_0__.isUndefined)(opt.top)) {
            pos.top = opt.top;
        }
        if (!(0,underscore__WEBPACK_IMPORTED_MODULE_0__.isUndefined)(opt.left)) {
            pos.left = opt.left;
        }
        var style = window.getComputedStyle(el);
        var ppfx = this.ppfx;
        var stateVar = state + 'State';
        var method = this.getOffsetMethod(state);
        // @ts-ignore
        var offsetViewer = canvas[method](opts.view);
        offsetViewer.style.opacity = '';
        var marginT = this['marginT' + state];
        var marginB = this['marginB' + state];
        var marginL = this['marginL' + state];
        var marginR = this['marginR' + state];
        var padT = this['padT' + state];
        var padB = this['padB' + state];
        var padL = this['padL' + state];
        var padR = this['padR' + state];
        if (offsetViewer.childNodes.length) {
            this[stateVar] = '1';
            marginT = offsetViewer.querySelector('[data-offset-m-t]');
            marginB = offsetViewer.querySelector('[data-offset-m-b]');
            marginL = offsetViewer.querySelector('[data-offset-m-l]');
            marginR = offsetViewer.querySelector('[data-offset-m-r]');
            padT = offsetViewer.querySelector('[data-offset-p-t]');
            padB = offsetViewer.querySelector('[data-offset-p-b]');
            padL = offsetViewer.querySelector('[data-offset-p-l]');
            padR = offsetViewer.querySelector('[data-offset-p-r]');
        }
        if (!this[stateVar]) {
            var stateLow = state.toLowerCase();
            var marginName = stateLow + 'margin-v';
            var paddingName = stateLow + 'padding-v';
            var marginV = (0,_common__WEBPACK_IMPORTED_MODULE_3__["default"])("<div class=\"".concat(ppfx, "marginName\">")).get(0);
            var paddingV = (0,_common__WEBPACK_IMPORTED_MODULE_3__["default"])("<div class=\"".concat(ppfx, "paddingName\">")).get(0);
            var marginEls = ppfx + marginName + '-el';
            var paddingEls = ppfx + paddingName + '-el';
            var fullMargName = "".concat(marginEls, " ").concat(ppfx + marginName);
            var fullPadName = "".concat(paddingEls, " ").concat(ppfx + paddingName);
            marginT = (0,_common__WEBPACK_IMPORTED_MODULE_3__["default"])("<div class=\"".concat(fullMargName, "-top\"></div>")).get(0);
            marginB = (0,_common__WEBPACK_IMPORTED_MODULE_3__["default"])("<div class=\"".concat(fullMargName, "-bottom\"></div>")).get(0);
            marginL = (0,_common__WEBPACK_IMPORTED_MODULE_3__["default"])("<div class=\"".concat(fullMargName, "-left\"></div>")).get(0);
            marginR = (0,_common__WEBPACK_IMPORTED_MODULE_3__["default"])("<div class=\"".concat(fullMargName, "-right\"></div>")).get(0);
            padT = (0,_common__WEBPACK_IMPORTED_MODULE_3__["default"])("<div class=\"".concat(fullPadName, "-top\"></div>")).get(0);
            padB = (0,_common__WEBPACK_IMPORTED_MODULE_3__["default"])("<div class=\"".concat(fullPadName, "-bottom\"></div>")).get(0);
            padL = (0,_common__WEBPACK_IMPORTED_MODULE_3__["default"])("<div class=\"".concat(fullPadName, "-left\"></div>")).get(0);
            padR = (0,_common__WEBPACK_IMPORTED_MODULE_3__["default"])("<div class=\"".concat(fullPadName, "-right\"></div>")).get(0);
            this['marginT' + state] = marginT;
            this['marginB' + state] = marginB;
            this['marginL' + state] = marginL;
            this['marginR' + state] = marginR;
            this['padT' + state] = padT;
            this['padB' + state] = padB;
            this['padL' + state] = padL;
            this['padR' + state] = padR;
            marginV.appendChild(marginT);
            marginV.appendChild(marginB);
            marginV.appendChild(marginL);
            marginV.appendChild(marginR);
            paddingV.appendChild(padT);
            paddingV.appendChild(padB);
            paddingV.appendChild(padL);
            paddingV.appendChild(padR);
            offsetViewer.appendChild(marginV);
            offsetViewer.appendChild(paddingV);
            this[stateVar] = '1';
        }
        var unit = 'px';
        var marginLeftSt = parseFloat(style.marginLeft.replace(unit, '')) * zoom;
        var marginRightSt = parseFloat(style.marginRight.replace(unit, '')) * zoom;
        var marginTopSt = parseFloat(style.marginTop.replace(unit, '')) * zoom;
        var marginBottomSt = parseFloat(style.marginBottom.replace(unit, '')) * zoom;
        var mtStyle = marginT.style;
        var mbStyle = marginB.style;
        var mlStyle = marginL.style;
        var mrStyle = marginR.style;
        var ptStyle = padT.style;
        var pbStyle = padB.style;
        var plStyle = padL.style;
        var prStyle = padR.style;
        var posLeft = parseFloat(pos.left);
        var widthEl = parseFloat(style.width) * zoom + unit;
        // Margin style
        mtStyle.height = marginTopSt + unit;
        mtStyle.width = widthEl;
        mtStyle.top = pos.top - marginTopSt + unit;
        mtStyle.left = posLeft + unit;
        mbStyle.height = marginBottomSt + unit;
        mbStyle.width = widthEl;
        mbStyle.top = pos.top + pos.height + unit;
        mbStyle.left = posLeft + unit;
        var marginSideH = pos.height + marginTopSt + marginBottomSt + unit;
        var marginSideT = pos.top - marginTopSt + unit;
        mlStyle.height = marginSideH;
        mlStyle.width = marginLeftSt + unit;
        mlStyle.top = marginSideT;
        mlStyle.left = posLeft - marginLeftSt + unit;
        mrStyle.height = marginSideH;
        mrStyle.width = marginRightSt + unit;
        mrStyle.top = marginSideT;
        mrStyle.left = posLeft + pos.width + unit;
        // Padding style
        var padTop = parseFloat(style.paddingTop) * zoom;
        ptStyle.height = padTop + unit;
        // ptStyle.width = widthEl;
        // ptStyle.top = pos.top + unit;
        // ptStyle.left = posLeft + unit;
        var padBot = parseFloat(style.paddingBottom) * zoom;
        pbStyle.height = padBot + unit;
        // pbStyle.width = widthEl;
        // pbStyle.top = pos.top + pos.height - padBot + unit;
        // pbStyle.left = posLeft + unit;
        var padSideH = pos.height - padBot - padTop + unit;
        var padSideT = pos.top + padTop + unit;
        plStyle.height = padSideH;
        plStyle.width = parseFloat(style.paddingLeft) * zoom + unit;
        plStyle.top = padSideT;
        // plStyle.left = pos.left + unit;
        //  plStyle.right = 0;
        var padRight = parseFloat(style.paddingRight) * zoom;
        prStyle.height = padSideH;
        prStyle.width = padRight + unit;
        prStyle.top = padSideT;
        // prStyle.left = pos.left + pos.width - padRight + unit;
        //  prStyle.left = 0;
    },
    stop: function (editor, sender, opts) {
        if (opts === void 0) { opts = {}; }
        var opt = opts || {};
        var state = opt.state || '';
        var method = this.getOffsetMethod(state);
        var view = opts.view;
        var canvas = this.canvas;
        // @ts-ignore
        var offsetViewer = canvas[method](view);
        offsetViewer.style.opacity = 0;
    },
});


/***/ }),

/***/ 434:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var underscore__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(50);
/* harmony import */ var _utils_mixins__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(163);


/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({
    init: function () {
        (0,underscore__WEBPACK_IMPORTED_MODULE_0__.bindAll)(this, '_onFramesChange');
    },
    run: function (ed) {
        this.toggleVis(ed, true);
    },
    stop: function (ed) {
        this.toggleVis(ed, false);
    },
    toggleVis: function (ed, active) {
        if (active === void 0) { active = true; }
        if (!ed.Commands.isActive('preview')) {
            var cv = ed.Canvas;
            var mth = active ? 'on' : 'off';
            var canvasModel = cv.getModel();
            canvasModel[mth]('change:frames', this._onFramesChange);
            this.handleFrames(cv.getFrames(), active);
        }
    },
    handleFrames: function (frames, active) {
        var _this = this;
        frames.forEach(function (frame) {
            var _a;
            ((_a = frame.view) === null || _a === void 0 ? void 0 : _a.loaded) && _this._upFrame(frame, active);
            if (!frame.__ol) {
                frame.on('loaded', function () { return _this._upFrame(frame); });
                frame.__ol = true;
            }
        });
    },
    _onFramesChange: function (_, frames) {
        this.handleFrames(frames);
    },
    _upFrame: function (frame, active) {
        var _a;
        var _b = this, ppfx = _b.ppfx, em = _b.em, id = _b.id;
        var isActive = (0,_utils_mixins__WEBPACK_IMPORTED_MODULE_1__.isDef)(active) ? active : em.Commands.isActive(id);
        var method = isActive ? 'add' : 'remove';
        var cls = "".concat(ppfx, "dashed");
        (_a = frame.view) === null || _a === void 0 ? void 0 : _a.getBody().classList[method](cls);
    },
});


/***/ }),

/***/ 346:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   FE: () => (/* binding */ Collection),
/* harmony export */   G7: () => (/* binding */ View),
/* harmony export */   Hn: () => (/* binding */ Model),
/* harmony export */   pH: () => (/* binding */ DEFAULT_COORDS),
/* harmony export */   vA: () => (/* binding */ CoordinatesTypes)
/* harmony export */ });
/* unused harmony export DEFAULT_BOXRECT */
/* harmony import */ var backbone__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(316);
/* harmony import */ var backbone__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(backbone__WEBPACK_IMPORTED_MODULE_0__);
var __extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __assign = (undefined && undefined.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};


var Model = /** @class */ (function (_super) {
    __extends(Model, _super);
    function Model() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    return Model;
}((backbone__WEBPACK_IMPORTED_MODULE_0___default().Model)));

var Collection = /** @class */ (function (_super) {
    __extends(Collection, _super);
    function Collection() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    return Collection;
}((backbone__WEBPACK_IMPORTED_MODULE_0___default().Collection)));

var View = /** @class */ (function (_super) {
    __extends(View, _super);
    function View() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    return View;
}((backbone__WEBPACK_IMPORTED_MODULE_0___default().View)));

var CoordinatesTypes;
(function (CoordinatesTypes) {
    CoordinatesTypes["Screen"] = "screen";
    CoordinatesTypes["World"] = "world";
})(CoordinatesTypes || (CoordinatesTypes = {}));
var DEFAULT_COORDS = {
    x: 0,
    y: 0,
};
var DEFAULT_BOXRECT = __assign(__assign({}, DEFAULT_COORDS), { width: 0, height: 0 });


/***/ }),

/***/ 330:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Z: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var underscore__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(50);
/* harmony import */ var _common__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(346);
var __extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();


var DomainViews = /** @class */ (function (_super) {
    __extends(DomainViews, _super);
    function DomainViews(opts, config, autoAdd) {
        if (opts === void 0) { opts = {}; }
        if (autoAdd === void 0) { autoAdd = false; }
        var _this = _super.call(this, opts) || this;
        // Defines the View per type
        _this.itemsView = '';
        _this.itemType = 'type';
        _this.reuseView = false;
        _this.config = config || opts.config || {};
        autoAdd && _this.listenTo(_this.collection, 'add', _this.addTo);
        _this.items = [];
        return _this;
    }
    /**
     * Add new model to the collection
     * @param {Model} model
     * @private
     * */
    DomainViews.prototype.addTo = function (model) {
        this.add(model);
    };
    DomainViews.prototype.itemViewNotFound = function (type) {
        var _a = this, config = _a.config, ns = _a.ns;
        var em = config.em;
        var warn = "".concat(ns ? "[".concat(ns, "]: ") : '', "'").concat(type, "' type not found");
        em && em.logWarning(warn);
    };
    /**
     * Render new model inside the view
     * @param {Model} model
     * @param {Object} fragment Fragment collection
     * @private
     * */
    DomainViews.prototype.add = function (model, fragment) {
        var _a = this, config = _a.config, reuseView = _a.reuseView, items = _a.items;
        var itemsView = (this.itemsView || {});
        var inputTypes = [
            'button',
            'checkbox',
            'color',
            'date',
            'datetime-local',
            'email',
            'file',
            'hidden',
            'image',
            'month',
            'number',
            'password',
            'radio',
            'range',
            'reset',
            'search',
            'submit',
            'tel',
            'text',
            'time',
            'url',
            'week',
        ];
        var frag = fragment || null;
        var itemView = this.itemView;
        var typeField = model.get(this.itemType);
        var view;
        if (itemsView[typeField]) {
            itemView = itemsView[typeField];
        }
        else if (typeField && !itemsView[typeField] && !(0,underscore__WEBPACK_IMPORTED_MODULE_0__.includes)(inputTypes, typeField)) {
            this.itemViewNotFound(typeField);
        }
        if (model.view && reuseView) {
            view = model.view;
        }
        else {
            view = new itemView({ model: model, config: config }, config);
        }
        items && items.push(view);
        var rendered = view.render().el;
        if (frag)
            frag.appendChild(rendered);
        else
            this.$el.append(rendered);
    };
    DomainViews.prototype.render = function () {
        var frag = document.createDocumentFragment();
        this.clearItems();
        this.$el.empty();
        if (this.collection.length)
            this.collection.each(function (model) {
                // @ts-ignore
                this.add(model, frag);
            }, this);
        this.$el.append(frag);
        this.onRender();
        return this;
    };
    DomainViews.prototype.onRender = function () { };
    DomainViews.prototype.onRemoveBefore = function (items, opts) { };
    DomainViews.prototype.onRemove = function (items, opts) { };
    DomainViews.prototype.remove = function (opts) {
        if (opts === void 0) { opts = {}; }
        var items = this.items;
        this.onRemoveBefore(items, opts);
        this.clearItems();
        _super.prototype.remove.call(this);
        this.onRemove(items, opts);
        return this;
    };
    DomainViews.prototype.clearItems = function () {
        var items = this.items || [];
        // TODO Traits do not update the target anymore
        // items.forEach(item => item.remove());
        // this.items = [];
    };
    return DomainViews;
}(_common__WEBPACK_IMPORTED_MODULE_1__/* .View */ .G7));
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (DomainViews);
// Default view
DomainViews.prototype.itemView = '';


/***/ }),

/***/ 668:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Z: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var underscore__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(50);
/* harmony import */ var _dom__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(491);
var __assign = (undefined && undefined.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};


var resetPos = function () { return ({ x: 0, y: 0 }); };
var xyArr = ['x', 'y'];
var Dragger = /** @class */ (function () {
    /**
     * Init the dragger
     * @param  {Object} opts
     */
    function Dragger(opts) {
        if (opts === void 0) { opts = {}; }
        this.opts = {
            snapOffset: 5,
            scale: 1,
        };
        (0,underscore__WEBPACK_IMPORTED_MODULE_0__.bindAll)(this, 'drag', 'stop', 'keyHandle', 'handleScroll');
        this.setOptions(opts);
        this.delta = resetPos();
        this.lastScroll = resetPos();
        this.lastScrollDiff = resetPos();
        this.startPointer = resetPos();
        this.startPosition = resetPos();
        this.globScrollDiff = resetPos();
        this.currentPointer = resetPos();
        this.position = resetPos();
        this.guidesStatic = [];
        this.guidesTarget = [];
        this.docs = [];
        return this;
    }
    /**
     * Update options
     * @param {Object} options
     */
    Dragger.prototype.setOptions = function (opts) {
        if (opts === void 0) { opts = {}; }
        this.opts = __assign(__assign({}, this.opts), opts);
    };
    Dragger.prototype.toggleDrag = function (enable) {
        var docs = this.getDocumentEl();
        var container = this.getContainerEl();
        var win = this.getWindowEl();
        var method = enable ? 'on' : 'off';
        var methods = { on: _dom__WEBPACK_IMPORTED_MODULE_1__.on, off: _dom__WEBPACK_IMPORTED_MODULE_1__/* .off */ .S1 };
        methods[method](container, 'mousemove dragover', this.drag);
        methods[method](docs, 'mouseup dragend touchend', this.stop);
        methods[method](docs, 'keydown', this.keyHandle);
        methods[method](win, 'scroll', this.handleScroll);
    };
    Dragger.prototype.handleScroll = function () {
        var _a = this, lastScroll = _a.lastScroll, delta = _a.delta;
        var actualScroll = this.getScrollInfo();
        var scrollDiff = {
            x: actualScroll.x - lastScroll.x,
            y: actualScroll.y - lastScroll.y,
        };
        this.move(delta.x + scrollDiff.x, delta.y + scrollDiff.y);
        this.lastScrollDiff = scrollDiff;
    };
    /**
     * Start dragging
     * @param  {Event} e
     */
    Dragger.prototype.start = function (ev) {
        var opts = this.opts;
        var onStart = opts.onStart;
        this.toggleDrag(true);
        this.startPointer = this.getPointerPos(ev);
        this.guidesStatic = (0,underscore__WEBPACK_IMPORTED_MODULE_0__.result)(opts, 'guidesStatic') || [];
        this.guidesTarget = (0,underscore__WEBPACK_IMPORTED_MODULE_0__.result)(opts, 'guidesTarget') || [];
        (0,underscore__WEBPACK_IMPORTED_MODULE_0__.isFunction)(onStart) && onStart(ev, this);
        this.startPosition = this.getStartPosition();
        this.lastScrollDiff = resetPos();
        this.globScrollDiff = resetPos();
        this.drag(ev);
    };
    /**
     * Drag event
     * @param  {Event} event
     */
    Dragger.prototype.drag = function (ev) {
        var _this = this;
        var _a = this, opts = _a.opts, lastScrollDiff = _a.lastScrollDiff, globScrollDiff = _a.globScrollDiff;
        var onDrag = opts.onDrag;
        var startPointer = this.startPointer;
        var currentPos = this.getPointerPos(ev);
        var glDiff = {
            x: globScrollDiff.x + lastScrollDiff.x,
            y: globScrollDiff.y + lastScrollDiff.y,
        };
        this.globScrollDiff = glDiff;
        var delta = {
            x: currentPos.x - startPointer.x + glDiff.x,
            y: currentPos.y - startPointer.y + glDiff.y,
        };
        this.lastScrollDiff = resetPos();
        var lockedAxis = this.lockedAxis;
        // @ts-ignore Lock one axis
        if (ev.shiftKey) {
            lockedAxis = !lockedAxis && this.detectAxisLock(delta.x, delta.y);
        }
        else {
            lockedAxis = null;
        }
        if (lockedAxis === 'x') {
            delta.x = startPointer.x;
        }
        else if (lockedAxis === 'y') {
            delta.y = startPointer.y;
        }
        var moveDelta = function (delta) {
            xyArr.forEach(function (co) { return (delta[co] = delta[co] * (0,underscore__WEBPACK_IMPORTED_MODULE_0__.result)(opts, 'scale')); });
            _this.delta = delta;
            _this.move(delta.x, delta.y);
            (0,underscore__WEBPACK_IMPORTED_MODULE_0__.isFunction)(onDrag) && onDrag(ev, _this);
        };
        var deltaPre = __assign({}, delta);
        this.currentPointer = currentPos;
        this.lockedAxis = lockedAxis;
        this.lastScroll = this.getScrollInfo();
        moveDelta(delta);
        if (this.guidesTarget.length) {
            var _b = this.snapGuides(deltaPre), newDelta = _b.newDelta, trgX = _b.trgX, trgY = _b.trgY;
            (trgX || trgY) && moveDelta(newDelta);
        }
        // @ts-ignore In case the mouse button was released outside of the window
        ev.which === 0 && this.stop(ev);
    };
    /**
     * Check if the delta hits some guide
     */
    Dragger.prototype.snapGuides = function (delta) {
        var _this = this;
        var newDelta = delta;
        var _a = this, trgX = _a.trgX, trgY = _a.trgY;
        this.guidesTarget.forEach(function (trg) {
            // Skip the guide if its locked axis already exists
            if ((trg.x && _this.trgX) || (trg.y && _this.trgY))
                return;
            trg.active = false;
            _this.guidesStatic.forEach(function (stat) {
                if ((trg.y && stat.x) || (trg.x && stat.y))
                    return;
                var isY = trg.y && stat.y;
                var axs = isY ? 'y' : 'x';
                var trgPoint = trg[axs];
                var statPoint = stat[axs];
                var deltaPoint = delta[axs];
                var trgGuide = isY ? trgY : trgX;
                if (_this.isPointIn(trgPoint, statPoint)) {
                    if ((0,underscore__WEBPACK_IMPORTED_MODULE_0__.isUndefined)(trgGuide)) {
                        var trgValue = deltaPoint - (trgPoint - statPoint);
                        _this.setGuideLock(trg, trgValue);
                    }
                }
            });
        });
        trgX = this.trgX;
        trgY = this.trgY;
        xyArr.forEach(function (co) {
            var axis = co.toUpperCase();
            // @ts-ignore
            var trg = _this["trg".concat(axis)];
            if (trg && !_this.isPointIn(delta[co], trg.lock)) {
                _this.setGuideLock(trg, null);
                trg = null;
            }
            if (trg && !(0,underscore__WEBPACK_IMPORTED_MODULE_0__.isUndefined)(trg.lock)) {
                newDelta[co] = trg.lock;
            }
        });
        return {
            newDelta: newDelta,
            trgX: this.trgX,
            trgY: this.trgY,
        };
    };
    Dragger.prototype.isPointIn = function (src, trg, _a) {
        var _b = _a === void 0 ? {} : _a, offset = _b.offset;
        var ofst = offset || this.opts.snapOffset || 0;
        return (src >= trg && src <= trg + ofst) || (src <= trg && src >= trg - ofst);
    };
    Dragger.prototype.setGuideLock = function (guide, value) {
        var axis = !(0,underscore__WEBPACK_IMPORTED_MODULE_0__.isUndefined)(guide.x) ? 'X' : 'Y';
        var trgName = "trg".concat(axis);
        if (value !== null) {
            guide.active = true;
            guide.lock = value;
            // @ts-ignore
            this[trgName] = guide;
        }
        else {
            delete guide.active;
            delete guide.lock;
            // @ts-ignore
            delete this[trgName];
        }
        return guide;
    };
    /**
     * Stop dragging
     */
    Dragger.prototype.stop = function (ev, opts) {
        if (opts === void 0) { opts = {}; }
        var delta = this.delta;
        var cancelled = !!opts.cancel;
        var x = cancelled ? 0 : delta.x;
        var y = cancelled ? 0 : delta.y;
        this.toggleDrag();
        this.lockedAxis = null;
        this.move(x, y, true);
        var onEnd = this.opts.onEnd;
        (0,underscore__WEBPACK_IMPORTED_MODULE_0__.isFunction)(onEnd) && onEnd(ev, this, { cancelled: cancelled });
    };
    Dragger.prototype.keyHandle = function (ev) {
        if ((0,_dom__WEBPACK_IMPORTED_MODULE_1__/* .isEscKey */ .kl)(ev)) {
            this.stop(ev, { cancel: true });
        }
    };
    /**
     * Move the element
     * @param  {integer} x
     * @param  {integer} y
     */
    Dragger.prototype.move = function (x, y, end) {
        var _a = this, el = _a.el, opts = _a.opts;
        var pos = this.startPosition;
        if (!pos)
            return;
        var setPosition = opts.setPosition;
        var xPos = pos.x + x;
        var yPos = pos.y + y;
        this.position = {
            x: xPos,
            y: yPos,
            end: end,
        };
        (0,underscore__WEBPACK_IMPORTED_MODULE_0__.isFunction)(setPosition) && setPosition(this.position);
        if (el) {
            el.style.left = "".concat(xPos, "px");
            el.style.top = "".concat(yPos, "px");
        }
    };
    Dragger.prototype.getContainerEl = function () {
        var container = this.opts.container;
        return container ? [container] : this.getDocumentEl();
    };
    Dragger.prototype.getWindowEl = function () {
        var cont = this.getContainerEl();
        return cont.map(function (item) {
            var doc = item.ownerDocument || item;
            // @ts-ignore
            return doc.defaultView || doc.parentWindow;
        });
    };
    /**
     * Returns documents
     */
    Dragger.prototype.getDocumentEl = function (el) {
        var doc = this.opts.doc;
        el = el || this.el;
        if (!this.docs.length) {
            var docs = [document];
            el && docs.push(el.ownerDocument);
            doc && docs.push(doc);
            this.docs = docs;
        }
        return this.docs;
    };
    /**
     * Get mouse coordinates
     * @param  {Event} event
     * @return {Object}
     */
    Dragger.prototype.getPointerPos = function (ev) {
        var getPos = this.opts.getPointerPosition;
        var pEv = (0,_dom__WEBPACK_IMPORTED_MODULE_1__/* .getPointerEvent */ .VB)(ev);
        return getPos
            ? getPos(ev)
            : {
                x: pEv.clientX,
                y: pEv.clientY,
            };
    };
    Dragger.prototype.getStartPosition = function () {
        var _a = this, el = _a.el, opts = _a.opts;
        var getPos = opts.getPosition;
        var result = resetPos();
        if ((0,underscore__WEBPACK_IMPORTED_MODULE_0__.isFunction)(getPos)) {
            result = getPos();
        }
        else if (el) {
            result = {
                x: parseFloat(el.style.left),
                y: parseFloat(el.style.top),
            };
        }
        return result;
    };
    Dragger.prototype.getScrollInfo = function () {
        var doc = this.opts.doc;
        var body = doc && doc.body;
        return {
            y: body ? body.scrollTop : 0,
            x: body ? body.scrollLeft : 0,
        };
    };
    Dragger.prototype.detectAxisLock = function (x, y) {
        var relX = x;
        var relY = y;
        var absX = Math.abs(relX);
        var absY = Math.abs(relY);
        // Vertical or Horizontal lock
        if (relY >= absX || relY <= -absX) {
            return 'x';
        }
        else if (relX > absY || relX < -absY) {
            return 'y';
        }
    };
    return Dragger;
}());
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (Dragger);


/***/ }),

/***/ 895:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
// @ts-nocheck
/* Adapted for headless */
/* MIT https://github.com/kenwheeler/cash */

var doc = typeof document !== 'undefined' ? document : null, win = typeof window !== 'undefined' ? window : null, _Array$prototype = Array.prototype, filter = _Array$prototype.filter, indexOf = _Array$prototype.indexOf, map = _Array$prototype.map, push = _Array$prototype.push, reverse = _Array$prototype.reverse, slice = _Array$prototype.slice, splice = _Array$prototype.splice;
var idRe = /^#[\w-]*$/, classRe = /^\.[\w-]*$/, htmlRe = /<.+>/, tagRe = /^\w+$/; // @require ./variables.js
function find(selector, context) {
    if (context === void 0) {
        context = doc;
    }
    return classRe.test(selector)
        ? context.getElementsByClassName(selector.slice(1))
        : tagRe.test(selector)
            ? context.getElementsByTagName(selector)
            : context.querySelectorAll(selector);
} // @require ./find.js
// @require ./variables.js
function Cash(selector, context) {
    if (context === void 0) {
        context = doc;
    }
    if (!selector)
        return;
    if (selector.__cash)
        return selector;
    var eles = selector;
    if (isString(selector)) {
        if (context.__cash)
            context = context[0];
        eles = idRe.test(selector)
            ? context.getElementById(selector.slice(1))
            : htmlRe.test(selector)
                ? parseHTML(selector)
                : find(selector, context);
        if (!eles)
            return;
    }
    else if (isFunction(selector)) {
        return this.ready(selector); //FIXME: `fn.ready` is not included in `core`, but it's actually a core functionality
    }
    if (eles.nodeType || eles === win)
        eles = [eles];
    this.length = eles.length;
    for (var i = 0, l = this.length; i < l; i++) {
        this[i] = eles[i];
    }
}
function cash(selector, context) {
    return new Cash(selector, context);
}
/* PROTOTYPE */
var fn = (cash.fn =
    cash.prototype =
        Cash.prototype =
            {
                constructor: cash,
                __cash: true,
                length: 0,
                splice: splice, // Ensures a cash collection gets printed as array-like in Chrome
            }); // @require core/cash.js
// @require core/variables.js
fn.get = function (index) {
    if (index === undefined)
        return slice.call(this);
    return this[index < 0 ? index + this.length : index];
}; // @require core/cash.js
// @require ./get.js
fn.eq = function (index) {
    return cash(this.get(index));
}; // @require core/cash.js
// @require ./eq.js
fn.first = function () {
    return this.eq(0);
}; // @require core/cash.js
// @require ./eq.js
fn.last = function () {
    return this.eq(-1);
}; // @require core/cash.js
// @require core/variables.js
fn.map = function (callback) {
    return cash(map.call(this, function (ele, i) {
        return callback.call(ele, i, ele);
    }));
}; // @require core/cash.js
// @require core/variables.js
fn.slice = function () {
    return cash(slice.apply(this, arguments));
}; // @require ./cash.js
var camelCaseRe = /(?:^\w|[A-Z]|\b\w)/g, camelCaseWhitespaceRe = /[\s-_]+/g;
function camelCase(str) {
    return str
        .replace(camelCaseRe, function (letter, index) {
        return letter[!index ? 'toLowerCase' : 'toUpperCase']();
    })
        .replace(camelCaseWhitespaceRe, '');
}
cash.camelCase = camelCase; // @require ./cash.js
function each(arr, callback) {
    for (var i = 0, l = arr.length; i < l; i++) {
        if (callback.call(arr[i], arr[i], i, arr) === false)
            break;
    }
}
cash.each = each; // @require core/cash.js
// @require core/each.js
fn.each = function (callback) {
    each(this, function (ele, i) {
        return callback.call(ele, i, ele);
    });
    return this;
}; // @require core/cash.js
// @require collection/each.js
fn.removeProp = function (prop) {
    return this.each(function (i, ele) {
        delete ele[prop];
    });
}; // @require ./cash.js
function extend(target) {
    if (target === void 0) {
        target = this;
    }
    var args = arguments, length = args.length;
    for (var i = length < 2 ? 0 : 1; i < length; i++) {
        for (var key in args[i]) {
            target[key] = args[i][key];
        }
    }
    return target;
}
cash.extend = fn.extend = extend; // @require ./cash.js
var guid = 1;
cash.guid = guid; // @require ./cash.js
function matches(ele, selector) {
    var matches = ele &&
        (ele.matches ||
            ele.webkitMatchesSelector ||
            ele.mozMatchesSelector ||
            ele.msMatchesSelector ||
            ele.oMatchesSelector);
    return !!matches && matches.call(ele, selector);
}
cash.matches = matches; // @require ./cash.js
function isFunction(x) {
    return typeof x === 'function';
}
cash.isFunction = isFunction;
function isString(x) {
    return typeof x === 'string';
}
cash.isString = isString;
function isNumeric(x) {
    return !isNaN(parseFloat(x)) && isFinite(x);
}
cash.isNumeric = isNumeric;
var isArray = Array.isArray;
cash.isArray = isArray; // @require core/cash.js
// @require core/type_checking.js
// @require collection/each.js
fn.prop = function (prop, value) {
    if (!prop)
        return;
    if (isString(prop)) {
        if (arguments.length < 2)
            return this[0] && this[0][prop];
        return this.each(function (i, ele) {
            ele[prop] = value;
        });
    }
    for (var key in prop) {
        this.prop(key, prop[key]);
    }
    return this;
}; // @require ./matches.js
// @require ./type_checking.js
function getCompareFunction(selector) {
    return isString(selector)
        ? function (i, ele) {
            return matches(ele, selector);
        }
        : selector.__cash
            ? function (i, ele) {
                return selector.is(ele);
            }
            : function (i, ele, selector) {
                return ele === selector;
            };
} // @require core/cash.js
// @require core/get_compare_function.js
// @require core/type_checking.js
// @require core/variables.js
// @require collection/get.js
fn.filter = function (selector) {
    if (!selector)
        return cash();
    var comparator = isFunction(selector) ? selector : getCompareFunction(selector);
    return cash(filter.call(this, function (ele, i) {
        return comparator.call(ele, i, ele, selector);
    }));
}; // @require ./type_checking.js
var splitValuesRe = /\S+/g;
function getSplitValues(str) {
    return isString(str) ? str.match(splitValuesRe) || [] : [];
} // @require core/cash.js
// @require core/get_split_values.js
// @require collection/each.js
fn.hasClass = function (cls) {
    var classes = getSplitValues(cls);
    var check = false;
    if (classes.length) {
        this.each(function (i, ele) {
            check = ele.classList.contains(classes[0]);
            return !check;
        });
    }
    return check;
}; // @require core/cash.js
// @require core/get_split_values.js
// @require collection/each.js
fn.removeAttr = function (attr) {
    var attrs = getSplitValues(attr);
    if (!attrs.length)
        return this;
    return this.each(function (i, ele) {
        each(attrs, function (a) {
            ele.removeAttribute(a);
        });
    });
}; // @require core/cash.js
// @require core/type_checking.js
// @require collection/each.js
// @require ./remove_attr.js
fn.attr = function (attr, value) {
    if (!attr)
        return;
    if (isString(attr)) {
        if (arguments.length < 2) {
            if (!this[0])
                return;
            var _value = this[0].getAttribute(attr);
            return _value === null ? undefined : _value;
        }
        if (value === null)
            return this.removeAttr(attr);
        return this.each(function (i, ele) {
            ele.setAttribute(attr, value);
        });
    }
    for (var key in attr) {
        this.attr(key, attr[key]);
    }
    return this;
}; // @require core/cash.js
// @require core/each.js
// @require core/get_split_values.js
// @require collection/each.js
fn.toggleClass = function (cls, force) {
    var classes = getSplitValues(cls), isForce = force !== undefined;
    if (!classes.length)
        return this;
    return this.each(function (i, ele) {
        each(classes, function (c) {
            if (isForce) {
                force ? ele.classList.add(c) : ele.classList.remove(c);
            }
            else {
                ele.classList.toggle(c);
            }
        });
    });
}; // @require core/cash.js
// @require ./toggle_class.js
fn.addClass = function (cls) {
    return this.toggleClass(cls, true);
}; // @require core/cash.js
// @require ./attr.js
// @require ./toggle_class.js
fn.removeClass = function (cls) {
    return !arguments.length ? this.attr('class', '') : this.toggleClass(cls, false);
}; // @optional ./add_class.js
// @optional ./attr.js
// @optional ./has_class.js
// @optional ./prop.js
// @optional ./remove_attr.js
// @optional ./remove_class.js
// @optional ./remove_prop.js
// @optional ./toggle_class.js
// @require ./cash.js
function unique(arr) {
    return arr.filter(function (item, index, self) {
        return self.indexOf(item) === index;
    });
}
cash.unique = unique; // @require core/cash.js
// @require core/unique.js
// @require ./get.js
fn.add = function (selector, context) {
    return cash(unique(this.get().concat(cash(selector, context).get())));
}; // @require core/variables.js
function computeStyle(ele, prop, isVariable) {
    if (ele.nodeType !== 1)
        return;
    var style = win.getComputedStyle(ele, null);
    return prop ? (isVariable ? style.getPropertyValue(prop) : style[prop]) : style;
} // @require ./compute_style.js
function computeStyleInt(ele, prop) {
    return parseInt(computeStyle(ele, prop), 10) || 0;
}
var cssVariableRe = /^--/; // @require ./variables.js
function isCSSVariable(prop) {
    return cssVariableRe.test(prop);
} // @require core/camel_case.js
// @require core/cash.js
// @require core/each.js
// @require core/variables.js
// @require ./is_css_variable.js
var prefixedProps = {}, docEl = doc && doc.createElement('div'), style = docEl ? docEl.style : {}, vendorsPrefixes = ['webkit', 'moz', 'ms', 'o'];
function getPrefixedProp(prop, isVariable) {
    if (isVariable === void 0) {
        isVariable = isCSSVariable(prop);
    }
    if (isVariable)
        return prop;
    if (!prefixedProps[prop]) {
        var propCC = camelCase(prop), propUC = '' + propCC.charAt(0).toUpperCase() + propCC.slice(1), props = (propCC + ' ' + vendorsPrefixes.join(propUC + ' ') + propUC).split(' ');
        each(props, function (p) {
            if (p in style) {
                prefixedProps[prop] = p;
                return false;
            }
        });
    }
    return prefixedProps[prop];
}
cash.prefixedProp = getPrefixedProp; // @require core/type_checking.js
// @require ./is_css_variable.js
var numericProps = {
    animationIterationCount: true,
    columnCount: true,
    flexGrow: true,
    flexShrink: true,
    fontWeight: true,
    lineHeight: true,
    opacity: true,
    order: true,
    orphans: true,
    widows: true,
    zIndex: true,
};
function getSuffixedValue(prop, value, isVariable) {
    if (isVariable === void 0) {
        isVariable = isCSSVariable(prop);
    }
    return !isVariable && !numericProps[prop] && isNumeric(value) ? value + 'px' : value;
} // @require core/cash.js
// @require core/type_checking.js
// @require collection/each.js
// @require ./helpers/compute_style.js
// @require ./helpers/get_prefixed_prop.js
// @require ./helpers/get_suffixed_value.js
// @require ./helpers/is_css_variable.js
fn.css = function (prop, value) {
    if (isString(prop)) {
        var isVariable = isCSSVariable(prop);
        prop = getPrefixedProp(prop, isVariable);
        if (arguments.length < 2)
            return this[0] && computeStyle(this[0], prop, isVariable);
        if (!prop)
            return this;
        value = getSuffixedValue(prop, value, isVariable);
        return this.each(function (i, ele) {
            if (ele.nodeType !== 1)
                return;
            if (isVariable) {
                ele.style.setProperty(prop, value);
            }
            else {
                ele.style[prop] = value;
            }
        });
    }
    for (var key in prop) {
        this.css(key, prop[key]);
    }
    return this;
}; // @optional ./css.js
var dataNamespace = '__cashData', dataAttributeRe = /^data-(.*)/; // @require core/cash.js
// @require ./helpers/variables.js
cash.hasData = function (ele) {
    return dataNamespace in ele;
}; // @require ./variables.js
function getDataCache(ele) {
    return (ele[dataNamespace] = ele[dataNamespace] || {});
} // @require attributes/attr.js
// @require ./get_data_cache.js
function getData(ele, key) {
    var cache = getDataCache(ele);
    if (key) {
        if (!(key in cache)) {
            var value = ele.dataset ? ele.dataset[key] || ele.dataset[camelCase(key)] : cash(ele).attr('data-' + key);
            if (value !== undefined) {
                try {
                    value = JSON.parse(value);
                }
                catch (e) { }
                cache[key] = value;
            }
        }
        return cache[key];
    }
    return cache;
} // @require ./variables.js
// @require ./get_data_cache.js
function removeData(ele, key) {
    if (key === undefined) {
        delete ele[dataNamespace];
    }
    else {
        delete getDataCache(ele)[key];
    }
} // @require ./get_data_cache.js
function setData(ele, key, value) {
    getDataCache(ele)[key] = value;
} // @require core/cash.js
// @require core/type_checking.js
// @require collection/each.js
// @require ./helpers/get_data.js
// @require ./helpers/set_data.js
// @require ./helpers/variables.js
fn.data = function (name, value) {
    var _this = this;
    if (!name) {
        if (!this[0])
            return;
        each(this[0].attributes, function (attr) {
            var match = attr.name.match(dataAttributeRe);
            if (!match)
                return;
            _this.data(match[1]);
        });
        return getData(this[0]);
    }
    if (isString(name)) {
        if (value === undefined)
            return this[0] && getData(this[0], name);
        return this.each(function (i, ele) {
            return setData(ele, name, value);
        });
    }
    for (var key in name) {
        this.data(key, name[key]);
    }
    return this;
}; // @require core/cash.js
// @require collection/each.js
// @require ./helpers/remove_data.js
fn.removeData = function (key) {
    return this.each(function (i, ele) {
        return removeData(ele, key);
    });
}; // @optional ./data.js
// @optional ./remove_data.js
// @require css/helpers/compute_style_int.js
function getExtraSpace(ele, xAxis) {
    return (computeStyleInt(ele, 'border' + (xAxis ? 'Left' : 'Top') + 'Width') +
        computeStyleInt(ele, 'padding' + (xAxis ? 'Left' : 'Top')) +
        computeStyleInt(ele, 'padding' + (xAxis ? 'Right' : 'Bottom')) +
        computeStyleInt(ele, 'border' + (xAxis ? 'Right' : 'Bottom') + 'Width'));
} // @require core/cash.js
// @require core/each.js
// @require core/variables.js
each(['Width', 'Height'], function (prop) {
    fn['inner' + prop] = function () {
        if (!this[0])
            return;
        if (this[0] === win)
            return win['inner' + prop];
        return this[0]['client' + prop];
    };
}); // @require core/camel_case.js
// @require core/cash.js
// @require core/each.js
// @require core/variables.js
// @require css/helpers/compute_style.js
// @require css/helpers/get_suffixed_value.js
// @require ./helpers/get_extra_space.js
each(['width', 'height'], function (prop, index) {
    fn[prop] = function (value) {
        if (!this[0])
            return value === undefined ? undefined : this;
        if (!arguments.length) {
            if (this[0] === win)
                return this[0][camelCase('outer-' + prop)];
            return this[0].getBoundingClientRect()[prop] - getExtraSpace(this[0], !index);
        }
        value = parseInt(value, 10);
        return this.each(function (i, ele) {
            if (ele.nodeType !== 1)
                return;
            var boxSizing = computeStyle(ele, 'boxSizing');
            ele.style[prop] = getSuffixedValue(prop, value + (boxSizing === 'border-box' ? getExtraSpace(ele, !index) : 0));
        });
    };
}); // @require core/cash.js
// @require core/each.js
// @require core/variables.js
// @require css/helpers/compute_style_int.js
each(['Width', 'Height'], function (prop, index) {
    fn['outer' + prop] = function (includeMargins) {
        if (!this[0])
            return;
        if (this[0] === win)
            return win['outer' + prop];
        return (this[0]['offset' + prop] +
            (includeMargins
                ? computeStyleInt(this[0], 'margin' + (!index ? 'Left' : 'Top')) +
                    computeStyleInt(this[0], 'margin' + (!index ? 'Right' : 'Bottom'))
                : 0));
    };
}); // @optional ./inner.js
// @optional ./normal.js
// @optional ./outer.js
function hasNamespaces(ns1, ns2) {
    for (var i = 0, l = ns2.length; i < l; i++) {
        if (ns1.indexOf(ns2[i]) < 0)
            return false;
    }
    return true;
} // @require core/each.js
function removeEventListeners(cache, ele, name) {
    each(cache[name], function (_ref) {
        var namespaces = _ref[0], callback = _ref[1];
        ele.removeEventListener(name, callback);
    });
    delete cache[name];
}
var eventsNamespace = '__cashEvents', eventsNamespacesSeparator = '.'; // @require ./variables.js
function getEventsCache(ele) {
    return (ele[eventsNamespace] = ele[eventsNamespace] || {});
} // @require core/guid.js
// @require events/helpers/get_events_cache.js
function addEvent(ele, name, namespaces, callback) {
    callback.guid = callback.guid || guid++;
    var eventCache = getEventsCache(ele);
    eventCache[name] = eventCache[name] || [];
    eventCache[name].push([namespaces, callback]);
    ele.addEventListener(name, callback);
} // @require ./variables.js
function parseEventName(eventName) {
    var parts = eventName.split(eventsNamespacesSeparator);
    return [parts[0], parts.slice(1).sort()]; // [name, namespaces]
} // @require core/guid.js
// @require ./get_events_cache.js
// @require ./has_namespaces.js
// @require ./parse_event_name.js
// @require ./remove_event_listeners.js
function removeEvent(ele, name, namespaces, callback) {
    var cache = getEventsCache(ele);
    if (!name) {
        if (!namespaces || !namespaces.length) {
            for (name in cache) {
                removeEventListeners(cache, ele, name);
            }
        }
        else {
            for (name in cache) {
                removeEvent(ele, name, namespaces, callback);
            }
        }
    }
    else {
        var eventCache = cache[name];
        if (!eventCache)
            return;
        if (callback)
            callback.guid = callback.guid || guid++;
        cache[name] = eventCache.filter(function (_ref2) {
            var ns = _ref2[0], cb = _ref2[1];
            if ((callback && cb.guid !== callback.guid) || !hasNamespaces(ns, namespaces))
                return true;
            ele.removeEventListener(name, cb);
        });
    }
} // @require core/cash.js
// @require core/each.js
// @require collection/each.js
// @require ./helpers/parse_event_name.js
// @require ./helpers/remove_event.js
fn.off = function (eventFullName, callback) {
    var _this2 = this;
    if (eventFullName === undefined) {
        this.each(function (i, ele) {
            return removeEvent(ele);
        });
    }
    else {
        each(getSplitValues(eventFullName), function (eventFullName) {
            var _parseEventName = parseEventName(eventFullName), name = _parseEventName[0], namespaces = _parseEventName[1];
            _this2.each(function (i, ele) {
                return removeEvent(ele, name, namespaces, callback);
            });
        });
    }
    return this;
}; // @require core/cash.js
// @require core/get_split_values.js
// @require core/guid.js
// @require core/matches.js
// @require core/type_checking.js
// @require collection/each.js
// @require ./helpers/variables.js
// @require ./helpers/add_event.js
// @require ./helpers/has_namespaces.js
// @require ./helpers/parse_event_name.js
// @require ./helpers/remove_event.js
fn.on = function (eventFullName, selector, callback, _one) {
    var _this3 = this;
    if (!isString(eventFullName)) {
        for (var key in eventFullName) {
            this.on(key, selector, eventFullName[key]);
        }
        return this;
    }
    if (isFunction(selector)) {
        callback = selector;
        selector = false;
    }
    each(getSplitValues(eventFullName), function (eventFullName) {
        var _parseEventName2 = parseEventName(eventFullName), name = _parseEventName2[0], namespaces = _parseEventName2[1];
        _this3.each(function (i, ele) {
            var finalCallback = function finalCallback(event) {
                if (event.namespace && !hasNamespaces(namespaces, event.namespace.split(eventsNamespacesSeparator)))
                    return;
                var thisArg = ele;
                if (selector) {
                    var target = event.target;
                    while (!matches(target, selector)) {
                        if (target === ele)
                            return;
                        target = target.parentNode;
                        if (!target)
                            return;
                    }
                    thisArg = target;
                }
                event.namespace = event.namespace || '';
                var returnValue = callback.call(thisArg, event, event.data);
                if (_one) {
                    removeEvent(ele, name, namespaces, finalCallback);
                }
                if (returnValue === false) {
                    event.preventDefault();
                    event.stopPropagation();
                }
            };
            finalCallback.guid = callback.guid = callback.guid || guid++;
            addEvent(ele, name, namespaces, finalCallback);
        });
    });
    return this;
}; // @require core/cash.js
// @require ./on.js
fn.one = function (eventFullName, delegate, callback) {
    return this.on(eventFullName, delegate, callback, true);
}; // @require core/cash.js
// @require core/variables.js
fn.ready = function (callback) {
    var finalCallback = function finalCallback() {
        return callback(cash);
    };
    if (doc.readyState !== 'loading') {
        setTimeout(finalCallback);
    }
    else {
        doc.addEventListener('DOMContentLoaded', finalCallback);
    }
    return this;
}; // @require core/cash.js
// @require core/type_checking.js
// @require core/variables.js
// @require collection/each.js
// @require ./helpers/parse_event_name.js
// @require ./helpers/variables.js
fn.trigger = function (eventFullName, data) {
    var evt = eventFullName;
    if (isString(eventFullName)) {
        var _parseEventName3 = parseEventName(eventFullName), name = _parseEventName3[0], namespaces = _parseEventName3[1];
        evt = doc.createEvent('HTMLEvents');
        evt.initEvent(name, true, true);
        evt.namespace = namespaces.join(eventsNamespacesSeparator);
    }
    evt.data = data;
    return this.each(function (i, ele) {
        ele.dispatchEvent(evt);
    });
}; // @optional ./off.js
// @optional ./on.js
// @optional ./one.js
// @optional ./ready.js
// @optional ./trigger.js
// @require core/each.js
function getValueSelectMultiple(ele) {
    var values = [];
    each(ele.options, function (option) {
        if (option.selected && !option.disabled && !option.parentNode.disabled) {
            values.push(option.value);
        }
    });
    return values;
}
function getValueSelectSingle(ele) {
    return ele.selectedIndex < 0 ? null : ele.options[ele.selectedIndex].value;
} // @require ./get_value_select_single.js
// @require ./get_value_select_multiple.js
var selectOneRe = /select-one/i, selectMultipleRe = /select-multiple/i;
function getValue(ele) {
    var type = ele.type;
    if (selectOneRe.test(type))
        return getValueSelectSingle(ele);
    if (selectMultipleRe.test(type))
        return getValueSelectMultiple(ele);
    return ele.value;
}
var queryEncodeSpaceRe = /%20/g;
function queryEncode(prop, value) {
    return '&' + encodeURIComponent(prop) + '=' + encodeURIComponent(value).replace(queryEncodeSpaceRe, '+');
} // @require core/cash.js
// @require core/each.js
// @require core/type_checking.js
// @require ./helpers/get_value.js
// @require ./helpers/query_encode.js
var skippableRe = /file|reset|submit|button|image/i, checkableRe = /radio|checkbox/i;
fn.serialize = function () {
    var query = '';
    this.each(function (i, ele) {
        each(ele.elements || [ele], function (ele) {
            if (ele.disabled || !ele.name || ele.tagName === 'FIELDSET')
                return;
            if (skippableRe.test(ele.type))
                return;
            if (checkableRe.test(ele.type) && !ele.checked)
                return;
            var value = getValue(ele);
            if (value === undefined)
                return;
            var values = isArray(value) ? value : [value];
            each(values, function (value) {
                query += queryEncode(ele.name, value);
            });
        });
    });
    return query.substr(1);
}; // @require core/cash.js
// @require core/each.js
// @require core/type_checking.js
// @require collection/each.js
// @require ./helpers/get_value.js
fn.val = function (value) {
    if (value === undefined)
        return this[0] && getValue(this[0]);
    return this.each(function (i, ele) {
        var isMultiple = selectMultipleRe.test(ele.type), eleValue = value === null ? (isMultiple ? [] : '') : value;
        if (isMultiple && isArray(eleValue)) {
            each(ele.options, function (option) {
                option.selected = eleValue.indexOf(option.value) >= 0;
            });
        }
        else {
            ele.value = eleValue;
        }
    });
}; // @optional ./serialize.js
// @optional ./val.js
// @require core/cash.js
// @require collection/map.js
fn.clone = function () {
    return this.map(function (i, ele) {
        return ele.cloneNode(true);
    });
}; // @require core/cash.js
// @require collection/each.js
fn.detach = function () {
    return this.each(function (i, ele) {
        if (ele.parentNode) {
            ele.parentNode.removeChild(ele);
        }
    });
}; // @require ./cash.js
// @require ./variables.js
// @require ./type_checking.js
// @require collection/get.js
// @require manipulation/detach.js
var fragmentRe = /^\s*<(\w+)[^>]*>/, singleTagRe = /^\s*<(\w+)\s*\/?>(?:<\/\1>)?\s*$/;
var containers;
function initContainers() {
    if (containers)
        return;
    var table = doc.createElement('table'), tr = doc.createElement('tr');
    containers = {
        '*': doc.createElement('div'),
        tr: doc.createElement('tbody'),
        td: tr,
        th: tr,
        thead: table,
        tbody: table,
        tfoot: table,
    };
}
function parseHTML(html) {
    initContainers();
    if (!isString(html))
        return [];
    if (singleTagRe.test(html))
        return [doc.createElement(RegExp.$1)];
    var fragment = fragmentRe.test(html) && RegExp.$1, container = containers[fragment] || containers['*'];
    container.innerHTML = html;
    return cash(container.childNodes).detach().get();
}
cash.parseHTML = parseHTML; // @optional ./camel_case.js
// @optional ./each.js
// @optional ./export.js
// @optional ./extend.js
// @optional ./find.js
// @optional ./get_compare_function.js
// @optional ./get_split_values.js
// @optional ./guid.js
// @optional ./matches.js
// @optional ./parse_html.js
// @optional ./unique.js
// @optional ./variables.js
// @require ./cash.js
// @require ./type_checking.js
// @require core/cash.js
fn.empty = function () {
    var ele = this[0];
    if (ele) {
        while (ele.firstChild) {
            ele.removeChild(ele.firstChild);
        }
    }
    return this;
};
function insertElement(ele, child, prepend) {
    if (prepend) {
        ele.insertBefore(child, ele.childNodes[0]);
    }
    else {
        ele.appendChild(child);
    }
} // @require core/each.js
// @require core/type_checking.js
// @require ./insert_element.js
function insertContent(parent, child, prepend) {
    if (child === undefined)
        return;
    var isStr = isString(child);
    if (!isStr && child.length) {
        each(child, function (ele) {
            return insertContent(parent, ele, prepend);
        });
    }
    else {
        each(parent, isStr
            ? function (ele) {
                ele.insertAdjacentHTML(prepend ? 'afterbegin' : 'beforeend', child);
            }
            : function (ele, index) {
                return insertElement(ele, !index ? child : child.cloneNode(true), prepend);
            });
    }
} // @require core/cash.js
// @require core/each.js
// @require ./helpers/insert_content.js
fn.append = function () {
    var _this4 = this;
    each(arguments, function (content) {
        insertContent(_this4, content);
    });
    return this;
}; // @require core/cash.js
// @require ./helpers/insert_content.js
fn.appendTo = function (parent) {
    insertContent(cash(parent), this);
    return this;
}; // @require core/cash.js
// @require collection/each.js
fn.html = function (content) {
    if (content === undefined)
        return this[0] && this[0].innerHTML;
    var source = content.nodeType ? content[0].outerHTML : content;
    return this.each(function (i, ele) {
        ele.innerHTML = source;
    });
}; // @require core/cash.js
// @require collection/each.js
fn.insertAfter = function (content) {
    var _this5 = this;
    cash(content).each(function (index, ele) {
        var parent = ele.parentNode;
        _this5.each(function (i, e) {
            parent.insertBefore(!index ? e : e.cloneNode(true), ele.nextSibling);
        });
    });
    return this;
}; // @require core/cash.js
// @require core/each.js
// @require core/variables.js
// @require collection/slice.js
// @require ./insert_after.js
fn.after = function () {
    var _this6 = this;
    each(reverse.apply(arguments), function (content) {
        reverse.apply(cash(content).slice()).insertAfter(_this6);
    });
    return this;
}; // @require core/cash.js
// @require collection/each.js
fn.insertBefore = function (selector) {
    var _this7 = this;
    cash(selector).each(function (index, ele) {
        var parent = ele.parentNode;
        _this7.each(function (i, e) {
            parent.insertBefore(!index ? e : e.cloneNode(true), ele);
        });
    });
    return this;
}; // @require core/cash.js
// @require core/each.js
// @require ./insert_before.js
fn.before = function () {
    var _this8 = this;
    each(arguments, function (content) {
        cash(content).insertBefore(_this8);
    });
    return this;
}; // @require core/cash.js
// @require core/each.js
// @require ./helpers/insert_content.js
fn.prepend = function () {
    var _this9 = this;
    each(arguments, function (content) {
        insertContent(_this9, content, true);
    });
    return this;
}; // @require core/cash.js
// @require core/variables.js
// @require collection/slice.js
// @require ./helpers/insert_content.js
fn.prependTo = function (parent) {
    insertContent(cash(parent), reverse.apply(this.slice()), true);
    return this;
}; // @require core/cash.js
// @require events/off.js
// @require ./detach.js
fn.remove = function () {
    return this.detach().off();
}; // @require core/cash.js
// @require collection/each.js
// @require collection/slice.js
// @require ./after.js
// @require ./remove.js
fn.replaceWith = function (content) {
    var _this10 = this;
    return this.each(function (i, ele) {
        var parent = ele.parentNode;
        if (!parent)
            return;
        var $eles = i ? cash(content).clone() : cash(content);
        if (!$eles[0]) {
            _this10.remove();
            return false;
        }
        parent.replaceChild($eles[0], ele);
        cash($eles[0]).after($eles.slice(1));
    });
}; // @require core/cash.js
// @require ./replace_with.js
fn.replaceAll = function (content) {
    cash(content).replaceWith(this);
    return this;
}; // @require core/cash.js
// @require collection/each.js
fn.text = function (content) {
    if (content === undefined)
        return this[0] ? this[0].textContent : '';
    return this.each(function (i, ele) {
        ele.textContent = content;
    });
}; // @optional ./after.js
// @optional ./append.js
// @optional ./append_to.js
// @optional ./before.js
// @optional ./clone.js
// @optional ./detach.js
// @optional ./empty.js
// @optional ./html.js
// @optional ./insert_after.js
// @optional ./insert_before.js
// @optional ./prepend.js
// @optional ./prepend_to.js
// @optional ./remove.js
// @optional ./replace_all.js
// @optional ./replace_with.js
// @optional ./text.js
// @require core/cash.js
// @require core/variables.js
var docEle = doc && doc.documentElement;
fn.offset = function () {
    var ele = this[0];
    if (!ele)
        return;
    var rect = ele.getBoundingClientRect();
    return {
        top: rect.top + win.pageYOffset - docEle.clientTop,
        left: rect.left + win.pageXOffset - docEle.clientLeft,
    };
}; // @require core/cash.js
fn.offsetParent = function () {
    return cash(this[0] && this[0].offsetParent);
}; // @require core/cash.js
fn.position = function () {
    var ele = this[0];
    if (!ele)
        return;
    return {
        left: ele.offsetLeft,
        top: ele.offsetTop,
    };
}; // @optional ./offset.js
// @optional ./offset_parent.js
// @optional ./position.js
// @require core/cash.js
// @require core/matches.js
// @require core/unique.js
// @require collection/each.js
// @require collection/filter.js
fn.children = function (selector) {
    var result = [];
    this.each(function (i, ele) {
        push.apply(result, ele.children);
    });
    result = cash(unique(result));
    if (!selector)
        return result;
    return result.filter(function (i, ele) {
        return matches(ele, selector);
    });
}; // @require core/cash.js
// @require core/unique.js
// @require collection/each.js
fn.contents = function () {
    var result = [];
    this.each(function (i, ele) {
        push.apply(result, ele.tagName === 'IFRAME' ? [ele.contentDocument] : ele.childNodes);
    });
    return cash(result.length && unique(result));
}; // @require core/cash.js
// @require core/unique.js
// @require core/find.js
// @require core/variables.js
fn.find = function (selector) {
    var result = [];
    for (var i = 0, l = this.length; i < l; i++) {
        var found = find(selector, this[i]);
        if (found.length) {
            push.apply(result, found);
        }
    }
    return cash(result.length && unique(result));
}; // @require core/cash.js
// @require core/find.js
// @require core/type_checking.js
// @require collection/filter.js
fn.has = function (selector) {
    var comparator = isString(selector)
        ? function (i, ele) {
            return !!find(selector, ele).length;
        }
        : function (i, ele) {
            return ele.contains(selector);
        };
    return this.filter(comparator);
}; // @require core/cash.js
// @require core/get_compare_function.js
// @require collection/each.js
fn.is = function (selector) {
    if (!selector || !this[0])
        return false;
    var comparator = getCompareFunction(selector);
    var check = false;
    this.each(function (i, ele) {
        check = comparator(i, ele, selector);
        return !check;
    });
    return check;
}; // @require core/cash.js
fn.next = function () {
    return cash(this[0] && this[0].nextElementSibling);
}; // @require core/cash.js
// @require core/get_compare_function.js
// @require collection/filter.js
fn.not = function (selector) {
    if (!selector || !this[0])
        return this;
    var comparator = getCompareFunction(selector);
    return this.filter(function (i, ele) {
        return !comparator(i, ele, selector);
    });
}; // @require core/cash.js
// @require core/unique.js
// @require collection/each.js
fn.parent = function () {
    var result = [];
    this.each(function (i, ele) {
        if (ele && ele.parentNode) {
            result.push(ele.parentNode);
        }
    });
    return cash(unique(result));
}; // @require core/cash.js
// @require core/variables.js
// @require traversal/children.js
// @require traversal/parent.js
// @require ./get.js
//FIXME Ugly file name, is there a better option?
fn.index = function (ele) {
    var child = ele ? cash(ele)[0] : this[0], collection = ele ? this : cash(child).parent().children();
    return indexOf.call(collection, child);
}; // @optional ./add.js
// @optional ./each.js
// @optional ./eq.js
// @optional ./filter.js
// @optional ./first.js
// @optional ./get.js
// @optional ./indexFn.js
// @optional ./last.js
// @optional ./map.js
// @optional ./slice.js
// @require core/cash.js
// @require collection/filter.js
// @require ./is.js
// @require ./parent.js
fn.closest = function (selector) {
    if (!selector || !this[0])
        return cash();
    if (this.is(selector))
        return this.filter(selector);
    return this.parent().closest(selector);
}; // @require core/cash.js
// @require core/matches.js
// @require core/unique.js
// @require core/variables.js
// @require collection/each.js
fn.parents = function (selector) {
    var result = [];
    var last;
    this.each(function (i, ele) {
        last = ele;
        while (last && last.parentNode && last !== doc.body.parentNode) {
            last = last.parentNode;
            if (!selector || (selector && matches(last, selector))) {
                result.push(last);
            }
        }
    });
    return cash(unique(result));
}; // @require core/cash.js
fn.prev = function () {
    return cash(this[0] && this[0].previousElementSibling);
}; // @require core/cash.js
// @require collection/filter.js
// @require ./children.js
// @require ./parent.js
fn.siblings = function () {
    var ele = this[0];
    return this.parent()
        .children()
        .filter(function (i, child) {
        return child !== ele;
    });
}; // @optional ./children.js
// @optional ./closest.js
// @optional ./contents.js
// @optional ./find.js
// @optional ./has.js
// @optional ./is.js
// @optional ./next.js
// @optional ./not.js
// @optional ./parent.js
// @optional ./parents.js
// @optional ./prev.js
// @optional ./siblings.js
// @optional attributes/index.js
// @optional collection/index.js
// @optional css/index.js
// @optional data/index.js
// @optional dimensions/index.js
// @optional events/index.js
// @optional forms/index.js
// @optional manipulation/index.js
// @optional offset/index.js
// @optional traversal/index.js
// @require core/index.js
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (cash);


/***/ }),

/***/ 491:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   $Q: () => (/* binding */ appendAtIndex),
/* harmony export */   BM: () => (/* binding */ isTextNode),
/* harmony export */   FW: () => (/* binding */ attrUp),
/* harmony export */   G1: () => (/* binding */ motionsEv),
/* harmony export */   GX: () => (/* binding */ getDocumentScroll),
/* harmony export */   L_: () => (/* binding */ removeEl),
/* harmony export */   Mx: () => (/* binding */ isDoc),
/* harmony export */   R3: () => (/* binding */ append),
/* harmony export */   S1: () => (/* binding */ off),
/* harmony export */   SJ: () => (/* binding */ appendVNodes),
/* harmony export */   Ut: () => (/* binding */ getElRect),
/* harmony export */   VB: () => (/* binding */ getPointerEvent),
/* harmony export */   Vb: () => (/* binding */ hasModifierKey),
/* harmony export */   cx: () => (/* binding */ cx),
/* harmony export */   dL: () => (/* binding */ replaceWith),
/* harmony export */   kl: () => (/* binding */ isEscKey),
/* harmony export */   o5: () => (/* binding */ isTaggableNode),
/* harmony export */   on: () => (/* binding */ on),
/* harmony export */   pn: () => (/* binding */ isVisible),
/* harmony export */   r$: () => (/* binding */ isEnterKey),
/* harmony export */   rw: () => (/* binding */ createText),
/* harmony export */   sE: () => (/* binding */ find),
/* harmony export */   sN: () => (/* binding */ getKeyChar),
/* harmony export */   t3: () => (/* binding */ createCustomEvent),
/* harmony export */   ut: () => (/* binding */ createEl)
/* harmony export */ });
/* unused harmony exports empty, isCommentNode, getKeyCode, hasCtrlKey */
/* harmony import */ var underscore__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(50);
var __spreadArray = (undefined && undefined.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};

var KEY_TAG = 'tag';
var KEY_ATTR = 'attributes';
var KEY_CHILD = 'children';
var motionsEv = 'transitionend oTransitionEnd transitionend webkitTransitionEnd';
var isDoc = function (el) { return (el === null || el === void 0 ? void 0 : el.nodeType) === Node.DOCUMENT_NODE; };
var removeEl = function (el) {
    var parent = el && el.parentNode;
    parent && parent.removeChild(el);
};
function cx() {
    var inputs = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        inputs[_i] = arguments[_i];
    }
    var inp = Array.isArray(inputs[0]) ? inputs[0] : __spreadArray([], inputs, true);
    return inp.filter(Boolean).join(' ');
}
var find = function (el, query) { return el.querySelectorAll(query); };
var attrUp = function (el, attrs) {
    if (attrs === void 0) { attrs = {}; }
    return el && el.setAttribute && (0,underscore__WEBPACK_IMPORTED_MODULE_0__.each)(attrs, function (value, key) { return el.setAttribute(key, value); });
};
var isVisible = function (el) {
    var _a;
    return el && !!(el.offsetWidth || el.offsetHeight || ((_a = el.getClientRects) === null || _a === void 0 ? void 0 : _a.call(el).length));
};
var empty = function (node) {
    while (node.firstChild)
        node.removeChild(node.firstChild);
};
var replaceWith = function (oldEl, newEl) {
    var _a;
    (_a = oldEl.parentNode) === null || _a === void 0 ? void 0 : _a.replaceChild(newEl, oldEl);
};
var appendAtIndex = function (parent, child, index) {
    var childNodes = parent.childNodes;
    var total = childNodes.length;
    var at = (0,underscore__WEBPACK_IMPORTED_MODULE_0__.isUndefined)(index) ? total : index;
    if ((0,underscore__WEBPACK_IMPORTED_MODULE_0__.isString)(child)) {
        // @ts-ignore
        parent.insertAdjacentHTML('beforeEnd', child);
        child = parent.lastChild;
        parent.removeChild(child);
    }
    if (at >= total) {
        parent.appendChild(child);
    }
    else {
        parent.insertBefore(child, childNodes[at]);
    }
};
var append = function (parent, child) { return appendAtIndex(parent, child); };
var createEl = function (tag, attrs, child) {
    if (attrs === void 0) { attrs = {}; }
    var el = document.createElement(tag);
    attrs && (0,underscore__WEBPACK_IMPORTED_MODULE_0__.each)(attrs, function (value, key) { return el.setAttribute(key, value); });
    if (child) {
        if ((0,underscore__WEBPACK_IMPORTED_MODULE_0__.isString)(child))
            el.innerHTML = child;
        else
            el.appendChild(child);
    }
    return el;
};
var createText = function (str) { return document.createTextNode(str); };
// Unfortunately just creating `KeyboardEvent(e.type, e)` is not enough,
// the keyCode/which will be always `0`. Even if it's an old/deprecated
// property keymaster (and many others) still use it... using `defineProperty`
// hack seems the only way
var createCustomEvent = function (e, cls) {
    var oEvent;
    var type = e.type;
    try {
        // @ts-ignore
        oEvent = new window[cls](type, e);
    }
    catch (err) {
        oEvent = document.createEvent(cls);
        oEvent.initEvent(type, true, true);
    }
    oEvent._parentEvent = e;
    if (type.indexOf('key') === 0) {
        oEvent.keyCodeVal = e.keyCode;
        ['keyCode', 'which'].forEach(function (prop) {
            Object.defineProperty(oEvent, prop, {
                get: function () {
                    return this.keyCodeVal;
                },
            });
        });
    }
    return oEvent;
};
/**
 * Append an array of vNodes to an element
 * @param {HTMLElement} node HTML element
 * @param {Array} vNodes Array of node objects
 */
var appendVNodes = function (node, vNodes) {
    if (vNodes === void 0) { vNodes = []; }
    var vNodesArr = Array.isArray(vNodes) ? vNodes : [vNodes];
    vNodesArr.forEach(function (vnode) {
        var tag = vnode[KEY_TAG] || 'div';
        var attr = vnode[KEY_ATTR] || {};
        var el = document.createElement(tag);
        (0,underscore__WEBPACK_IMPORTED_MODULE_0__.each)(attr, function (value, key) {
            el.setAttribute(key, value);
        });
        node.appendChild(el);
    });
};
/**
 * Check if element is a text node
 * @param  {Node} el
 * @return {Boolean}
 */
var isTextNode = function (el) { return (el === null || el === void 0 ? void 0 : el.nodeType) === Node.TEXT_NODE; };
/**
 * Check if element is a comment node
 * @param  {Node} el
 * @return {Boolean}
 */
var isCommentNode = function (el) { return (el === null || el === void 0 ? void 0 : el.nodeType) === Node.COMMENT_NODE; };
/**
 * Check if taggable node
 * @param  {Node} el
 * @return {Boolean}
 */
var isTaggableNode = function (el) { return el && !isTextNode(el) && !isCommentNode(el); };
/**
 * Get DOMRect of the element.
 * @param el
 * @returns {DOMRect}
 */
var getElRect = function (el) {
    var def = {
        top: 0,
        left: 0,
        width: 0,
        height: 0,
    };
    if (!el)
        return def;
    var rectText;
    if (isTextNode(el)) {
        var range = document.createRange();
        range.selectNode(el);
        rectText = range.getBoundingClientRect();
        range.detach();
    }
    return rectText || (el.getBoundingClientRect ? el.getBoundingClientRect() : def);
};
/**
 * Get document scroll coordinates
 */
var getDocumentScroll = function (el) {
    var doc = (el === null || el === void 0 ? void 0 : el.ownerDocument) || document;
    var docEl = doc.documentElement;
    var win = doc.defaultView || window;
    return {
        x: (win.pageXOffset || docEl.scrollLeft || 0) - (docEl.clientLeft || 0),
        y: (win.pageYOffset || docEl.scrollTop || 0) - (docEl.clientTop || 0),
    };
};
var getKeyCode = function (ev) { return ev.which || ev.keyCode; };
var getKeyChar = function (ev) { return String.fromCharCode(getKeyCode(ev)); };
var getPointerEvent = function (ev) { return (ev.touches && ev.touches[0] ? ev.touches[0] : ev); };
var isEscKey = function (ev) { return getKeyCode(ev) === 27; };
var isEnterKey = function (ev) { return getKeyCode(ev) === 13; };
var hasCtrlKey = function (ev) { return ev.ctrlKey; };
var hasModifierKey = function (ev) { return hasCtrlKey(ev) || ev.metaKey; };
var on = function (el, ev, fn, opts) {
    var evs = ev.split(/\s+/);
    var els = (0,underscore__WEBPACK_IMPORTED_MODULE_0__.isArray)(el) ? el : [el];
    evs.forEach(function (ev) {
        els.forEach(function (el) { return el === null || el === void 0 ? void 0 : el.addEventListener(ev, fn, opts); });
    });
};
var off = function (el, ev, fn, opts) {
    var evs = ev.split(/\s+/);
    var els = (0,underscore__WEBPACK_IMPORTED_MODULE_0__.isArray)(el) ? el : [el];
    evs.forEach(function (ev) {
        els.forEach(function (el) { return el === null || el === void 0 ? void 0 : el.removeEventListener(ev, fn, opts); });
    });
};


/***/ }),

/***/ 163:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   appendStyles: () => (/* binding */ appendStyles),
/* harmony export */   buildBase64UrlFromSvg: () => (/* binding */ buildBase64UrlFromSvg),
/* harmony export */   camelCase: () => (/* binding */ camelCase),
/* harmony export */   capitalize: () => (/* binding */ capitalize),
/* harmony export */   createId: () => (/* binding */ createId),
/* harmony export */   deepMerge: () => (/* binding */ deepMerge),
/* harmony export */   escape: () => (/* binding */ escape),
/* harmony export */   escapeNodeContent: () => (/* binding */ escapeNodeContent),
/* harmony export */   find: () => (/* binding */ find),
/* harmony export */   getComponentModel: () => (/* binding */ getComponentModel),
/* harmony export */   getComponentView: () => (/* binding */ getComponentView),
/* harmony export */   getElement: () => (/* binding */ getElement),
/* harmony export */   getGlobal: () => (/* binding */ getGlobal),
/* harmony export */   getModel: () => (/* binding */ getModel),
/* harmony export */   getUiClass: () => (/* binding */ getUiClass),
/* harmony export */   getUnitFromValue: () => (/* binding */ getUnitFromValue),
/* harmony export */   getViewEl: () => (/* binding */ getViewEl),
/* harmony export */   hasDnd: () => (/* binding */ hasDnd),
/* harmony export */   hasWin: () => (/* binding */ hasWin),
/* harmony export */   isBultInMethod: () => (/* binding */ isBultInMethod),
/* harmony export */   isComponent: () => (/* binding */ isComponent),
/* harmony export */   isDef: () => (/* binding */ isDef),
/* harmony export */   isEmptyObj: () => (/* binding */ isEmptyObj),
/* harmony export */   isObject: () => (/* binding */ isObject),
/* harmony export */   isRule: () => (/* binding */ isRule),
/* harmony export */   matches: () => (/* binding */ matches),
/* harmony export */   normalizeFloat: () => (/* binding */ normalizeFloat),
/* harmony export */   normalizeKey: () => (/* binding */ normalizeKey),
/* harmony export */   setViewEl: () => (/* binding */ setViewEl),
/* harmony export */   shallowDiff: () => (/* binding */ shallowDiff),
/* harmony export */   toLowerCase: () => (/* binding */ toLowerCase),
/* harmony export */   upFirst: () => (/* binding */ upFirst),
/* harmony export */   wait: () => (/* binding */ wait)
/* harmony export */ });
/* harmony import */ var underscore__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(50);
/* harmony import */ var _dom__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(491);
var __assign = (undefined && undefined.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __spreadArray = (undefined && undefined.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};


var obj = {};
var isBultInMethod = function (key) { return (0,underscore__WEBPACK_IMPORTED_MODULE_0__.isFunction)(obj[key]); };
var normalizeKey = function (key) { return (isBultInMethod(key) ? "_".concat(key) : key); };
var wait = function (mls) {
    if (mls === void 0) { mls = 0; }
    return new Promise(function (res) { return setTimeout(res, mls); });
};
var isDef = function (value) { return typeof value !== 'undefined'; };
var hasWin = function () { return typeof window !== 'undefined'; };
var getGlobal = function () {
    return typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : __webpack_require__.g;
};
var toLowerCase = function (str) { return (str || '').toLowerCase(); };
var elProt = hasWin() ? window.Element.prototype : {};
// @ts-ignore
var matches = elProt.matches || elProt.webkitMatchesSelector || elProt.mozMatchesSelector || elProt.msMatchesSelector;
var getUiClass = function (em, defCls) {
    var _a = em.getConfig(), stylePrefix = _a.stylePrefix, customUI = _a.customUI;
    return [customUI && "".concat(stylePrefix, "cui"), defCls].filter(function (i) { return i; }).join(' ');
};
/**
 * Import styles asynchronously
 * @param {String|Array<String>} styles
 */
var appendStyles = function (styles, opts) {
    if (opts === void 0) { opts = {}; }
    var stls = (0,underscore__WEBPACK_IMPORTED_MODULE_0__.isArray)(styles) ? __spreadArray([], styles, true) : [styles];
    if (stls.length) {
        var href = stls.shift();
        if (href && (!opts.unique || !document.querySelector("link[href=\"".concat(href, "\"]")))) {
            var head = document.head;
            var link = document.createElement('link');
            link.href = href;
            link.rel = 'stylesheet';
            if (opts.prepand) {
                head.insertBefore(link, head.firstChild);
            }
            else {
                head.appendChild(link);
            }
        }
        appendStyles(stls);
    }
};
/**
 * Returns shallow diff between 2 objects
 * @param  {Object} objOrig
 * @param  {Objec} objNew
 * @return {Object}
 * @example
 * var a = {foo: 'bar', baz: 1, faz: 'sop'};
 * var b = {foo: 'bar', baz: 2, bar: ''};
 * shallowDiff(a, b);
 * // -> {baz: 2, faz: null, bar: ''};
 */
var shallowDiff = function (objOrig, objNew) {
    var result = {};
    var keysNew = (0,underscore__WEBPACK_IMPORTED_MODULE_0__.keys)(objNew);
    for (var prop in objOrig) {
        if (objOrig.hasOwnProperty(prop)) {
            var origValue = objOrig[prop];
            var newValue = objNew[prop];
            if (keysNew.indexOf(prop) >= 0) {
                if (origValue !== newValue) {
                    result[prop] = newValue;
                }
            }
            else {
                result[prop] = null;
            }
        }
    }
    for (var prop in objNew) {
        if (objNew.hasOwnProperty(prop)) {
            if ((0,underscore__WEBPACK_IMPORTED_MODULE_0__.isUndefined)(objOrig[prop])) {
                result[prop] = objNew[prop];
            }
        }
    }
    return result;
};
var getUnitFromValue = function (value) {
    return value.replace(parseFloat(value), '');
};
var upFirst = function (value) { return value[0].toUpperCase() + value.toLowerCase().slice(1); };
var camelCase = function (value) {
    return value.replace(/-./g, function (x) { return x[1].toUpperCase(); });
};
var normalizeFloat = function (value, step, valueDef) {
    if (step === void 0) { step = 1; }
    if (valueDef === void 0) { valueDef = 0; }
    var stepDecimals = 0;
    if (isNaN(value))
        return valueDef;
    value = parseFloat(value);
    if (Math.floor(value) !== value) {
        var side = step.toString().split('.')[1];
        stepDecimals = side ? side.length : 0;
    }
    return stepDecimals ? parseFloat(value.toFixed(stepDecimals)) : value;
};
var hasDnd = function (em) {
    return 'draggable' in document.createElement('i') && (em ? em.config.nativeDnD : true);
};
/**
 * Ensure to fetch the element from the input argument
 * @param  {HTMLElement|Component} el Component or HTML element
 * @return {HTMLElement}
 */
var getElement = function (el) {
    if ((0,underscore__WEBPACK_IMPORTED_MODULE_0__.isElement)(el) || (0,_dom__WEBPACK_IMPORTED_MODULE_1__/* .isTextNode */ .BM)(el)) {
        return el;
        // @ts-ignore
    }
    else if (el && el.getEl) {
        // @ts-ignore
        return el.getEl();
    }
};
var find = function (arr, test) {
    var result = null;
    arr.some(function (el, i) { return (test(el, i, arr) ? ((result = el), 1) : 0); });
    return result;
};
var escape = function (str) {
    if (str === void 0) { str = ''; }
    return "".concat(str)
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;')
        .replace(/`/g, '&#96;');
};
var escapeNodeContent = function (str) {
    if (str === void 0) { str = ''; }
    return "".concat(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
};
var deepMerge = function () {
    var args = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        args[_i] = arguments[_i];
    }
    var target = __assign({}, args[0]);
    for (var i = 1; i < args.length; i++) {
        var source = __assign({}, args[i]);
        for (var key in source) {
            var targValue = target[key];
            var srcValue = source[key];
            if (isObject(targValue) && isObject(srcValue)) {
                target[key] = deepMerge(targValue, srcValue);
            }
            else {
                target[key] = srcValue;
            }
        }
    }
    return target;
};
/**
 * Ensure to fetch the model from the input argument
 * @param  {HTMLElement|Component} el Component or HTML element
 * @return {Component}
 */
var getModel = function (el, $) {
    var model;
    if (!$ && el && el.__cashData) {
        model = el.__cashData.model;
    }
    else if ($ && (0,underscore__WEBPACK_IMPORTED_MODULE_0__.isElement)(el)) {
        model = $(el).data('model');
    }
    return model;
};
var isObject = function (val) { return val && !Array.isArray(val) && typeof val === 'object'; };
var isEmptyObj = function (val) { return Object.keys(val).length <= 0; };
var capitalize = function (str) {
    if (str === void 0) { str = ''; }
    return str && str.charAt(0).toUpperCase() + str.substring(1);
};
var isRule = function (obj) { return obj && obj.toCSS; };
var getViewEl = function (el) { return el === null || el === void 0 ? void 0 : el.__gjsv; };
var isComponent = function (obj) { return !!(obj === null || obj === void 0 ? void 0 : obj.toHTML); };
var getComponentView = function (el) { return getViewEl(el); };
var getComponentModel = function (el) { var _a; return (_a = getComponentView(el)) === null || _a === void 0 ? void 0 : _a.model; };
var setViewEl = function (el, view) {
    el.__gjsv = view;
};
var createId = function (length) {
    if (length === void 0) { length = 16; }
    var result = '';
    var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    var len = chars.length;
    for (var i = 0; i < length; i++) {
        result += chars.charAt(Math.floor(Math.random() * len));
    }
    return result;
};
var buildBase64UrlFromSvg = function (svg) {
    if (svg && svg.substr(0, 4) === '<svg') {
        var base64Str = '';
        if (hasWin()) {
            base64Str = window.btoa(svg);
        }
        else if (typeof Buffer !== 'undefined') {
            base64Str = Buffer.from(svg, 'utf8').toString('base64');
        }
        return base64Str ? "data:image/svg+xml;base64,".concat(base64Str) : svg;
    }
    return svg;
};



/***/ }),

/***/ 828:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var map = {
	"./CanvasClear": 858,
	"./CanvasClear.ts": 858,
	"./CanvasMove": 884,
	"./CanvasMove.ts": 884,
	"./CommandAbstract": 790,
	"./CommandAbstract.ts": 790,
	"./ComponentDelete": 180,
	"./ComponentDelete.ts": 180,
	"./ComponentDrag": 544,
	"./ComponentDrag.ts": 544,
	"./ComponentEnter": 236,
	"./ComponentEnter.ts": 236,
	"./ComponentExit": 368,
	"./ComponentExit.ts": 368,
	"./ComponentNext": 243,
	"./ComponentNext.ts": 243,
	"./ComponentPrev": 400,
	"./ComponentPrev.ts": 400,
	"./ComponentStyleClear": 910,
	"./ComponentStyleClear.ts": 910,
	"./CopyComponent": 744,
	"./CopyComponent.ts": 744,
	"./ExportTemplate": 457,
	"./ExportTemplate.ts": 457,
	"./Fullscreen": 975,
	"./Fullscreen.ts": 975,
	"./MoveComponent": 191,
	"./MoveComponent.ts": 191,
	"./OpenAssets": 912,
	"./OpenAssets.ts": 912,
	"./OpenBlocks": 117,
	"./OpenBlocks.ts": 117,
	"./OpenLayers": 614,
	"./OpenLayers.ts": 614,
	"./OpenStyleManager": 801,
	"./OpenStyleManager.ts": 801,
	"./OpenTraitManager": 395,
	"./OpenTraitManager.ts": 395,
	"./PasteComponent": 98,
	"./PasteComponent.ts": 98,
	"./Preview": 129,
	"./Preview.ts": 129,
	"./Resize": 116,
	"./Resize.ts": 116,
	"./SelectComponent": 407,
	"./SelectComponent.ts": 407,
	"./SelectPosition": 189,
	"./SelectPosition.ts": 189,
	"./ShowOffset": 804,
	"./ShowOffset.ts": 804,
	"./SwitchVisibility": 434,
	"./SwitchVisibility.ts": 434
};


function webpackContext(req) {
	var id = webpackContextResolve(req);
	return __webpack_require__(id);
}
function webpackContextResolve(req) {
	if(!__webpack_require__.o(map, req)) {
		var e = new Error("Cannot find module '" + req + "'");
		e.code = 'MODULE_NOT_FOUND';
		throw e;
	}
	return map[req];
}
webpackContext.keys = function webpackContextKeys() {
	return Object.keys(map);
};
webpackContext.resolve = webpackContextResolve;
module.exports = webpackContext;
webpackContext.id = 828;

/***/ }),

/***/ 50:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  VERSION: () => (/* reexport */ VERSION),
  after: () => (/* reexport */ after),
  all: () => (/* reexport */ every),
  allKeys: () => (/* reexport */ allKeys),
  any: () => (/* reexport */ some),
  assign: () => (/* reexport */ extendOwn),
  before: () => (/* reexport */ before),
  bind: () => (/* reexport */ bind),
  bindAll: () => (/* reexport */ bindAll),
  chain: () => (/* reexport */ chain),
  chunk: () => (/* reexport */ chunk),
  clone: () => (/* reexport */ clone),
  collect: () => (/* reexport */ map),
  compact: () => (/* reexport */ compact),
  compose: () => (/* reexport */ compose),
  constant: () => (/* reexport */ constant),
  contains: () => (/* reexport */ contains),
  countBy: () => (/* reexport */ countBy),
  create: () => (/* reexport */ create),
  debounce: () => (/* reexport */ debounce),
  "default": () => (/* reexport */ index_default),
  defaults: () => (/* reexport */ defaults),
  defer: () => (/* reexport */ defer),
  delay: () => (/* reexport */ delay),
  detect: () => (/* reexport */ find),
  difference: () => (/* reexport */ difference),
  drop: () => (/* reexport */ rest),
  each: () => (/* reexport */ each),
  escape: () => (/* reexport */ modules_escape),
  every: () => (/* reexport */ every),
  extend: () => (/* reexport */ extend),
  extendOwn: () => (/* reexport */ extendOwn),
  filter: () => (/* reexport */ filter),
  find: () => (/* reexport */ find),
  findIndex: () => (/* reexport */ findIndex),
  findKey: () => (/* reexport */ findKey),
  findLastIndex: () => (/* reexport */ findLastIndex),
  findWhere: () => (/* reexport */ findWhere),
  first: () => (/* reexport */ first),
  flatten: () => (/* reexport */ flatten_flatten),
  foldl: () => (/* reexport */ reduce),
  foldr: () => (/* reexport */ reduceRight),
  forEach: () => (/* reexport */ each),
  functions: () => (/* reexport */ functions),
  get: () => (/* reexport */ get),
  groupBy: () => (/* reexport */ groupBy),
  has: () => (/* reexport */ has_has),
  head: () => (/* reexport */ first),
  identity: () => (/* reexport */ identity),
  include: () => (/* reexport */ contains),
  includes: () => (/* reexport */ contains),
  indexBy: () => (/* reexport */ indexBy),
  indexOf: () => (/* reexport */ indexOf),
  initial: () => (/* reexport */ initial),
  inject: () => (/* reexport */ reduce),
  intersection: () => (/* reexport */ intersection),
  invert: () => (/* reexport */ invert),
  invoke: () => (/* reexport */ invoke),
  isArguments: () => (/* reexport */ modules_isArguments),
  isArray: () => (/* reexport */ isArray),
  isArrayBuffer: () => (/* reexport */ isArrayBuffer),
  isBoolean: () => (/* reexport */ isBoolean),
  isDataView: () => (/* reexport */ modules_isDataView),
  isDate: () => (/* reexport */ isDate),
  isElement: () => (/* reexport */ isElement),
  isEmpty: () => (/* reexport */ isEmpty),
  isEqual: () => (/* reexport */ isEqual),
  isError: () => (/* reexport */ isError),
  isFinite: () => (/* reexport */ isFinite_isFinite),
  isFunction: () => (/* reexport */ modules_isFunction),
  isMap: () => (/* reexport */ isMap),
  isMatch: () => (/* reexport */ isMatch),
  isNaN: () => (/* reexport */ isNaN_isNaN),
  isNull: () => (/* reexport */ isNull),
  isNumber: () => (/* reexport */ isNumber),
  isObject: () => (/* reexport */ isObject),
  isRegExp: () => (/* reexport */ isRegExp),
  isSet: () => (/* reexport */ isSet),
  isString: () => (/* reexport */ isString),
  isSymbol: () => (/* reexport */ isSymbol),
  isTypedArray: () => (/* reexport */ modules_isTypedArray),
  isUndefined: () => (/* reexport */ isUndefined),
  isWeakMap: () => (/* reexport */ isWeakMap),
  isWeakSet: () => (/* reexport */ isWeakSet),
  iteratee: () => (/* reexport */ iteratee),
  keys: () => (/* reexport */ keys),
  last: () => (/* reexport */ last),
  lastIndexOf: () => (/* reexport */ lastIndexOf),
  map: () => (/* reexport */ map),
  mapObject: () => (/* reexport */ mapObject),
  matcher: () => (/* reexport */ matcher),
  matches: () => (/* reexport */ matcher),
  max: () => (/* reexport */ max),
  memoize: () => (/* reexport */ memoize),
  methods: () => (/* reexport */ functions),
  min: () => (/* reexport */ min),
  mixin: () => (/* reexport */ mixin),
  negate: () => (/* reexport */ negate),
  noop: () => (/* reexport */ noop),
  now: () => (/* reexport */ now),
  object: () => (/* reexport */ object),
  omit: () => (/* reexport */ omit),
  once: () => (/* reexport */ once),
  pairs: () => (/* reexport */ pairs),
  partial: () => (/* reexport */ modules_partial),
  partition: () => (/* reexport */ partition),
  pick: () => (/* reexport */ pick),
  pluck: () => (/* reexport */ pluck),
  property: () => (/* reexport */ property),
  propertyOf: () => (/* reexport */ propertyOf),
  random: () => (/* reexport */ random),
  range: () => (/* reexport */ range),
  reduce: () => (/* reexport */ reduce),
  reduceRight: () => (/* reexport */ reduceRight),
  reject: () => (/* reexport */ reject),
  rest: () => (/* reexport */ rest),
  restArguments: () => (/* reexport */ restArguments),
  result: () => (/* reexport */ result),
  sample: () => (/* reexport */ sample),
  select: () => (/* reexport */ filter),
  shuffle: () => (/* reexport */ shuffle),
  size: () => (/* reexport */ size),
  some: () => (/* reexport */ some),
  sortBy: () => (/* reexport */ sortBy),
  sortedIndex: () => (/* reexport */ sortedIndex),
  tail: () => (/* reexport */ rest),
  take: () => (/* reexport */ first),
  tap: () => (/* reexport */ tap),
  template: () => (/* reexport */ template),
  templateSettings: () => (/* reexport */ templateSettings),
  throttle: () => (/* reexport */ throttle),
  times: () => (/* reexport */ times),
  toArray: () => (/* reexport */ toArray),
  toPath: () => (/* reexport */ toPath),
  transpose: () => (/* reexport */ unzip),
  unescape: () => (/* reexport */ modules_unescape),
  union: () => (/* reexport */ union),
  uniq: () => (/* reexport */ uniq),
  unique: () => (/* reexport */ uniq),
  uniqueId: () => (/* reexport */ uniqueId),
  unzip: () => (/* reexport */ unzip),
  values: () => (/* reexport */ values),
  where: () => (/* reexport */ where),
  without: () => (/* reexport */ without),
  wrap: () => (/* reexport */ wrap),
  zip: () => (/* reexport */ zip)
});

// NAMESPACE OBJECT: ./node_modules/underscore/modules/index.js
var modules_namespaceObject = {};
__webpack_require__.r(modules_namespaceObject);
__webpack_require__.d(modules_namespaceObject, {
  VERSION: () => (VERSION),
  after: () => (after),
  all: () => (every),
  allKeys: () => (allKeys),
  any: () => (some),
  assign: () => (extendOwn),
  before: () => (before),
  bind: () => (bind),
  bindAll: () => (bindAll),
  chain: () => (chain),
  chunk: () => (chunk),
  clone: () => (clone),
  collect: () => (map),
  compact: () => (compact),
  compose: () => (compose),
  constant: () => (constant),
  contains: () => (contains),
  countBy: () => (countBy),
  create: () => (create),
  debounce: () => (debounce),
  "default": () => (underscore_array_methods),
  defaults: () => (defaults),
  defer: () => (defer),
  delay: () => (delay),
  detect: () => (find),
  difference: () => (difference),
  drop: () => (rest),
  each: () => (each),
  escape: () => (modules_escape),
  every: () => (every),
  extend: () => (extend),
  extendOwn: () => (extendOwn),
  filter: () => (filter),
  find: () => (find),
  findIndex: () => (findIndex),
  findKey: () => (findKey),
  findLastIndex: () => (findLastIndex),
  findWhere: () => (findWhere),
  first: () => (first),
  flatten: () => (flatten_flatten),
  foldl: () => (reduce),
  foldr: () => (reduceRight),
  forEach: () => (each),
  functions: () => (functions),
  get: () => (get),
  groupBy: () => (groupBy),
  has: () => (has_has),
  head: () => (first),
  identity: () => (identity),
  include: () => (contains),
  includes: () => (contains),
  indexBy: () => (indexBy),
  indexOf: () => (indexOf),
  initial: () => (initial),
  inject: () => (reduce),
  intersection: () => (intersection),
  invert: () => (invert),
  invoke: () => (invoke),
  isArguments: () => (modules_isArguments),
  isArray: () => (isArray),
  isArrayBuffer: () => (isArrayBuffer),
  isBoolean: () => (isBoolean),
  isDataView: () => (modules_isDataView),
  isDate: () => (isDate),
  isElement: () => (isElement),
  isEmpty: () => (isEmpty),
  isEqual: () => (isEqual),
  isError: () => (isError),
  isFinite: () => (isFinite_isFinite),
  isFunction: () => (modules_isFunction),
  isMap: () => (isMap),
  isMatch: () => (isMatch),
  isNaN: () => (isNaN_isNaN),
  isNull: () => (isNull),
  isNumber: () => (isNumber),
  isObject: () => (isObject),
  isRegExp: () => (isRegExp),
  isSet: () => (isSet),
  isString: () => (isString),
  isSymbol: () => (isSymbol),
  isTypedArray: () => (modules_isTypedArray),
  isUndefined: () => (isUndefined),
  isWeakMap: () => (isWeakMap),
  isWeakSet: () => (isWeakSet),
  iteratee: () => (iteratee),
  keys: () => (keys),
  last: () => (last),
  lastIndexOf: () => (lastIndexOf),
  map: () => (map),
  mapObject: () => (mapObject),
  matcher: () => (matcher),
  matches: () => (matcher),
  max: () => (max),
  memoize: () => (memoize),
  methods: () => (functions),
  min: () => (min),
  mixin: () => (mixin),
  negate: () => (negate),
  noop: () => (noop),
  now: () => (now),
  object: () => (object),
  omit: () => (omit),
  once: () => (once),
  pairs: () => (pairs),
  partial: () => (modules_partial),
  partition: () => (partition),
  pick: () => (pick),
  pluck: () => (pluck),
  property: () => (property),
  propertyOf: () => (propertyOf),
  random: () => (random),
  range: () => (range),
  reduce: () => (reduce),
  reduceRight: () => (reduceRight),
  reject: () => (reject),
  rest: () => (rest),
  restArguments: () => (restArguments),
  result: () => (result),
  sample: () => (sample),
  select: () => (filter),
  shuffle: () => (shuffle),
  size: () => (size),
  some: () => (some),
  sortBy: () => (sortBy),
  sortedIndex: () => (sortedIndex),
  tail: () => (rest),
  take: () => (first),
  tap: () => (tap),
  template: () => (template),
  templateSettings: () => (templateSettings),
  throttle: () => (throttle),
  times: () => (times),
  toArray: () => (toArray),
  toPath: () => (toPath),
  transpose: () => (unzip),
  unescape: () => (modules_unescape),
  union: () => (union),
  uniq: () => (uniq),
  unique: () => (uniq),
  uniqueId: () => (uniqueId),
  unzip: () => (unzip),
  values: () => (values),
  where: () => (where),
  without: () => (without),
  wrap: () => (wrap),
  zip: () => (zip)
});

;// CONCATENATED MODULE: ./node_modules/underscore/modules/_setup.js
// Current version.
var VERSION = '1.13.6';

// Establish the root object, `window` (`self`) in the browser, `global`
// on the server, or `this` in some virtual machines. We use `self`
// instead of `window` for `WebWorker` support.
var root = (typeof self == 'object' && self.self === self && self) ||
          (typeof global == 'object' && global.global === global && global) ||
          Function('return this')() ||
          {};

// Save bytes in the minified (but not gzipped) version:
var ArrayProto = Array.prototype, ObjProto = Object.prototype;
var SymbolProto = typeof Symbol !== 'undefined' ? Symbol.prototype : null;

// Create quick reference variables for speed access to core prototypes.
var push = ArrayProto.push,
    slice = ArrayProto.slice,
    _setup_toString = ObjProto.toString,
    _setup_hasOwnProperty = ObjProto.hasOwnProperty;

// Modern feature detection.
var supportsArrayBuffer = typeof ArrayBuffer !== 'undefined',
    supportsDataView = typeof DataView !== 'undefined';

// All **ECMAScript 5+** native function implementations that we hope to use
// are declared here.
var nativeIsArray = Array.isArray,
    nativeKeys = Object.keys,
    nativeCreate = Object.create,
    nativeIsView = supportsArrayBuffer && ArrayBuffer.isView;

// Create references to these builtin functions because we override them.
var _isNaN = isNaN,
    _isFinite = isFinite;

// Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed.
var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString');
var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString',
  'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];

// The largest integer that can be represented exactly.
var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1;

;// CONCATENATED MODULE: ./node_modules/underscore/modules/restArguments.js
// Some functions take a variable number of arguments, or a few expected
// arguments at the beginning and then a variable number of values to operate
// on. This helper accumulates all remaining arguments past the function’s
// argument length (or an explicit `startIndex`), into an array that becomes
// the last argument. Similar to ES6’s "rest parameter".
function restArguments(func, startIndex) {
  startIndex = startIndex == null ? func.length - 1 : +startIndex;
  return function() {
    var length = Math.max(arguments.length - startIndex, 0),
        rest = Array(length),
        index = 0;
    for (; index < length; index++) {
      rest[index] = arguments[index + startIndex];
    }
    switch (startIndex) {
      case 0: return func.call(this, rest);
      case 1: return func.call(this, arguments[0], rest);
      case 2: return func.call(this, arguments[0], arguments[1], rest);
    }
    var args = Array(startIndex + 1);
    for (index = 0; index < startIndex; index++) {
      args[index] = arguments[index];
    }
    args[startIndex] = rest;
    return func.apply(this, args);
  };
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/isObject.js
// Is a given variable an object?
function isObject(obj) {
  var type = typeof obj;
  return type === 'function' || (type === 'object' && !!obj);
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/isNull.js
// Is a given value equal to null?
function isNull(obj) {
  return obj === null;
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/isUndefined.js
// Is a given variable undefined?
function isUndefined(obj) {
  return obj === void 0;
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/isBoolean.js


// Is a given value a boolean?
function isBoolean(obj) {
  return obj === true || obj === false || _setup_toString.call(obj) === '[object Boolean]';
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/isElement.js
// Is a given value a DOM element?
function isElement(obj) {
  return !!(obj && obj.nodeType === 1);
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/_tagTester.js


// Internal function for creating a `toString`-based type tester.
function tagTester(name) {
  var tag = '[object ' + name + ']';
  return function(obj) {
    return _setup_toString.call(obj) === tag;
  };
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/isString.js


/* harmony default export */ const isString = (tagTester('String'));

;// CONCATENATED MODULE: ./node_modules/underscore/modules/isNumber.js


/* harmony default export */ const isNumber = (tagTester('Number'));

;// CONCATENATED MODULE: ./node_modules/underscore/modules/isDate.js


/* harmony default export */ const isDate = (tagTester('Date'));

;// CONCATENATED MODULE: ./node_modules/underscore/modules/isRegExp.js


/* harmony default export */ const isRegExp = (tagTester('RegExp'));

;// CONCATENATED MODULE: ./node_modules/underscore/modules/isError.js


/* harmony default export */ const isError = (tagTester('Error'));

;// CONCATENATED MODULE: ./node_modules/underscore/modules/isSymbol.js


/* harmony default export */ const isSymbol = (tagTester('Symbol'));

;// CONCATENATED MODULE: ./node_modules/underscore/modules/isArrayBuffer.js


/* harmony default export */ const isArrayBuffer = (tagTester('ArrayBuffer'));

;// CONCATENATED MODULE: ./node_modules/underscore/modules/isFunction.js



var isFunction = tagTester('Function');

// Optimize `isFunction` if appropriate. Work around some `typeof` bugs in old
// v8, IE 11 (#1621), Safari 8 (#1929), and PhantomJS (#2236).
var nodelist = root.document && root.document.childNodes;
if ( true && typeof Int8Array != 'object' && typeof nodelist != 'function') {
  isFunction = function(obj) {
    return typeof obj == 'function' || false;
  };
}

/* harmony default export */ const modules_isFunction = (isFunction);

;// CONCATENATED MODULE: ./node_modules/underscore/modules/_hasObjectTag.js


/* harmony default export */ const _hasObjectTag = (tagTester('Object'));

;// CONCATENATED MODULE: ./node_modules/underscore/modules/_stringTagBug.js



// In IE 10 - Edge 13, `DataView` has string tag `'[object Object]'`.
// In IE 11, the most common among them, this problem also applies to
// `Map`, `WeakMap` and `Set`.
var hasStringTagBug = (
      supportsDataView && _hasObjectTag(new DataView(new ArrayBuffer(8)))
    ),
    isIE11 = (typeof Map !== 'undefined' && _hasObjectTag(new Map));

;// CONCATENATED MODULE: ./node_modules/underscore/modules/isDataView.js





var isDataView = tagTester('DataView');

// In IE 10 - Edge 13, we need a different heuristic
// to determine whether an object is a `DataView`.
function ie10IsDataView(obj) {
  return obj != null && modules_isFunction(obj.getInt8) && isArrayBuffer(obj.buffer);
}

/* harmony default export */ const modules_isDataView = (hasStringTagBug ? ie10IsDataView : isDataView);

;// CONCATENATED MODULE: ./node_modules/underscore/modules/isArray.js



// Is a given value an array?
// Delegates to ECMA5's native `Array.isArray`.
/* harmony default export */ const isArray = (nativeIsArray || tagTester('Array'));

;// CONCATENATED MODULE: ./node_modules/underscore/modules/_has.js


// Internal function to check whether `key` is an own property name of `obj`.
function has(obj, key) {
  return obj != null && _setup_hasOwnProperty.call(obj, key);
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/isArguments.js



var isArguments = tagTester('Arguments');

// Define a fallback version of the method in browsers (ahem, IE < 9), where
// there isn't any inspectable "Arguments" type.
(function() {
  if (!isArguments(arguments)) {
    isArguments = function(obj) {
      return has(obj, 'callee');
    };
  }
}());

/* harmony default export */ const modules_isArguments = (isArguments);

;// CONCATENATED MODULE: ./node_modules/underscore/modules/isFinite.js



// Is a given object a finite number?
function isFinite_isFinite(obj) {
  return !isSymbol(obj) && _isFinite(obj) && !isNaN(parseFloat(obj));
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/isNaN.js



// Is the given value `NaN`?
function isNaN_isNaN(obj) {
  return isNumber(obj) && _isNaN(obj);
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/constant.js
// Predicate-generating function. Often useful outside of Underscore.
function constant(value) {
  return function() {
    return value;
  };
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/_createSizePropertyCheck.js


// Common internal logic for `isArrayLike` and `isBufferLike`.
function createSizePropertyCheck(getSizeProperty) {
  return function(collection) {
    var sizeProperty = getSizeProperty(collection);
    return typeof sizeProperty == 'number' && sizeProperty >= 0 && sizeProperty <= MAX_ARRAY_INDEX;
  }
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/_shallowProperty.js
// Internal helper to generate a function to obtain property `key` from `obj`.
function shallowProperty(key) {
  return function(obj) {
    return obj == null ? void 0 : obj[key];
  };
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/_getByteLength.js


// Internal helper to obtain the `byteLength` property of an object.
/* harmony default export */ const _getByteLength = (shallowProperty('byteLength'));

;// CONCATENATED MODULE: ./node_modules/underscore/modules/_isBufferLike.js



// Internal helper to determine whether we should spend extensive checks against
// `ArrayBuffer` et al.
/* harmony default export */ const _isBufferLike = (createSizePropertyCheck(_getByteLength));

;// CONCATENATED MODULE: ./node_modules/underscore/modules/isTypedArray.js





// Is a given value a typed array?
var typedArrayPattern = /\[object ((I|Ui)nt(8|16|32)|Float(32|64)|Uint8Clamped|Big(I|Ui)nt64)Array\]/;
function isTypedArray(obj) {
  // `ArrayBuffer.isView` is the most future-proof, so use it when available.
  // Otherwise, fall back on the above regular expression.
  return nativeIsView ? (nativeIsView(obj) && !modules_isDataView(obj)) :
                _isBufferLike(obj) && typedArrayPattern.test(_setup_toString.call(obj));
}

/* harmony default export */ const modules_isTypedArray = (supportsArrayBuffer ? isTypedArray : constant(false));

;// CONCATENATED MODULE: ./node_modules/underscore/modules/_getLength.js


// Internal helper to obtain the `length` property of an object.
/* harmony default export */ const _getLength = (shallowProperty('length'));

;// CONCATENATED MODULE: ./node_modules/underscore/modules/_collectNonEnumProps.js




// Internal helper to create a simple lookup structure.
// `collectNonEnumProps` used to depend on `_.contains`, but this led to
// circular imports. `emulatedSet` is a one-off solution that only works for
// arrays of strings.
function emulatedSet(keys) {
  var hash = {};
  for (var l = keys.length, i = 0; i < l; ++i) hash[keys[i]] = true;
  return {
    contains: function(key) { return hash[key] === true; },
    push: function(key) {
      hash[key] = true;
      return keys.push(key);
    }
  };
}

// Internal helper. Checks `keys` for the presence of keys in IE < 9 that won't
// be iterated by `for key in ...` and thus missed. Extends `keys` in place if
// needed.
function collectNonEnumProps(obj, keys) {
  keys = emulatedSet(keys);
  var nonEnumIdx = nonEnumerableProps.length;
  var constructor = obj.constructor;
  var proto = (modules_isFunction(constructor) && constructor.prototype) || ObjProto;

  // Constructor is a special case.
  var prop = 'constructor';
  if (has(obj, prop) && !keys.contains(prop)) keys.push(prop);

  while (nonEnumIdx--) {
    prop = nonEnumerableProps[nonEnumIdx];
    if (prop in obj && obj[prop] !== proto[prop] && !keys.contains(prop)) {
      keys.push(prop);
    }
  }
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/keys.js





// Retrieve the names of an object's own properties.
// Delegates to **ECMAScript 5**'s native `Object.keys`.
function keys(obj) {
  if (!isObject(obj)) return [];
  if (nativeKeys) return nativeKeys(obj);
  var keys = [];
  for (var key in obj) if (has(obj, key)) keys.push(key);
  // Ahem, IE < 9.
  if (hasEnumBug) collectNonEnumProps(obj, keys);
  return keys;
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/isEmpty.js






// Is a given array, string, or object empty?
// An "empty" object has no enumerable own-properties.
function isEmpty(obj) {
  if (obj == null) return true;
  // Skip the more expensive `toString`-based type checks if `obj` has no
  // `.length`.
  var length = _getLength(obj);
  if (typeof length == 'number' && (
    isArray(obj) || isString(obj) || modules_isArguments(obj)
  )) return length === 0;
  return _getLength(keys(obj)) === 0;
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/isMatch.js


// Returns whether an object has a given set of `key:value` pairs.
function isMatch(object, attrs) {
  var _keys = keys(attrs), length = _keys.length;
  if (object == null) return !length;
  var obj = Object(object);
  for (var i = 0; i < length; i++) {
    var key = _keys[i];
    if (attrs[key] !== obj[key] || !(key in obj)) return false;
  }
  return true;
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/underscore.js


// If Underscore is called as a function, it returns a wrapped object that can
// be used OO-style. This wrapper holds altered versions of all functions added
// through `_.mixin`. Wrapped objects may be chained.
function _(obj) {
  if (obj instanceof _) return obj;
  if (!(this instanceof _)) return new _(obj);
  this._wrapped = obj;
}

_.VERSION = VERSION;

// Extracts the result from a wrapped and chained object.
_.prototype.value = function() {
  return this._wrapped;
};

// Provide unwrapping proxies for some methods used in engine operations
// such as arithmetic and JSON stringification.
_.prototype.valueOf = _.prototype.toJSON = _.prototype.value;

_.prototype.toString = function() {
  return String(this._wrapped);
};

;// CONCATENATED MODULE: ./node_modules/underscore/modules/_toBufferView.js


// Internal function to wrap or shallow-copy an ArrayBuffer,
// typed array or DataView to a new view, reusing the buffer.
function toBufferView(bufferSource) {
  return new Uint8Array(
    bufferSource.buffer || bufferSource,
    bufferSource.byteOffset || 0,
    _getByteLength(bufferSource)
  );
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/isEqual.js











// We use this string twice, so give it a name for minification.
var tagDataView = '[object DataView]';

// Internal recursive comparison function for `_.isEqual`.
function eq(a, b, aStack, bStack) {
  // Identical objects are equal. `0 === -0`, but they aren't identical.
  // See the [Harmony `egal` proposal](https://wiki.ecmascript.org/doku.php?id=harmony:egal).
  if (a === b) return a !== 0 || 1 / a === 1 / b;
  // `null` or `undefined` only equal to itself (strict comparison).
  if (a == null || b == null) return false;
  // `NaN`s are equivalent, but non-reflexive.
  if (a !== a) return b !== b;
  // Exhaust primitive checks
  var type = typeof a;
  if (type !== 'function' && type !== 'object' && typeof b != 'object') return false;
  return deepEq(a, b, aStack, bStack);
}

// Internal recursive comparison function for `_.isEqual`.
function deepEq(a, b, aStack, bStack) {
  // Unwrap any wrapped objects.
  if (a instanceof _) a = a._wrapped;
  if (b instanceof _) b = b._wrapped;
  // Compare `[[Class]]` names.
  var className = _setup_toString.call(a);
  if (className !== _setup_toString.call(b)) return false;
  // Work around a bug in IE 10 - Edge 13.
  if (hasStringTagBug && className == '[object Object]' && modules_isDataView(a)) {
    if (!modules_isDataView(b)) return false;
    className = tagDataView;
  }
  switch (className) {
    // These types are compared by value.
    case '[object RegExp]':
      // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')
    case '[object String]':
      // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
      // equivalent to `new String("5")`.
      return '' + a === '' + b;
    case '[object Number]':
      // `NaN`s are equivalent, but non-reflexive.
      // Object(NaN) is equivalent to NaN.
      if (+a !== +a) return +b !== +b;
      // An `egal` comparison is performed for other numeric values.
      return +a === 0 ? 1 / +a === 1 / b : +a === +b;
    case '[object Date]':
    case '[object Boolean]':
      // Coerce dates and booleans to numeric primitive values. Dates are compared by their
      // millisecond representations. Note that invalid dates with millisecond representations
      // of `NaN` are not equivalent.
      return +a === +b;
    case '[object Symbol]':
      return SymbolProto.valueOf.call(a) === SymbolProto.valueOf.call(b);
    case '[object ArrayBuffer]':
    case tagDataView:
      // Coerce to typed array so we can fall through.
      return deepEq(toBufferView(a), toBufferView(b), aStack, bStack);
  }

  var areArrays = className === '[object Array]';
  if (!areArrays && modules_isTypedArray(a)) {
      var byteLength = _getByteLength(a);
      if (byteLength !== _getByteLength(b)) return false;
      if (a.buffer === b.buffer && a.byteOffset === b.byteOffset) return true;
      areArrays = true;
  }
  if (!areArrays) {
    if (typeof a != 'object' || typeof b != 'object') return false;

    // Objects with different constructors are not equivalent, but `Object`s or `Array`s
    // from different frames are.
    var aCtor = a.constructor, bCtor = b.constructor;
    if (aCtor !== bCtor && !(modules_isFunction(aCtor) && aCtor instanceof aCtor &&
                             modules_isFunction(bCtor) && bCtor instanceof bCtor)
                        && ('constructor' in a && 'constructor' in b)) {
      return false;
    }
  }
  // Assume equality for cyclic structures. The algorithm for detecting cyclic
  // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.

  // Initializing stack of traversed objects.
  // It's done here since we only need them for objects and arrays comparison.
  aStack = aStack || [];
  bStack = bStack || [];
  var length = aStack.length;
  while (length--) {
    // Linear search. Performance is inversely proportional to the number of
    // unique nested structures.
    if (aStack[length] === a) return bStack[length] === b;
  }

  // Add the first object to the stack of traversed objects.
  aStack.push(a);
  bStack.push(b);

  // Recursively compare objects and arrays.
  if (areArrays) {
    // Compare array lengths to determine if a deep comparison is necessary.
    length = a.length;
    if (length !== b.length) return false;
    // Deep compare the contents, ignoring non-numeric properties.
    while (length--) {
      if (!eq(a[length], b[length], aStack, bStack)) return false;
    }
  } else {
    // Deep compare objects.
    var _keys = keys(a), key;
    length = _keys.length;
    // Ensure that both objects contain the same number of properties before comparing deep equality.
    if (keys(b).length !== length) return false;
    while (length--) {
      // Deep compare each member
      key = _keys[length];
      if (!(has(b, key) && eq(a[key], b[key], aStack, bStack))) return false;
    }
  }
  // Remove the first object from the stack of traversed objects.
  aStack.pop();
  bStack.pop();
  return true;
}

// Perform a deep comparison to check if two objects are equal.
function isEqual(a, b) {
  return eq(a, b);
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/allKeys.js




// Retrieve all the enumerable property names of an object.
function allKeys(obj) {
  if (!isObject(obj)) return [];
  var keys = [];
  for (var key in obj) keys.push(key);
  // Ahem, IE < 9.
  if (hasEnumBug) collectNonEnumProps(obj, keys);
  return keys;
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/_methodFingerprint.js




// Since the regular `Object.prototype.toString` type tests don't work for
// some types in IE 11, we use a fingerprinting heuristic instead, based
// on the methods. It's not great, but it's the best we got.
// The fingerprint method lists are defined below.
function ie11fingerprint(methods) {
  var length = _getLength(methods);
  return function(obj) {
    if (obj == null) return false;
    // `Map`, `WeakMap` and `Set` have no enumerable keys.
    var keys = allKeys(obj);
    if (_getLength(keys)) return false;
    for (var i = 0; i < length; i++) {
      if (!modules_isFunction(obj[methods[i]])) return false;
    }
    // If we are testing against `WeakMap`, we need to ensure that
    // `obj` doesn't have a `forEach` method in order to distinguish
    // it from a regular `Map`.
    return methods !== weakMapMethods || !modules_isFunction(obj[forEachName]);
  };
}

// In the interest of compact minification, we write
// each string in the fingerprints only once.
var forEachName = 'forEach',
    hasName = 'has',
    commonInit = ['clear', 'delete'],
    mapTail = ['get', hasName, 'set'];

// `Map`, `WeakMap` and `Set` each have slightly different
// combinations of the above sublists.
var mapMethods = commonInit.concat(forEachName, mapTail),
    weakMapMethods = commonInit.concat(mapTail),
    setMethods = ['add'].concat(commonInit, forEachName, hasName);

;// CONCATENATED MODULE: ./node_modules/underscore/modules/isMap.js




/* harmony default export */ const isMap = (isIE11 ? ie11fingerprint(mapMethods) : tagTester('Map'));

;// CONCATENATED MODULE: ./node_modules/underscore/modules/isWeakMap.js




/* harmony default export */ const isWeakMap = (isIE11 ? ie11fingerprint(weakMapMethods) : tagTester('WeakMap'));

;// CONCATENATED MODULE: ./node_modules/underscore/modules/isSet.js




/* harmony default export */ const isSet = (isIE11 ? ie11fingerprint(setMethods) : tagTester('Set'));

;// CONCATENATED MODULE: ./node_modules/underscore/modules/isWeakSet.js


/* harmony default export */ const isWeakSet = (tagTester('WeakSet'));

;// CONCATENATED MODULE: ./node_modules/underscore/modules/values.js


// Retrieve the values of an object's properties.
function values(obj) {
  var _keys = keys(obj);
  var length = _keys.length;
  var values = Array(length);
  for (var i = 0; i < length; i++) {
    values[i] = obj[_keys[i]];
  }
  return values;
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/pairs.js


// Convert an object into a list of `[key, value]` pairs.
// The opposite of `_.object` with one argument.
function pairs(obj) {
  var _keys = keys(obj);
  var length = _keys.length;
  var pairs = Array(length);
  for (var i = 0; i < length; i++) {
    pairs[i] = [_keys[i], obj[_keys[i]]];
  }
  return pairs;
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/invert.js


// Invert the keys and values of an object. The values must be serializable.
function invert(obj) {
  var result = {};
  var _keys = keys(obj);
  for (var i = 0, length = _keys.length; i < length; i++) {
    result[obj[_keys[i]]] = _keys[i];
  }
  return result;
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/functions.js


// Return a sorted list of the function names available on the object.
function functions(obj) {
  var names = [];
  for (var key in obj) {
    if (modules_isFunction(obj[key])) names.push(key);
  }
  return names.sort();
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/_createAssigner.js
// An internal function for creating assigner functions.
function createAssigner(keysFunc, defaults) {
  return function(obj) {
    var length = arguments.length;
    if (defaults) obj = Object(obj);
    if (length < 2 || obj == null) return obj;
    for (var index = 1; index < length; index++) {
      var source = arguments[index],
          keys = keysFunc(source),
          l = keys.length;
      for (var i = 0; i < l; i++) {
        var key = keys[i];
        if (!defaults || obj[key] === void 0) obj[key] = source[key];
      }
    }
    return obj;
  };
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/extend.js



// Extend a given object with all the properties in passed-in object(s).
/* harmony default export */ const extend = (createAssigner(allKeys));

;// CONCATENATED MODULE: ./node_modules/underscore/modules/extendOwn.js



// Assigns a given object with all the own properties in the passed-in
// object(s).
// (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)
/* harmony default export */ const extendOwn = (createAssigner(keys));

;// CONCATENATED MODULE: ./node_modules/underscore/modules/defaults.js



// Fill in a given object with default properties.
/* harmony default export */ const defaults = (createAssigner(allKeys, true));

;// CONCATENATED MODULE: ./node_modules/underscore/modules/_baseCreate.js



// Create a naked function reference for surrogate-prototype-swapping.
function ctor() {
  return function(){};
}

// An internal function for creating a new object that inherits from another.
function baseCreate(prototype) {
  if (!isObject(prototype)) return {};
  if (nativeCreate) return nativeCreate(prototype);
  var Ctor = ctor();
  Ctor.prototype = prototype;
  var result = new Ctor;
  Ctor.prototype = null;
  return result;
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/create.js



// Creates an object that inherits from the given prototype object.
// If additional properties are provided then they will be added to the
// created object.
function create(prototype, props) {
  var result = baseCreate(prototype);
  if (props) extendOwn(result, props);
  return result;
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/clone.js




// Create a (shallow-cloned) duplicate of an object.
function clone(obj) {
  if (!isObject(obj)) return obj;
  return isArray(obj) ? obj.slice() : extend({}, obj);
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/tap.js
// Invokes `interceptor` with the `obj` and then returns `obj`.
// The primary purpose of this method is to "tap into" a method chain, in
// order to perform operations on intermediate results within the chain.
function tap(obj, interceptor) {
  interceptor(obj);
  return obj;
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/toPath.js



// Normalize a (deep) property `path` to array.
// Like `_.iteratee`, this function can be customized.
function toPath(path) {
  return isArray(path) ? path : [path];
}
_.toPath = toPath;

;// CONCATENATED MODULE: ./node_modules/underscore/modules/_toPath.js



// Internal wrapper for `_.toPath` to enable minification.
// Similar to `cb` for `_.iteratee`.
function _toPath_toPath(path) {
  return _.toPath(path);
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/_deepGet.js
// Internal function to obtain a nested property in `obj` along `path`.
function deepGet(obj, path) {
  var length = path.length;
  for (var i = 0; i < length; i++) {
    if (obj == null) return void 0;
    obj = obj[path[i]];
  }
  return length ? obj : void 0;
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/get.js




// Get the value of the (deep) property on `path` from `object`.
// If any property in `path` does not exist or if the value is
// `undefined`, return `defaultValue` instead.
// The `path` is normalized through `_.toPath`.
function get(object, path, defaultValue) {
  var value = deepGet(object, _toPath_toPath(path));
  return isUndefined(value) ? defaultValue : value;
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/has.js



// Shortcut function for checking if an object has a given property directly on
// itself (in other words, not on a prototype). Unlike the internal `has`
// function, this public version can also traverse nested properties.
function has_has(obj, path) {
  path = _toPath_toPath(path);
  var length = path.length;
  for (var i = 0; i < length; i++) {
    var key = path[i];
    if (!has(obj, key)) return false;
    obj = obj[key];
  }
  return !!length;
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/identity.js
// Keep the identity function around for default iteratees.
function identity(value) {
  return value;
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/matcher.js



// Returns a predicate for checking whether an object has a given set of
// `key:value` pairs.
function matcher(attrs) {
  attrs = extendOwn({}, attrs);
  return function(obj) {
    return isMatch(obj, attrs);
  };
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/property.js



// Creates a function that, when passed an object, will traverse that object’s
// properties down the given `path`, specified as an array of keys or indices.
function property(path) {
  path = _toPath_toPath(path);
  return function(obj) {
    return deepGet(obj, path);
  };
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/_optimizeCb.js
// Internal function that returns an efficient (for current engines) version
// of the passed-in callback, to be repeatedly applied in other Underscore
// functions.
function optimizeCb(func, context, argCount) {
  if (context === void 0) return func;
  switch (argCount == null ? 3 : argCount) {
    case 1: return function(value) {
      return func.call(context, value);
    };
    // The 2-argument case is omitted because we’re not using it.
    case 3: return function(value, index, collection) {
      return func.call(context, value, index, collection);
    };
    case 4: return function(accumulator, value, index, collection) {
      return func.call(context, accumulator, value, index, collection);
    };
  }
  return function() {
    return func.apply(context, arguments);
  };
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/_baseIteratee.js








// An internal function to generate callbacks that can be applied to each
// element in a collection, returning the desired result — either `_.identity`,
// an arbitrary callback, a property matcher, or a property accessor.
function baseIteratee(value, context, argCount) {
  if (value == null) return identity;
  if (modules_isFunction(value)) return optimizeCb(value, context, argCount);
  if (isObject(value) && !isArray(value)) return matcher(value);
  return property(value);
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/iteratee.js



// External wrapper for our callback generator. Users may customize
// `_.iteratee` if they want additional predicate/iteratee shorthand styles.
// This abstraction hides the internal-only `argCount` argument.
function iteratee(value, context) {
  return baseIteratee(value, context, Infinity);
}
_.iteratee = iteratee;

;// CONCATENATED MODULE: ./node_modules/underscore/modules/_cb.js




// The function we call internally to generate a callback. It invokes
// `_.iteratee` if overridden, otherwise `baseIteratee`.
function cb(value, context, argCount) {
  if (_.iteratee !== iteratee) return _.iteratee(value, context);
  return baseIteratee(value, context, argCount);
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/mapObject.js



// Returns the results of applying the `iteratee` to each element of `obj`.
// In contrast to `_.map` it returns an object.
function mapObject(obj, iteratee, context) {
  iteratee = cb(iteratee, context);
  var _keys = keys(obj),
      length = _keys.length,
      results = {};
  for (var index = 0; index < length; index++) {
    var currentKey = _keys[index];
    results[currentKey] = iteratee(obj[currentKey], currentKey, obj);
  }
  return results;
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/noop.js
// Predicate-generating function. Often useful outside of Underscore.
function noop(){}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/propertyOf.js



// Generates a function for a given object that returns a given property.
function propertyOf(obj) {
  if (obj == null) return noop;
  return function(path) {
    return get(obj, path);
  };
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/times.js


// Run a function **n** times.
function times(n, iteratee, context) {
  var accum = Array(Math.max(0, n));
  iteratee = optimizeCb(iteratee, context, 1);
  for (var i = 0; i < n; i++) accum[i] = iteratee(i);
  return accum;
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/random.js
// Return a random integer between `min` and `max` (inclusive).
function random(min, max) {
  if (max == null) {
    max = min;
    min = 0;
  }
  return min + Math.floor(Math.random() * (max - min + 1));
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/now.js
// A (possibly faster) way to get the current timestamp as an integer.
/* harmony default export */ const now = (Date.now || function() {
  return new Date().getTime();
});

;// CONCATENATED MODULE: ./node_modules/underscore/modules/_createEscaper.js


// Internal helper to generate functions for escaping and unescaping strings
// to/from HTML interpolation.
function createEscaper(map) {
  var escaper = function(match) {
    return map[match];
  };
  // Regexes for identifying a key that needs to be escaped.
  var source = '(?:' + keys(map).join('|') + ')';
  var testRegexp = RegExp(source);
  var replaceRegexp = RegExp(source, 'g');
  return function(string) {
    string = string == null ? '' : '' + string;
    return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;
  };
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/_escapeMap.js
// Internal list of HTML entities for escaping.
/* harmony default export */ const _escapeMap = ({
  '&': '&amp;',
  '<': '&lt;',
  '>': '&gt;',
  '"': '&quot;',
  "'": '&#x27;',
  '`': '&#x60;'
});

;// CONCATENATED MODULE: ./node_modules/underscore/modules/escape.js



// Function for escaping strings to HTML interpolation.
/* harmony default export */ const modules_escape = (createEscaper(_escapeMap));

;// CONCATENATED MODULE: ./node_modules/underscore/modules/_unescapeMap.js



// Internal list of HTML entities for unescaping.
/* harmony default export */ const _unescapeMap = (invert(_escapeMap));

;// CONCATENATED MODULE: ./node_modules/underscore/modules/unescape.js



// Function for unescaping strings from HTML interpolation.
/* harmony default export */ const modules_unescape = (createEscaper(_unescapeMap));

;// CONCATENATED MODULE: ./node_modules/underscore/modules/templateSettings.js


// By default, Underscore uses ERB-style template delimiters. Change the
// following template settings to use alternative delimiters.
/* harmony default export */ const templateSettings = (_.templateSettings = {
  evaluate: /<%([\s\S]+?)%>/g,
  interpolate: /<%=([\s\S]+?)%>/g,
  escape: /<%-([\s\S]+?)%>/g
});

;// CONCATENATED MODULE: ./node_modules/underscore/modules/template.js




// When customizing `_.templateSettings`, if you don't want to define an
// interpolation, evaluation or escaping regex, we need one that is
// guaranteed not to match.
var noMatch = /(.)^/;

// Certain characters need to be escaped so that they can be put into a
// string literal.
var escapes = {
  "'": "'",
  '\\': '\\',
  '\r': 'r',
  '\n': 'n',
  '\u2028': 'u2028',
  '\u2029': 'u2029'
};

var escapeRegExp = /\\|'|\r|\n|\u2028|\u2029/g;

function escapeChar(match) {
  return '\\' + escapes[match];
}

// In order to prevent third-party code injection through
// `_.templateSettings.variable`, we test it against the following regular
// expression. It is intentionally a bit more liberal than just matching valid
// identifiers, but still prevents possible loopholes through defaults or
// destructuring assignment.
var bareIdentifier = /^\s*(\w|\$)+\s*$/;

// JavaScript micro-templating, similar to John Resig's implementation.
// Underscore templating handles arbitrary delimiters, preserves whitespace,
// and correctly escapes quotes within interpolated code.
// NB: `oldSettings` only exists for backwards compatibility.
function template(text, settings, oldSettings) {
  if (!settings && oldSettings) settings = oldSettings;
  settings = defaults({}, settings, _.templateSettings);

  // Combine delimiters into one regular expression via alternation.
  var matcher = RegExp([
    (settings.escape || noMatch).source,
    (settings.interpolate || noMatch).source,
    (settings.evaluate || noMatch).source
  ].join('|') + '|$', 'g');

  // Compile the template source, escaping string literals appropriately.
  var index = 0;
  var source = "__p+='";
  text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
    source += text.slice(index, offset).replace(escapeRegExp, escapeChar);
    index = offset + match.length;

    if (escape) {
      source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
    } else if (interpolate) {
      source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
    } else if (evaluate) {
      source += "';\n" + evaluate + "\n__p+='";
    }

    // Adobe VMs need the match returned to produce the correct offset.
    return match;
  });
  source += "';\n";

  var argument = settings.variable;
  if (argument) {
    // Insure against third-party code injection. (CVE-2021-23358)
    if (!bareIdentifier.test(argument)) throw new Error(
      'variable is not a bare identifier: ' + argument
    );
  } else {
    // If a variable is not specified, place data values in local scope.
    source = 'with(obj||{}){\n' + source + '}\n';
    argument = 'obj';
  }

  source = "var __t,__p='',__j=Array.prototype.join," +
    "print=function(){__p+=__j.call(arguments,'');};\n" +
    source + 'return __p;\n';

  var render;
  try {
    render = new Function(argument, '_', source);
  } catch (e) {
    e.source = source;
    throw e;
  }

  var template = function(data) {
    return render.call(this, data, _);
  };

  // Provide the compiled source as a convenience for precompilation.
  template.source = 'function(' + argument + '){\n' + source + '}';

  return template;
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/result.js



// Traverses the children of `obj` along `path`. If a child is a function, it
// is invoked with its parent as context. Returns the value of the final
// child, or `fallback` if any child is undefined.
function result(obj, path, fallback) {
  path = _toPath_toPath(path);
  var length = path.length;
  if (!length) {
    return modules_isFunction(fallback) ? fallback.call(obj) : fallback;
  }
  for (var i = 0; i < length; i++) {
    var prop = obj == null ? void 0 : obj[path[i]];
    if (prop === void 0) {
      prop = fallback;
      i = length; // Ensure we don't continue iterating.
    }
    obj = modules_isFunction(prop) ? prop.call(obj) : prop;
  }
  return obj;
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/uniqueId.js
// Generate a unique integer id (unique within the entire client session).
// Useful for temporary DOM ids.
var idCounter = 0;
function uniqueId(prefix) {
  var id = ++idCounter + '';
  return prefix ? prefix + id : id;
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/chain.js


// Start chaining a wrapped Underscore object.
function chain(obj) {
  var instance = _(obj);
  instance._chain = true;
  return instance;
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/_executeBound.js



// Internal function to execute `sourceFunc` bound to `context` with optional
// `args`. Determines whether to execute a function as a constructor or as a
// normal function.
function executeBound(sourceFunc, boundFunc, context, callingContext, args) {
  if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args);
  var self = baseCreate(sourceFunc.prototype);
  var result = sourceFunc.apply(self, args);
  if (isObject(result)) return result;
  return self;
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/partial.js




// Partially apply a function by creating a version that has had some of its
// arguments pre-filled, without changing its dynamic `this` context. `_` acts
// as a placeholder by default, allowing any combination of arguments to be
// pre-filled. Set `_.partial.placeholder` for a custom placeholder argument.
var partial = restArguments(function(func, boundArgs) {
  var placeholder = partial.placeholder;
  var bound = function() {
    var position = 0, length = boundArgs.length;
    var args = Array(length);
    for (var i = 0; i < length; i++) {
      args[i] = boundArgs[i] === placeholder ? arguments[position++] : boundArgs[i];
    }
    while (position < arguments.length) args.push(arguments[position++]);
    return executeBound(func, bound, this, this, args);
  };
  return bound;
});

partial.placeholder = _;
/* harmony default export */ const modules_partial = (partial);

;// CONCATENATED MODULE: ./node_modules/underscore/modules/bind.js




// Create a function bound to a given object (assigning `this`, and arguments,
// optionally).
/* harmony default export */ const bind = (restArguments(function(func, context, args) {
  if (!modules_isFunction(func)) throw new TypeError('Bind must be called on a function');
  var bound = restArguments(function(callArgs) {
    return executeBound(func, bound, context, this, args.concat(callArgs));
  });
  return bound;
}));

;// CONCATENATED MODULE: ./node_modules/underscore/modules/_isArrayLike.js



// Internal helper for collection methods to determine whether a collection
// should be iterated as an array or as an object.
// Related: https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength
// Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094
/* harmony default export */ const _isArrayLike = (createSizePropertyCheck(_getLength));

;// CONCATENATED MODULE: ./node_modules/underscore/modules/_flatten.js





// Internal implementation of a recursive `flatten` function.
function flatten(input, depth, strict, output) {
  output = output || [];
  if (!depth && depth !== 0) {
    depth = Infinity;
  } else if (depth <= 0) {
    return output.concat(input);
  }
  var idx = output.length;
  for (var i = 0, length = _getLength(input); i < length; i++) {
    var value = input[i];
    if (_isArrayLike(value) && (isArray(value) || modules_isArguments(value))) {
      // Flatten current level of array or arguments object.
      if (depth > 1) {
        flatten(value, depth - 1, strict, output);
        idx = output.length;
      } else {
        var j = 0, len = value.length;
        while (j < len) output[idx++] = value[j++];
      }
    } else if (!strict) {
      output[idx++] = value;
    }
  }
  return output;
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/bindAll.js




// Bind a number of an object's methods to that object. Remaining arguments
// are the method names to be bound. Useful for ensuring that all callbacks
// defined on an object belong to it.
/* harmony default export */ const bindAll = (restArguments(function(obj, keys) {
  keys = flatten(keys, false, false);
  var index = keys.length;
  if (index < 1) throw new Error('bindAll must be passed function names');
  while (index--) {
    var key = keys[index];
    obj[key] = bind(obj[key], obj);
  }
  return obj;
}));

;// CONCATENATED MODULE: ./node_modules/underscore/modules/memoize.js


// Memoize an expensive function by storing its results.
function memoize(func, hasher) {
  var memoize = function(key) {
    var cache = memoize.cache;
    var address = '' + (hasher ? hasher.apply(this, arguments) : key);
    if (!has(cache, address)) cache[address] = func.apply(this, arguments);
    return cache[address];
  };
  memoize.cache = {};
  return memoize;
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/delay.js


// Delays a function for the given number of milliseconds, and then calls
// it with the arguments supplied.
/* harmony default export */ const delay = (restArguments(function(func, wait, args) {
  return setTimeout(function() {
    return func.apply(null, args);
  }, wait);
}));

;// CONCATENATED MODULE: ./node_modules/underscore/modules/defer.js




// Defers a function, scheduling it to run after the current call stack has
// cleared.
/* harmony default export */ const defer = (modules_partial(delay, _, 1));

;// CONCATENATED MODULE: ./node_modules/underscore/modules/throttle.js


// Returns a function, that, when invoked, will only be triggered at most once
// during a given window of time. Normally, the throttled function will run
// as much as it can, without ever going more than once per `wait` duration;
// but if you'd like to disable the execution on the leading edge, pass
// `{leading: false}`. To disable execution on the trailing edge, ditto.
function throttle(func, wait, options) {
  var timeout, context, args, result;
  var previous = 0;
  if (!options) options = {};

  var later = function() {
    previous = options.leading === false ? 0 : now();
    timeout = null;
    result = func.apply(context, args);
    if (!timeout) context = args = null;
  };

  var throttled = function() {
    var _now = now();
    if (!previous && options.leading === false) previous = _now;
    var remaining = wait - (_now - previous);
    context = this;
    args = arguments;
    if (remaining <= 0 || remaining > wait) {
      if (timeout) {
        clearTimeout(timeout);
        timeout = null;
      }
      previous = _now;
      result = func.apply(context, args);
      if (!timeout) context = args = null;
    } else if (!timeout && options.trailing !== false) {
      timeout = setTimeout(later, remaining);
    }
    return result;
  };

  throttled.cancel = function() {
    clearTimeout(timeout);
    previous = 0;
    timeout = context = args = null;
  };

  return throttled;
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/debounce.js



// When a sequence of calls of the returned function ends, the argument
// function is triggered. The end of a sequence is defined by the `wait`
// parameter. If `immediate` is passed, the argument function will be
// triggered at the beginning of the sequence instead of at the end.
function debounce(func, wait, immediate) {
  var timeout, previous, args, result, context;

  var later = function() {
    var passed = now() - previous;
    if (wait > passed) {
      timeout = setTimeout(later, wait - passed);
    } else {
      timeout = null;
      if (!immediate) result = func.apply(context, args);
      // This check is needed because `func` can recursively invoke `debounced`.
      if (!timeout) args = context = null;
    }
  };

  var debounced = restArguments(function(_args) {
    context = this;
    args = _args;
    previous = now();
    if (!timeout) {
      timeout = setTimeout(later, wait);
      if (immediate) result = func.apply(context, args);
    }
    return result;
  });

  debounced.cancel = function() {
    clearTimeout(timeout);
    timeout = args = context = null;
  };

  return debounced;
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/wrap.js


// Returns the first function passed as an argument to the second,
// allowing you to adjust arguments, run code before and after, and
// conditionally execute the original function.
function wrap(func, wrapper) {
  return modules_partial(wrapper, func);
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/negate.js
// Returns a negated version of the passed-in predicate.
function negate(predicate) {
  return function() {
    return !predicate.apply(this, arguments);
  };
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/compose.js
// Returns a function that is the composition of a list of functions, each
// consuming the return value of the function that follows.
function compose() {
  var args = arguments;
  var start = args.length - 1;
  return function() {
    var i = start;
    var result = args[start].apply(this, arguments);
    while (i--) result = args[i].call(this, result);
    return result;
  };
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/after.js
// Returns a function that will only be executed on and after the Nth call.
function after(times, func) {
  return function() {
    if (--times < 1) {
      return func.apply(this, arguments);
    }
  };
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/before.js
// Returns a function that will only be executed up to (but not including) the
// Nth call.
function before(times, func) {
  var memo;
  return function() {
    if (--times > 0) {
      memo = func.apply(this, arguments);
    }
    if (times <= 1) func = null;
    return memo;
  };
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/once.js



// Returns a function that will be executed at most one time, no matter how
// often you call it. Useful for lazy initialization.
/* harmony default export */ const once = (modules_partial(before, 2));

;// CONCATENATED MODULE: ./node_modules/underscore/modules/findKey.js



// Returns the first key on an object that passes a truth test.
function findKey(obj, predicate, context) {
  predicate = cb(predicate, context);
  var _keys = keys(obj), key;
  for (var i = 0, length = _keys.length; i < length; i++) {
    key = _keys[i];
    if (predicate(obj[key], key, obj)) return key;
  }
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/_createPredicateIndexFinder.js



// Internal function to generate `_.findIndex` and `_.findLastIndex`.
function createPredicateIndexFinder(dir) {
  return function(array, predicate, context) {
    predicate = cb(predicate, context);
    var length = _getLength(array);
    var index = dir > 0 ? 0 : length - 1;
    for (; index >= 0 && index < length; index += dir) {
      if (predicate(array[index], index, array)) return index;
    }
    return -1;
  };
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/findIndex.js


// Returns the first index on an array-like that passes a truth test.
/* harmony default export */ const findIndex = (createPredicateIndexFinder(1));

;// CONCATENATED MODULE: ./node_modules/underscore/modules/findLastIndex.js


// Returns the last index on an array-like that passes a truth test.
/* harmony default export */ const findLastIndex = (createPredicateIndexFinder(-1));

;// CONCATENATED MODULE: ./node_modules/underscore/modules/sortedIndex.js



// Use a comparator function to figure out the smallest index at which
// an object should be inserted so as to maintain order. Uses binary search.
function sortedIndex(array, obj, iteratee, context) {
  iteratee = cb(iteratee, context, 1);
  var value = iteratee(obj);
  var low = 0, high = _getLength(array);
  while (low < high) {
    var mid = Math.floor((low + high) / 2);
    if (iteratee(array[mid]) < value) low = mid + 1; else high = mid;
  }
  return low;
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/_createIndexFinder.js




// Internal function to generate the `_.indexOf` and `_.lastIndexOf` functions.
function createIndexFinder(dir, predicateFind, sortedIndex) {
  return function(array, item, idx) {
    var i = 0, length = _getLength(array);
    if (typeof idx == 'number') {
      if (dir > 0) {
        i = idx >= 0 ? idx : Math.max(idx + length, i);
      } else {
        length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1;
      }
    } else if (sortedIndex && idx && length) {
      idx = sortedIndex(array, item);
      return array[idx] === item ? idx : -1;
    }
    if (item !== item) {
      idx = predicateFind(slice.call(array, i, length), isNaN_isNaN);
      return idx >= 0 ? idx + i : -1;
    }
    for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) {
      if (array[idx] === item) return idx;
    }
    return -1;
  };
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/indexOf.js




// Return the position of the first occurrence of an item in an array,
// or -1 if the item is not included in the array.
// If the array is large and already in sort order, pass `true`
// for **isSorted** to use binary search.
/* harmony default export */ const indexOf = (createIndexFinder(1, findIndex, sortedIndex));

;// CONCATENATED MODULE: ./node_modules/underscore/modules/lastIndexOf.js



// Return the position of the last occurrence of an item in an array,
// or -1 if the item is not included in the array.
/* harmony default export */ const lastIndexOf = (createIndexFinder(-1, findLastIndex));

;// CONCATENATED MODULE: ./node_modules/underscore/modules/find.js




// Return the first value which passes a truth test.
function find(obj, predicate, context) {
  var keyFinder = _isArrayLike(obj) ? findIndex : findKey;
  var key = keyFinder(obj, predicate, context);
  if (key !== void 0 && key !== -1) return obj[key];
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/findWhere.js



// Convenience version of a common use case of `_.find`: getting the first
// object containing specific `key:value` pairs.
function findWhere(obj, attrs) {
  return find(obj, matcher(attrs));
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/each.js




// The cornerstone for collection functions, an `each`
// implementation, aka `forEach`.
// Handles raw objects in addition to array-likes. Treats all
// sparse array-likes as if they were dense.
function each(obj, iteratee, context) {
  iteratee = optimizeCb(iteratee, context);
  var i, length;
  if (_isArrayLike(obj)) {
    for (i = 0, length = obj.length; i < length; i++) {
      iteratee(obj[i], i, obj);
    }
  } else {
    var _keys = keys(obj);
    for (i = 0, length = _keys.length; i < length; i++) {
      iteratee(obj[_keys[i]], _keys[i], obj);
    }
  }
  return obj;
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/map.js




// Return the results of applying the iteratee to each element.
function map(obj, iteratee, context) {
  iteratee = cb(iteratee, context);
  var _keys = !_isArrayLike(obj) && keys(obj),
      length = (_keys || obj).length,
      results = Array(length);
  for (var index = 0; index < length; index++) {
    var currentKey = _keys ? _keys[index] : index;
    results[index] = iteratee(obj[currentKey], currentKey, obj);
  }
  return results;
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/_createReduce.js




// Internal helper to create a reducing function, iterating left or right.
function createReduce(dir) {
  // Wrap code that reassigns argument variables in a separate function than
  // the one that accesses `arguments.length` to avoid a perf hit. (#1991)
  var reducer = function(obj, iteratee, memo, initial) {
    var _keys = !_isArrayLike(obj) && keys(obj),
        length = (_keys || obj).length,
        index = dir > 0 ? 0 : length - 1;
    if (!initial) {
      memo = obj[_keys ? _keys[index] : index];
      index += dir;
    }
    for (; index >= 0 && index < length; index += dir) {
      var currentKey = _keys ? _keys[index] : index;
      memo = iteratee(memo, obj[currentKey], currentKey, obj);
    }
    return memo;
  };

  return function(obj, iteratee, memo, context) {
    var initial = arguments.length >= 3;
    return reducer(obj, optimizeCb(iteratee, context, 4), memo, initial);
  };
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/reduce.js


// **Reduce** builds up a single result from a list of values, aka `inject`,
// or `foldl`.
/* harmony default export */ const reduce = (createReduce(1));

;// CONCATENATED MODULE: ./node_modules/underscore/modules/reduceRight.js


// The right-associative version of reduce, also known as `foldr`.
/* harmony default export */ const reduceRight = (createReduce(-1));

;// CONCATENATED MODULE: ./node_modules/underscore/modules/filter.js



// Return all the elements that pass a truth test.
function filter(obj, predicate, context) {
  var results = [];
  predicate = cb(predicate, context);
  each(obj, function(value, index, list) {
    if (predicate(value, index, list)) results.push(value);
  });
  return results;
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/reject.js




// Return all the elements for which a truth test fails.
function reject(obj, predicate, context) {
  return filter(obj, negate(cb(predicate)), context);
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/every.js




// Determine whether all of the elements pass a truth test.
function every(obj, predicate, context) {
  predicate = cb(predicate, context);
  var _keys = !_isArrayLike(obj) && keys(obj),
      length = (_keys || obj).length;
  for (var index = 0; index < length; index++) {
    var currentKey = _keys ? _keys[index] : index;
    if (!predicate(obj[currentKey], currentKey, obj)) return false;
  }
  return true;
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/some.js




// Determine if at least one element in the object passes a truth test.
function some(obj, predicate, context) {
  predicate = cb(predicate, context);
  var _keys = !_isArrayLike(obj) && keys(obj),
      length = (_keys || obj).length;
  for (var index = 0; index < length; index++) {
    var currentKey = _keys ? _keys[index] : index;
    if (predicate(obj[currentKey], currentKey, obj)) return true;
  }
  return false;
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/contains.js




// Determine if the array or object contains a given item (using `===`).
function contains(obj, item, fromIndex, guard) {
  if (!_isArrayLike(obj)) obj = values(obj);
  if (typeof fromIndex != 'number' || guard) fromIndex = 0;
  return indexOf(obj, item, fromIndex) >= 0;
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/invoke.js






// Invoke a method (with arguments) on every item in a collection.
/* harmony default export */ const invoke = (restArguments(function(obj, path, args) {
  var contextPath, func;
  if (modules_isFunction(path)) {
    func = path;
  } else {
    path = _toPath_toPath(path);
    contextPath = path.slice(0, -1);
    path = path[path.length - 1];
  }
  return map(obj, function(context) {
    var method = func;
    if (!method) {
      if (contextPath && contextPath.length) {
        context = deepGet(context, contextPath);
      }
      if (context == null) return void 0;
      method = context[path];
    }
    return method == null ? method : method.apply(context, args);
  });
}));

;// CONCATENATED MODULE: ./node_modules/underscore/modules/pluck.js



// Convenience version of a common use case of `_.map`: fetching a property.
function pluck(obj, key) {
  return map(obj, property(key));
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/where.js



// Convenience version of a common use case of `_.filter`: selecting only
// objects containing specific `key:value` pairs.
function where(obj, attrs) {
  return filter(obj, matcher(attrs));
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/max.js





// Return the maximum element (or element-based computation).
function max(obj, iteratee, context) {
  var result = -Infinity, lastComputed = -Infinity,
      value, computed;
  if (iteratee == null || (typeof iteratee == 'number' && typeof obj[0] != 'object' && obj != null)) {
    obj = _isArrayLike(obj) ? obj : values(obj);
    for (var i = 0, length = obj.length; i < length; i++) {
      value = obj[i];
      if (value != null && value > result) {
        result = value;
      }
    }
  } else {
    iteratee = cb(iteratee, context);
    each(obj, function(v, index, list) {
      computed = iteratee(v, index, list);
      if (computed > lastComputed || (computed === -Infinity && result === -Infinity)) {
        result = v;
        lastComputed = computed;
      }
    });
  }
  return result;
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/min.js





// Return the minimum element (or element-based computation).
function min(obj, iteratee, context) {
  var result = Infinity, lastComputed = Infinity,
      value, computed;
  if (iteratee == null || (typeof iteratee == 'number' && typeof obj[0] != 'object' && obj != null)) {
    obj = _isArrayLike(obj) ? obj : values(obj);
    for (var i = 0, length = obj.length; i < length; i++) {
      value = obj[i];
      if (value != null && value < result) {
        result = value;
      }
    }
  } else {
    iteratee = cb(iteratee, context);
    each(obj, function(v, index, list) {
      computed = iteratee(v, index, list);
      if (computed < lastComputed || (computed === Infinity && result === Infinity)) {
        result = v;
        lastComputed = computed;
      }
    });
  }
  return result;
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/toArray.js








// Safely create a real, live array from anything iterable.
var reStrSymbol = /[^\ud800-\udfff]|[\ud800-\udbff][\udc00-\udfff]|[\ud800-\udfff]/g;
function toArray(obj) {
  if (!obj) return [];
  if (isArray(obj)) return slice.call(obj);
  if (isString(obj)) {
    // Keep surrogate pair characters together.
    return obj.match(reStrSymbol);
  }
  if (_isArrayLike(obj)) return map(obj, identity);
  return values(obj);
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/sample.js






// Sample **n** random values from a collection using the modern version of the
// [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher–Yates_shuffle).
// If **n** is not specified, returns a single random element.
// The internal `guard` argument allows it to work with `_.map`.
function sample(obj, n, guard) {
  if (n == null || guard) {
    if (!_isArrayLike(obj)) obj = values(obj);
    return obj[random(obj.length - 1)];
  }
  var sample = toArray(obj);
  var length = _getLength(sample);
  n = Math.max(Math.min(n, length), 0);
  var last = length - 1;
  for (var index = 0; index < n; index++) {
    var rand = random(index, last);
    var temp = sample[index];
    sample[index] = sample[rand];
    sample[rand] = temp;
  }
  return sample.slice(0, n);
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/shuffle.js


// Shuffle a collection.
function shuffle(obj) {
  return sample(obj, Infinity);
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/sortBy.js




// Sort the object's values by a criterion produced by an iteratee.
function sortBy(obj, iteratee, context) {
  var index = 0;
  iteratee = cb(iteratee, context);
  return pluck(map(obj, function(value, key, list) {
    return {
      value: value,
      index: index++,
      criteria: iteratee(value, key, list)
    };
  }).sort(function(left, right) {
    var a = left.criteria;
    var b = right.criteria;
    if (a !== b) {
      if (a > b || a === void 0) return 1;
      if (a < b || b === void 0) return -1;
    }
    return left.index - right.index;
  }), 'value');
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/_group.js



// An internal function used for aggregate "group by" operations.
function group(behavior, partition) {
  return function(obj, iteratee, context) {
    var result = partition ? [[], []] : {};
    iteratee = cb(iteratee, context);
    each(obj, function(value, index) {
      var key = iteratee(value, index, obj);
      behavior(result, value, key);
    });
    return result;
  };
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/groupBy.js



// Groups the object's values by a criterion. Pass either a string attribute
// to group by, or a function that returns the criterion.
/* harmony default export */ const groupBy = (group(function(result, value, key) {
  if (has(result, key)) result[key].push(value); else result[key] = [value];
}));

;// CONCATENATED MODULE: ./node_modules/underscore/modules/indexBy.js


// Indexes the object's values by a criterion, similar to `_.groupBy`, but for
// when you know that your index values will be unique.
/* harmony default export */ const indexBy = (group(function(result, value, key) {
  result[key] = value;
}));

;// CONCATENATED MODULE: ./node_modules/underscore/modules/countBy.js



// Counts instances of an object that group by a certain criterion. Pass
// either a string attribute to count by, or a function that returns the
// criterion.
/* harmony default export */ const countBy = (group(function(result, value, key) {
  if (has(result, key)) result[key]++; else result[key] = 1;
}));

;// CONCATENATED MODULE: ./node_modules/underscore/modules/partition.js


// Split a collection into two arrays: one whose elements all pass the given
// truth test, and one whose elements all do not pass the truth test.
/* harmony default export */ const partition = (group(function(result, value, pass) {
  result[pass ? 0 : 1].push(value);
}, true));

;// CONCATENATED MODULE: ./node_modules/underscore/modules/size.js



// Return the number of elements in a collection.
function size(obj) {
  if (obj == null) return 0;
  return _isArrayLike(obj) ? obj.length : keys(obj).length;
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/_keyInObj.js
// Internal `_.pick` helper function to determine whether `key` is an enumerable
// property name of `obj`.
function keyInObj(value, key, obj) {
  return key in obj;
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/pick.js







// Return a copy of the object only containing the allowed properties.
/* harmony default export */ const pick = (restArguments(function(obj, keys) {
  var result = {}, iteratee = keys[0];
  if (obj == null) return result;
  if (modules_isFunction(iteratee)) {
    if (keys.length > 1) iteratee = optimizeCb(iteratee, keys[1]);
    keys = allKeys(obj);
  } else {
    iteratee = keyInObj;
    keys = flatten(keys, false, false);
    obj = Object(obj);
  }
  for (var i = 0, length = keys.length; i < length; i++) {
    var key = keys[i];
    var value = obj[key];
    if (iteratee(value, key, obj)) result[key] = value;
  }
  return result;
}));

;// CONCATENATED MODULE: ./node_modules/underscore/modules/omit.js








// Return a copy of the object without the disallowed properties.
/* harmony default export */ const omit = (restArguments(function(obj, keys) {
  var iteratee = keys[0], context;
  if (modules_isFunction(iteratee)) {
    iteratee = negate(iteratee);
    if (keys.length > 1) context = keys[1];
  } else {
    keys = map(flatten(keys, false, false), String);
    iteratee = function(value, key) {
      return !contains(keys, key);
    };
  }
  return pick(obj, iteratee, context);
}));

;// CONCATENATED MODULE: ./node_modules/underscore/modules/initial.js


// Returns everything but the last entry of the array. Especially useful on
// the arguments object. Passing **n** will return all the values in
// the array, excluding the last N.
function initial(array, n, guard) {
  return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n)));
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/first.js


// Get the first element of an array. Passing **n** will return the first N
// values in the array. The **guard** check allows it to work with `_.map`.
function first(array, n, guard) {
  if (array == null || array.length < 1) return n == null || guard ? void 0 : [];
  if (n == null || guard) return array[0];
  return initial(array, array.length - n);
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/rest.js


// Returns everything but the first entry of the `array`. Especially useful on
// the `arguments` object. Passing an **n** will return the rest N values in the
// `array`.
function rest(array, n, guard) {
  return slice.call(array, n == null || guard ? 1 : n);
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/last.js


// Get the last element of an array. Passing **n** will return the last N
// values in the array.
function last(array, n, guard) {
  if (array == null || array.length < 1) return n == null || guard ? void 0 : [];
  if (n == null || guard) return array[array.length - 1];
  return rest(array, Math.max(0, array.length - n));
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/compact.js


// Trim out all falsy values from an array.
function compact(array) {
  return filter(array, Boolean);
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/flatten.js


// Flatten out an array, either recursively (by default), or up to `depth`.
// Passing `true` or `false` as `depth` means `1` or `Infinity`, respectively.
function flatten_flatten(array, depth) {
  return flatten(array, depth, false);
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/difference.js





// Take the difference between one array and a number of other arrays.
// Only the elements present in just the first array will remain.
/* harmony default export */ const difference = (restArguments(function(array, rest) {
  rest = flatten(rest, true, true);
  return filter(array, function(value){
    return !contains(rest, value);
  });
}));

;// CONCATENATED MODULE: ./node_modules/underscore/modules/without.js



// Return a version of the array that does not contain the specified value(s).
/* harmony default export */ const without = (restArguments(function(array, otherArrays) {
  return difference(array, otherArrays);
}));

;// CONCATENATED MODULE: ./node_modules/underscore/modules/uniq.js





// Produce a duplicate-free version of the array. If the array has already
// been sorted, you have the option of using a faster algorithm.
// The faster algorithm will not work with an iteratee if the iteratee
// is not a one-to-one function, so providing an iteratee will disable
// the faster algorithm.
function uniq(array, isSorted, iteratee, context) {
  if (!isBoolean(isSorted)) {
    context = iteratee;
    iteratee = isSorted;
    isSorted = false;
  }
  if (iteratee != null) iteratee = cb(iteratee, context);
  var result = [];
  var seen = [];
  for (var i = 0, length = _getLength(array); i < length; i++) {
    var value = array[i],
        computed = iteratee ? iteratee(value, i, array) : value;
    if (isSorted && !iteratee) {
      if (!i || seen !== computed) result.push(value);
      seen = computed;
    } else if (iteratee) {
      if (!contains(seen, computed)) {
        seen.push(computed);
        result.push(value);
      }
    } else if (!contains(result, value)) {
      result.push(value);
    }
  }
  return result;
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/union.js




// Produce an array that contains the union: each distinct element from all of
// the passed-in arrays.
/* harmony default export */ const union = (restArguments(function(arrays) {
  return uniq(flatten(arrays, true, true));
}));

;// CONCATENATED MODULE: ./node_modules/underscore/modules/intersection.js



// Produce an array that contains every item shared between all the
// passed-in arrays.
function intersection(array) {
  var result = [];
  var argsLength = arguments.length;
  for (var i = 0, length = _getLength(array); i < length; i++) {
    var item = array[i];
    if (contains(result, item)) continue;
    var j;
    for (j = 1; j < argsLength; j++) {
      if (!contains(arguments[j], item)) break;
    }
    if (j === argsLength) result.push(item);
  }
  return result;
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/unzip.js




// Complement of zip. Unzip accepts an array of arrays and groups
// each array's elements on shared indices.
function unzip(array) {
  var length = (array && max(array, _getLength).length) || 0;
  var result = Array(length);

  for (var index = 0; index < length; index++) {
    result[index] = pluck(array, index);
  }
  return result;
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/zip.js



// Zip together multiple lists into a single array -- elements that share
// an index go together.
/* harmony default export */ const zip = (restArguments(unzip));

;// CONCATENATED MODULE: ./node_modules/underscore/modules/object.js


// Converts lists into objects. Pass either a single array of `[key, value]`
// pairs, or two parallel arrays of the same length -- one of keys, and one of
// the corresponding values. Passing by pairs is the reverse of `_.pairs`.
function object(list, values) {
  var result = {};
  for (var i = 0, length = _getLength(list); i < length; i++) {
    if (values) {
      result[list[i]] = values[i];
    } else {
      result[list[i][0]] = list[i][1];
    }
  }
  return result;
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/range.js
// Generate an integer Array containing an arithmetic progression. A port of
// the native Python `range()` function. See
// [the Python documentation](https://docs.python.org/library/functions.html#range).
function range(start, stop, step) {
  if (stop == null) {
    stop = start || 0;
    start = 0;
  }
  if (!step) {
    step = stop < start ? -1 : 1;
  }

  var length = Math.max(Math.ceil((stop - start) / step), 0);
  var range = Array(length);

  for (var idx = 0; idx < length; idx++, start += step) {
    range[idx] = start;
  }

  return range;
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/chunk.js


// Chunk a single array into multiple arrays, each containing `count` or fewer
// items.
function chunk(array, count) {
  if (count == null || count < 1) return [];
  var result = [];
  var i = 0, length = array.length;
  while (i < length) {
    result.push(slice.call(array, i, i += count));
  }
  return result;
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/_chainResult.js


// Helper function to continue chaining intermediate results.
function chainResult(instance, obj) {
  return instance._chain ? _(obj).chain() : obj;
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/mixin.js






// Add your own custom functions to the Underscore object.
function mixin(obj) {
  each(functions(obj), function(name) {
    var func = _[name] = obj[name];
    _.prototype[name] = function() {
      var args = [this._wrapped];
      push.apply(args, arguments);
      return chainResult(this, func.apply(_, args));
    };
  });
  return _;
}

;// CONCATENATED MODULE: ./node_modules/underscore/modules/underscore-array-methods.js





// Add all mutator `Array` functions to the wrapper.
each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
  var method = ArrayProto[name];
  _.prototype[name] = function() {
    var obj = this._wrapped;
    if (obj != null) {
      method.apply(obj, arguments);
      if ((name === 'shift' || name === 'splice') && obj.length === 0) {
        delete obj[0];
      }
    }
    return chainResult(this, obj);
  };
});

// Add all accessor `Array` functions to the wrapper.
each(['concat', 'join', 'slice'], function(name) {
  var method = ArrayProto[name];
  _.prototype[name] = function() {
    var obj = this._wrapped;
    if (obj != null) obj = method.apply(obj, arguments);
    return chainResult(this, obj);
  };
});

/* harmony default export */ const underscore_array_methods = (_);

;// CONCATENATED MODULE: ./node_modules/underscore/modules/index.js
// Named Exports
// =============

//     Underscore.js 1.13.6
//     https://underscorejs.org
//     (c) 2009-2022 Jeremy Ashkenas, Julian Gonggrijp, and DocumentCloud and Investigative Reporters & Editors
//     Underscore may be freely distributed under the MIT license.

// Baseline setup.



// Object Functions
// ----------------
// Our most fundamental functions operate on any JavaScript object.
// Most functions in Underscore depend on at least one function in this section.

// A group of functions that check the types of core JavaScript values.
// These are often informally referred to as the "isType" functions.



























// Functions that treat an object as a dictionary of key-value pairs.
















// Utility Functions
// -----------------
// A bit of a grab bag: Predicate-generating functions for use with filters and
// loops, string escaping and templating, create random numbers and unique ids,
// and functions that facilitate Underscore's chaining and iteration conventions.



















// Function (ahem) Functions
// -------------------------
// These functions take a function as an argument and return a new function
// as the result. Also known as higher-order functions.















// Finders
// -------
// Functions that extract (the position of) a single element from an object
// or array based on some criterion.









// Collection Functions
// --------------------
// Functions that work on any collection of elements: either an array, or
// an object of key-value pairs.
























// `_.pick` and `_.omit` are actually object functions, but we put
// them here in order to create a more natural reading order in the
// monolithic build as they depend on `_.contains`.



// Array Functions
// ---------------
// Functions that operate on arrays (and array-likes) only, because they’re
// expressed in terms of operations on an ordered list of values.

















// OOP
// ---
// These modules support the "object-oriented" calling style. See also
// `underscore.js` and `index-default.js`.



;// CONCATENATED MODULE: ./node_modules/underscore/modules/index-default.js
// Default Export
// ==============
// In this module, we mix our bundled exports into the `_` object and export
// the result. This is analogous to setting `module.exports = _` in CommonJS.
// Hence, this module is also the entry point of our UMD bundle and the package
// entry point for CommonJS and AMD users. In other words, this is (the source
// of) the module you are interfacing with when you do any of the following:
//
// ```js
// // CommonJS
// var _ = require('underscore');
//
// // AMD
// define(['underscore'], function(_) {...});
//
// // UMD in the browser
// // _ is available as a global variable
// ```



// Add all of the Underscore functions to the wrapper object.
var index_default_ = mixin(modules_namespaceObject);
// Legacy Node.js API.
index_default_._ = index_default_;
// Export the Underscore API.
/* harmony default export */ const index_default = (index_default_);

;// CONCATENATED MODULE: ./node_modules/underscore/modules/index-all.js
// ESM Exports
// ===========
// This module is the package entry point for ES module users. In other words,
// it is the module they are interfacing with when they import from the whole
// package instead of from a submodule, like this:
//
// ```js
// import { map } from 'underscore';
// ```
//
// The difference with `./index-default`, which is the package entry point for
// CommonJS, AMD and UMD users, is purely technical. In ES modules, named and
// default exports are considered to be siblings, so when you have a default
// export, its properties are not automatically available as named exports. For
// this reason, we re-export the named exports in addition to providing the same
// default export as in `./index-default`.




/***/ })

/******/ });
/************************************************************************/
/******/ // The module cache
/******/ var __webpack_module_cache__ = {};
/******/ 
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ 	// Check if module is in cache
/******/ 	var cachedModule = __webpack_module_cache__[moduleId];
/******/ 	if (cachedModule !== undefined) {
/******/ 		return cachedModule.exports;
/******/ 	}
/******/ 	// Create a new module (and put it into the cache)
/******/ 	var module = __webpack_module_cache__[moduleId] = {
/******/ 		// no module.id needed
/******/ 		// no module.loaded needed
/******/ 		exports: {}
/******/ 	};
/******/ 
/******/ 	// Execute the module function
/******/ 	__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ 
/******/ 	// Return the exports of the module
/******/ 	return module.exports;
/******/ }
/******/ 
/************************************************************************/
/******/ /* webpack/runtime/compat get default export */
/******/ (() => {
/******/ 	// getDefaultExport function for compatibility with non-harmony modules
/******/ 	__webpack_require__.n = (module) => {
/******/ 		var getter = module && module.__esModule ?
/******/ 			() => (module['default']) :
/******/ 			() => (module);
/******/ 		__webpack_require__.d(getter, { a: getter });
/******/ 		return getter;
/******/ 	};
/******/ })();
/******/ 
/******/ /* webpack/runtime/define property getters */
/******/ (() => {
/******/ 	// define getter functions for harmony exports
/******/ 	__webpack_require__.d = (exports, definition) => {
/******/ 		for(var key in definition) {
/******/ 			if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
/******/ 				Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ 			}
/******/ 		}
/******/ 	};
/******/ })();
/******/ 
/******/ /* webpack/runtime/global */
/******/ (() => {
/******/ 	__webpack_require__.g = (function() {
/******/ 		if (typeof globalThis === 'object') return globalThis;
/******/ 		try {
/******/ 			return this || new Function('return this')();
/******/ 		} catch (e) {
/******/ 			if (typeof window === 'object') return window;
/******/ 		}
/******/ 	})();
/******/ })();
/******/ 
/******/ /* webpack/runtime/hasOwnProperty shorthand */
/******/ (() => {
/******/ 	__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
/******/ })();
/******/ 
/******/ /* webpack/runtime/make namespace object */
/******/ (() => {
/******/ 	// define __esModule on exports
/******/ 	__webpack_require__.r = (exports) => {
/******/ 		if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ 			Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ 		}
/******/ 		Object.defineProperty(exports, '__esModule', { value: true });
/******/ 	};
/******/ })();
/******/ 
/************************************************************************/
var __webpack_exports__ = {};
// This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk.
(() => {

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  ZP: () => (/* binding */ src_0),
  kr: () => (/* binding */ grapesjs),
  j7: () => (/* binding */ usePlugin)
});

// EXTERNAL MODULE: ./node_modules/underscore/modules/index-all.js + 160 modules
var index_all = __webpack_require__(50);
// EXTERNAL MODULE: ./src/utils/mixins.ts
var mixins = __webpack_require__(163);
;// CONCATENATED MODULE: ./src/utils/html.ts

/**
 * Safe ES6 tagged template strings
 * @param {Array<String>} literals
 * @param  {Array<String>} substs
 * @returns {String}
 * @example
 * const str = '<b>Hello</b>';
 * const strHtml = html`Escaped ${str}, unescaped $${str}`;
 */
function html(literals) {
    var substs = [];
    for (var _i = 1; _i < arguments.length; _i++) {
        substs[_i - 1] = arguments[_i];
    }
    var raw = literals.raw;
    return raw.reduce(function (acc, lit, i) {
        var subst = substs[i - 1];
        var last = raw[i - 1];
        if (Array.isArray(subst)) {
            subst = subst.join('');
        }
        else if (last && last.slice(-1) === '$') {
            // If the interpolation is preceded by a dollar sign, it won't be escaped
            acc = acc.slice(0, -1);
        }
        else {
            subst = (0,mixins.escape)(subst);
        }
        return acc + subst + lit;
    });
}

;// CONCATENATED MODULE: ./src/editor/config/config.ts
var config = {
    stylePrefix: 'gjs-',
    components: '',
    style: '',
    fromElement: false,
    projectData: undefined,
    noticeOnUnload: true,
    showOffsets: false,
    showOffsetsSelected: false,
    forceClass: true,
    height: '900px',
    width: '100%',
    log: ['warning', 'error'],
    baseCss: '',
    protectedCss: '* { box-sizing: border-box; } body {margin: 0;}',
    canvasCss: '',
    defaultCommand: 'select-comp',
    showToolbar: true,
    showDevices: true,
    devicePreviewMode: false,
    mediaCondition: 'max-width',
    tagVarStart: '{[ ',
    tagVarEnd: ' ]}',
    keepEmptyTextNodes: false,
    jsInHtml: true,
    nativeDnD: true,
    multipleSelection: true,
    optsHtml: {},
    optsCss: {},
    avoidInlineStyle: true,
    avoidDefaults: true,
    clearStyles: false,
    listenToEl: [],
    cssIcons: 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css',
    icons: {
        close: '<svg viewBox="0 0 24 24"><path fill="currentColor" d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12 19 6.41z"></path></svg>',
        move: '<svg viewBox="0 0 24 24"><path fill="currentColor" d="M13,6V11H18V7.75L22.25,12L18,16.25V13H13V18H16.25L12,22.25L7.75,18H11V13H6V16.25L1.75,12L6,7.75V11H11V6H7.75L12,1.75L16.25,6H13Z"/></svg>',
        plus: '<svg viewBox="0 0 24 24"><path fill="currentColor" d="M19,13H13V19H11V13H5V11H11V5H13V11H19V13Z" /></svg>',
        caret: '<svg viewBox="0 0 24 24"><path fill="currentColor" d="M7,10L12,15L17,10H7Z" /></svg>',
        delete: '<svg viewBox="0 0 24 24"><path fill="currentColor" d="M19,4H15.5L14.5,3H9.5L8.5,4H5V6H19M6,19A2,2 0 0,0 8,21H16A2,2 0 0,0 18,19V7H6V19Z" /></svg>',
        copy: '<svg viewBox="0 0 24 24"><path fill="currentColor" d="M19,21H8V7H19M19,5H8A2,2 0 0,0 6,7V21A2,2 0 0,0 8,23H19A2,2 0 0,0 21,21V7A2,2 0 0,0 19,5M16,1H4A2,2 0 0,0 2,3V17H4V3H16V1Z" /></svg>',
        arrowUp: '<svg viewBox="0 0 24 24"><path fill="currentColor" d="M13,20H11V8L5.5,13.5L4.08,12.08L12,4.16L19.92,12.08L18.5,13.5L13,8V20Z" /></svg>',
        chevron: '<svg viewBox="0 0 24 24"><path fill="currentColor" d="M7.41,15.41L12,10.83L16.59,15.41L18,14L12,8L6,14L7.41,15.41Z" /></svg>',
        eye: '<svg viewBox="0 0 24 24"><path fill="currentColor" d="M12,9A3,3 0 0,0 9,12A3,3 0 0,0 12,15A3,3 0 0,0 15,12A3,3 0 0,0 12,9M12,17A5,5 0 0,1 7,12A5,5 0 0,1 12,7A5,5 0 0,1 17,12A5,5 0 0,1 12,17M12,4.5C7,4.5 2.73,7.61 1,12C2.73,16.39 7,19.5 12,19.5C17,19.5 21.27,16.39 23,12C21.27,7.61 17,4.5 12,4.5Z" /></svg>',
        eyeOff: '<svg viewBox="0 0 24 24"><path fill="currentColor" d="M11.83,9L15,12.16C15,12.11 15,12.05 15,12A3,3 0 0,0 12,9C11.94,9 11.89,9 11.83,9M7.53,9.8L9.08,11.35C9.03,11.56 9,11.77 9,12A3,3 0 0,0 12,15C12.22,15 12.44,14.97 12.65,14.92L14.2,16.47C13.53,16.8 12.79,17 12,17A5,5 0 0,1 7,12C7,11.21 7.2,10.47 7.53,9.8M2,4.27L4.28,6.55L4.73,7C3.08,8.3 1.78,10 1,12C2.73,16.39 7,19.5 12,19.5C13.55,19.5 15.03,19.2 16.38,18.66L16.81,19.08L19.73,22L21,20.73L3.27,3M12,7A5,5 0 0,1 17,12C17,12.64 16.87,13.26 16.64,13.82L19.57,16.75C21.07,15.5 22.27,13.86 23,12C21.27,7.61 17,4.5 12,4.5C10.6,4.5 9.26,4.75 8,5.2L10.17,7.35C10.74,7.13 11.35,7 12,7Z" /></svg>',
    },
    i18n: {},
    undoManager: {},
    assetManager: {},
    canvas: {},
    layerManager: {},
    storageManager: {},
    richTextEditor: {},
    domComponents: {},
    modal: {},
    codeManager: {},
    panels: {},
    commands: {},
    cssComposer: {},
    selectorManager: {},
    deviceManager: {},
    styleManager: {},
    blockManager: {},
    traitManager: {},
    textViewCode: 'Code',
    keepUnusedStyles: false,
    customUI: false,
};
/* harmony default export */ const config_config = (config);

// EXTERNAL MODULE: ./node_modules/backbone/backbone.js
var backbone = __webpack_require__(316);
var backbone_default = /*#__PURE__*/__webpack_require__.n(backbone);
// EXTERNAL MODULE: ./src/utils/cash-dom.ts
var cash_dom = __webpack_require__(895);
;// CONCATENATED MODULE: ./src/utils/extender.ts

/* harmony default export */ const extender = (function (_a) {
    var $ = _a.$;
    if ($ && $.prototype && $.prototype.constructor.name !== 'jQuery') {
        var fn = $.fn;
        // Additional helpers
        fn.hide = function () {
            return this.css('display', 'none');
        };
        fn.show = function () {
            return this.css('display', 'block');
        };
        fn.focus = function () {
            var el = this.get(0);
            el && el.focus();
            return this;
        };
        // For spectrum compatibility
        fn.bind = function (ev, h) {
            return this.on(ev, h);
        };
        fn.unbind = function (ev, h) {
            if ((0,index_all.isObject)(ev)) {
                for (var name_1 in ev) {
                    ev.hasOwnProperty(name_1) && this.off(name_1, ev[name_1]);
                }
                return this;
            }
            else {
                return this.off(ev, h);
            }
        };
        fn.click = function (h) {
            return h ? this.on('click', h) : this.trigger('click');
        };
        fn.change = function (h) {
            return h ? this.on('change', h) : this.trigger('change');
        };
        fn.keydown = function (h) {
            return h ? this.on('keydown', h) : this.trigger('keydown');
        };
        fn.delegate = function (selector, events, data, handler) {
            if (!handler) {
                handler = data;
            }
            return this.on(events, selector, function (e) {
                e.data = data;
                handler(e);
            });
        };
        fn.scrollLeft = function () {
            var el = this.get(0);
            el = el.nodeType == 9 ? el.defaultView : el;
            var win = el instanceof Window ? el : null;
            return win ? win.pageXOffset : el.scrollLeft || 0;
        };
        fn.scrollTop = function () {
            var el = this.get(0);
            el = el.nodeType == 9 ? el.defaultView : el;
            var win = el instanceof Window ? el : null;
            return win ? win.pageYOffset : el.scrollTop || 0;
        };
        var offset_1 = $.prototype.offset;
        fn.offset = function (coords) {
            var top, left;
            if (coords) {
                top = coords.top;
                left = coords.left;
            }
            if (typeof top != 'undefined') {
                this.css('top', "".concat(top, "px"));
            }
            if (typeof left != 'undefined') {
                this.css('left', "".concat(left, "px"));
            }
            return offset_1.call(this);
        };
        $.map = function (items, clb) {
            var ar = [];
            for (var i = 0; i < items.length; i++) {
                ar.push(clb(items[i], i));
            }
            return ar;
        };
        var indexOf_1 = Array.prototype.indexOf;
        $.inArray = function (val, arr, i) {
            return arr == null ? -1 : indexOf_1.call(arr, val, i);
        };
        $.Event = function (src, props) {
            if (!(this instanceof $.Event)) {
                return new $.Event(src, props);
            }
            this.type = src;
            this.isDefaultPrevented = function () { return false; };
        };
    }
});

// EXTERNAL MODULE: ./src/common/index.ts
var common = __webpack_require__(346);
;// CONCATENATED MODULE: ./src/editor/model/Selected.ts
var __extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();


var Selectable = /** @class */ (function (_super) {
    __extends(Selectable, _super);
    function Selectable() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    return Selectable;
}(common/* Model */.Hn));

var Selected = /** @class */ (function (_super) {
    __extends(Selected, _super);
    function Selected() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Selected.prototype.getByComponent = function (component) {
        var _this = this;
        return this.filter(function (s) { return _this.getComponent(s) === component; })[0];
    };
    Selected.prototype.addComponent = function (component, opts) {
        var _this = this;
        var toAdd = ((0,index_all.isArray)(component) ? component : [component])
            .filter(function (c) { return !_this.hasComponent(c); })
            .map(function (component) { return new Selectable({ component: component }); })[0];
        return this.push(toAdd, opts);
    };
    Selected.prototype.getComponent = function (model) {
        return model.get('component');
    };
    Selected.prototype.hasComponent = function (component) {
        var model = this.getByComponent(component);
        return model && this.contains(model);
    };
    Selected.prototype.lastComponent = function () {
        var last = this.last();
        return last ? this.getComponent(last) : undefined;
    };
    Selected.prototype.allComponents = function () {
        var _this = this;
        return this.map(function (s) { return _this.getComponent(s); }).filter(function (i) { return i; });
    };
    Selected.prototype.removeComponent = function (component, opts) {
        var _this = this;
        var toRemove = ((0,index_all.isArray)(component) ? component : [component]).map(function (c) { return _this.getByComponent(c); });
        return this.remove(toRemove, opts);
    };
    return Selected;
}(common/* Collection */.FE));
/* harmony default export */ const model_Selected = (Selected);

;// CONCATENATED MODULE: ./src/abstract/Module.ts
var Module_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __assign = (undefined && undefined.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __spreadArray = (undefined && undefined.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};


var Module = /** @class */ (function () {
    function Module(em, moduleName, defaults) {
        this.debounced = [];
        this.collections = [];
        this.cls = [];
        this._em = em;
        this._name = moduleName;
        var name = (this.name.charAt(0).toLowerCase() + this.name.slice(1));
        var cfgParent = !(0,index_all.isUndefined)(em.config[name]) ? em.config[name] : em.config[this.name];
        var cfg = (cfgParent === true ? {} : cfgParent || {});
        cfg.pStylePrefix = em.config.pStylePrefix || '';
        if (!(0,index_all.isUndefined)(cfgParent) && !cfgParent) {
            cfg._disable = 1;
        }
        cfg.em = em;
        this._config = (0,mixins.deepMerge)(defaults || {}, cfg);
    }
    Object.defineProperty(Module.prototype, "em", {
        get: function () {
            return this._em;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Module.prototype, "config", {
        get: function () {
            return this._config;
        },
        enumerable: false,
        configurable: true
    });
    Module.prototype.render = function (opts) { };
    Module.prototype.postLoad = function (key) { };
    Object.defineProperty(Module.prototype, "name", {
        get: function () {
            return this._name;
        },
        enumerable: false,
        configurable: true
    });
    Module.prototype.getConfig = function (name) {
        // @ts-ignore
        return name ? this.config[name] : this.config;
    };
    Module.prototype.__logWarn = function (str, opts) {
        if (opts === void 0) { opts = {}; }
        this.em.logWarning("[".concat(this.name, "]: ").concat(str), opts);
    };
    Module.prototype.destroy = function () {
        this.__destroy();
    };
    Module.prototype.__destroy = function () {
        var _a, _b, _c;
        (_a = this.view) === null || _a === void 0 ? void 0 : _a.remove();
        (_b = this.state) === null || _b === void 0 ? void 0 : _b.stopListening();
        (_c = this.state) === null || _c === void 0 ? void 0 : _c.clear();
        this.debounced.forEach(function (d) { return d.cancel(); });
        this.collections.forEach(function (c) {
            c.stopListening();
            c.reset();
        });
    };
    /**
     * Move the main DOM element of the module.
     * To execute only post editor render (in postRender)
     */
    Module.prototype.__appendTo = function () {
        var elTo = this.getConfig().appendTo;
        if (elTo) {
            var el = (0,index_all.isElement)(elTo) ? elTo : document.querySelector(elTo);
            if (!el)
                return this.__logWarn('"appendTo" element not found');
            el.appendChild(this.render());
        }
    };
    return Module;
}());
/* harmony default export */ const abstract_Module = (Module);
var ItemManagerModule = /** @class */ (function (_super) {
    Module_extends(ItemManagerModule, _super);
    function ItemManagerModule(em, moduleName, all, events, defaults, opts) {
        if (opts === void 0) { opts = {}; }
        var _this = _super.call(this, em, moduleName, defaults) || this;
        _this.cls = [];
        _this.private = false;
        _this.all = all;
        _this.events = events;
        !opts.skipListen && _this.__initListen();
        return _this;
    }
    ItemManagerModule.prototype.postLoad = function (key) { };
    ItemManagerModule.prototype.render = function (opts) { };
    ItemManagerModule.prototype.getProjectData = function (data) {
        var obj = {};
        var key = this.storageKey;
        if (key) {
            obj[key] = data || this.getAll();
        }
        return obj;
    };
    ItemManagerModule.prototype.loadProjectData = function (data, param) {
        if (data === void 0) { data = {}; }
        if (param === void 0) { param = {}; }
        var all = param.all, onResult = param.onResult, reset = param.reset;
        var key = this.storageKey;
        var opts = { action: 'load' };
        var coll = all || this.all;
        var result = data[key];
        if (typeof result == 'string') {
            try {
                result = JSON.parse(result);
            }
            catch (err) {
                this.__logWarn('Data parsing failed', { input: result });
            }
        }
        reset && result && coll.reset(undefined, opts);
        if (onResult) {
            result && onResult(result, opts);
        }
        else if (result && (0,mixins.isDef)(result.length)) {
            coll.reset(result, opts);
        }
        return result;
    };
    ItemManagerModule.prototype.clear = function (opts) {
        if (opts === void 0) { opts = {}; }
        var all = this.all;
        all && all.reset(undefined, opts);
        return this;
    };
    // getAll(): TCollection extends Collection<infer C> ? C[] : TCollection {
    ItemManagerModule.prototype.getAll = function () {
        return __spreadArray([], this.all.models, true);
    };
    ItemManagerModule.prototype.getAllMap = function () {
        return this.getAll().reduce(function (acc, i) {
            acc[i.get(i.idAttribute)] = i;
            return acc;
        }, {});
    };
    ItemManagerModule.prototype.__initListen = function (opts) {
        if (opts === void 0) { opts = {}; }
        var _a = this, all = _a.all, em = _a.em, events = _a.events;
        all &&
            em &&
            all
                .on('add', function (m, c, o) { return em.trigger(events.add, m, o); })
                .on('remove', function (m, c, o) { return em.trigger(events.remove, m, o); })
                .on('change', function (p, c) { return em.trigger(events.update, p, p.changedAttributes(), c); })
                .on('all', this.__catchAllEvent, this);
        // Register collections
        this.cls = [all].concat(opts.collections || []);
        // Propagate events
        (opts.propagate || []).forEach(function (_a) {
            var entity = _a.entity, event = _a.event;
            entity.on('all', function (ev, model, coll, opts) {
                var options = opts || coll;
                var opt = __assign({ event: ev }, options);
                [em, all].map(function (md) { return md.trigger(event, model, opt); });
            });
        });
    };
    ItemManagerModule.prototype.__remove = function (model, opts) {
        var _this = this;
        if (opts === void 0) { opts = {}; }
        var em = this.em;
        //@ts-ignore
        var md = (0,index_all.isString)(model) ? this.get(model) : model;
        var rm = function () {
            md && _this.all.remove(md, opts);
            return md;
        };
        !opts.silent && (em === null || em === void 0 ? void 0 : em.trigger(this.events.removeBefore, md, rm, opts));
        return !opts.abort && rm();
    };
    ItemManagerModule.prototype.__catchAllEvent = function (event, model, coll, opts) {
        var _a = this, em = _a.em, events = _a.events;
        var options = opts || coll;
        em && events.all && em.trigger(events.all, { event: event, model: model, options: options });
        this.__onAllEvent();
    };
    ItemManagerModule.prototype.__appendTo = function (renderProps) {
        //@ts-ignore
        var elTo = this.config.appendTo;
        if (elTo) {
            var el = (0,index_all.isElement)(elTo) ? elTo : document.querySelector(elTo);
            if (!el)
                return this.__logWarn('"appendTo" element not found');
            // @ts-ignore
            el.appendChild(this.render(renderProps));
        }
    };
    ItemManagerModule.prototype.__onAllEvent = function () { };
    ItemManagerModule.prototype._createId = function (len) {
        if (len === void 0) { len = 16; }
        var all = this.getAll();
        var ln = all.length + len;
        var allMap = this.getAllMap();
        var id;
        do {
            id = (0,mixins.createId)(ln);
        } while (allMap[id]);
        return id;
    };
    ItemManagerModule.prototype.__listenAdd = function (model, event) {
        var _this = this;
        model.on('add', function (m, c, o) { return _this.em.trigger(event, m, o); });
    };
    ItemManagerModule.prototype.__listenRemove = function (model, event) {
        var _this = this;
        model.on('remove', function (m, c, o) { return _this.em.trigger(event, m, o); });
    };
    ItemManagerModule.prototype.__listenUpdate = function (model, event) {
        var _this = this;
        model.on('change', function (p, c) { return _this.em.trigger(event, p, p.changedAttributes(), c); });
    };
    ItemManagerModule.prototype.__destroy = function () {
        var _a;
        this.cls.forEach(function (coll) {
            coll.stopListening();
            coll.reset();
        });
        (_a = this.view) === null || _a === void 0 ? void 0 : _a.remove();
        this.view = undefined;
    };
    return ItemManagerModule;
}(Module));


;// CONCATENATED MODULE: ./src/canvas/config/config.ts
var config_config_config = {
    stylePrefix: 'cv-',
    scripts: [],
    styles: [],
    customBadgeLabel: undefined,
    autoscrollLimit: 50,
    extHl: false,
    frameContent: '<!DOCTYPE html>',
    frameStyle: "\n    body { background-color: #fff }\n    * ::-webkit-scrollbar-track { background: rgba(0, 0, 0, 0.1) }\n    * ::-webkit-scrollbar-thumb { background: rgba(255, 255, 255, 0.2) }\n    * ::-webkit-scrollbar { width: 10px }\n  ",
    notTextable: ['button', 'a', 'input[type=checkbox]', 'input[type=radio]'],
    allowExternalDrop: true,
};
/* harmony default export */ const canvas_config_config = (config_config_config);

// EXTERNAL MODULE: ./src/abstract/ModuleModel.ts
var ModuleModel = __webpack_require__(642);
;// CONCATENATED MODULE: ./src/device_manager/config/config.ts
var device_manager_config_config_config = {
    default: '',
    devices: [
        {
            id: 'desktop',
            name: 'Desktop',
            width: '',
        },
        {
            id: 'tablet',
            name: 'Tablet',
            width: '770px',
            widthMedia: '992px',
        },
        {
            id: 'mobileLandscape',
            name: 'Mobile landscape',
            width: '568px',
            widthMedia: '768px',
        },
        {
            id: 'mobilePortrait',
            name: 'Mobile portrait',
            width: '320px',
            widthMedia: '480px',
        },
    ],
};
/* harmony default export */ const device_manager_config_config = (device_manager_config_config_config);

;// CONCATENATED MODULE: ./src/device_manager/model/Device.ts
var Device_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();

/**
 * @typedef Device
 * @property {String} [name=''] Device type, eg. `Mobile`
 * @property {String} [width] Width to set for the editor iframe, eg. '900px'
 * @property {String} [height=''] Height to set for the editor iframe, eg. '600px'
 * @property {String} [widthMedia=''] The width which will be used in media queries, If empty the width will be used
 * @property {Number} [priority=null] Setup the order of media queries
 */
var Device = /** @class */ (function (_super) {
    Device_extends(Device, _super);
    function Device() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Device.prototype.defaults = function () {
        return {
            name: '',
            width: null,
            height: '',
            widthMedia: null,
            priority: null,
        };
    };
    Device.prototype.initialize = function () {
        var _this = this;
        this.get('widthMedia') === null && this.set('widthMedia', this.get('width'));
        this.get('width') === null && this.set('width', this.get('widthMedia'));
        !this.get('priority') && this.set('priority', parseFloat(this.get('widthMedia')) || 0);
        var toCheck = ['width', 'height', 'widthMedia'];
        toCheck.forEach(function (prop) { return _this.checkUnit(prop); });
    };
    Device.prototype.checkUnit = function (prop) {
        var pr = (this.get(prop) || '');
        var noUnit = (parseFloat(pr) || 0).toString() === pr.toString();
        noUnit && this.set(prop, "".concat(pr, "px"));
    };
    Device.prototype.getName = function () {
        return this.get('name') || this.get('id');
    };
    Device.prototype.getWidthMedia = function () {
        return this.get('widthMedia') || '';
    };
    return Device;
}(common/* Model */.Hn));
/* harmony default export */ const model_Device = (Device);

;// CONCATENATED MODULE: ./src/device_manager/model/Devices.ts
var Devices_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();


var Devices = /** @class */ (function (_super) {
    Devices_extends(Devices, _super);
    function Devices() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    return Devices;
}(common/* Collection */.FE));
/* harmony default export */ const model_Devices = (Devices);
Devices.prototype.model = model_Device;

;// CONCATENATED MODULE: ./src/device_manager/view/DevicesView.ts
var DevicesView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __makeTemplateObject = (undefined && undefined.__makeTemplateObject) || function (cooked, raw) {
    if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
    return cooked;
};


var DevicesView = /** @class */ (function (_super) {
    DevicesView_extends(DevicesView, _super);
    function DevicesView(o) {
        var _this = _super.call(this, o) || this;
        _this.config = o.config || {};
        _this.em = _this.config.em;
        _this.ppfx = _this.config.pStylePrefix || '';
        _this.listenTo(_this.em, 'change:device', _this.updateSelect);
        return _this;
    }
    DevicesView.prototype.template = function (_a) {
        var ppfx = _a.ppfx, label = _a.label;
        return html(templateObject_1 || (templateObject_1 = __makeTemplateObject(["\n      <div class=\"", "device-label\">", "</div>\n      <div class=\"", "field ", "select\">\n        <span id=\"", "input-holder\">\n          <select class=\"", "devices\"></select>\n        </span>\n        <div class=\"", "sel-arrow\">\n          <div class=\"", "d-s-arrow\"></div>\n        </div>\n      </div>\n      <button style=\"display:none\" class=\"", "add-trasp\" data-add-trasp>+</button>\n    "], ["\n      <div class=\"", "device-label\">", "</div>\n      <div class=\"", "field ", "select\">\n        <span id=\"", "input-holder\">\n          <select class=\"", "devices\"></select>\n        </span>\n        <div class=\"", "sel-arrow\">\n          <div class=\"", "d-s-arrow\"></div>\n        </div>\n      </div>\n      <button style=\"display:none\" class=\"", "add-trasp\" data-add-trasp>+</button>\n    "])), ppfx, label, ppfx, ppfx, ppfx, ppfx, ppfx, ppfx, ppfx);
    };
    DevicesView.prototype.events = function () {
        return {
            change: 'updateDevice',
            'click [data-add-trasp]': 'startAdd',
        };
    };
    /**
     * Start adding new device
     * @return {[type]} [description]
     * @private
     */
    DevicesView.prototype.startAdd = function () { };
    /**
     * Update device of the editor
     * @private
     */
    DevicesView.prototype.updateDevice = function () {
        var em = this.em;
        if (em) {
            var devEl = this.devicesEl;
            em.set('device', devEl ? devEl.val() : '');
        }
    };
    /**
     * Update select value on device update
     * @private
     */
    DevicesView.prototype.updateSelect = function () {
        var _a = this, em = _a.em, devicesEl = _a.devicesEl;
        if (em && em.getDeviceModel && devicesEl) {
            var device = em.getDeviceModel();
            devicesEl.val(device ? device.get('id') : '');
        }
    };
    /**
     * Return devices options
     * @return {string} String of options
     * @private
     */
    DevicesView.prototype.getOptions = function () {
        var _a = this, collection = _a.collection, em = _a.em;
        var result = '';
        collection.forEach(function (device) {
            var _a = device.attributes, name = _a.name, id = _a.id;
            var label = (em && em.t && em.t("deviceManager.devices.".concat(id))) || name;
            result += "<option value=\"".concat(id || name, "\">").concat(label, "</option>");
        });
        return result;
    };
    DevicesView.prototype.render = function () {
        var _a = this, em = _a.em, ppfx = _a.ppfx, $el = _a.$el, el = _a.el;
        var label = em && em.t && em.t('deviceManager.device');
        $el.html(this.template({ ppfx: ppfx, label: label }));
        this.devicesEl = $el.find(".".concat(ppfx, "devices"));
        this.devicesEl.append(this.getOptions());
        this.devicesEl.val(em.get('device'));
        el.className = "".concat(ppfx, "devices-c");
        return this;
    };
    return DevicesView;
}(common/* View */.G7));
/* harmony default export */ const view_DevicesView = (DevicesView);
var templateObject_1;

;// CONCATENATED MODULE: ./src/device_manager/index.ts
var device_manager_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var device_manager_assign = (undefined && undefined.__assign) || function () {
    device_manager_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return device_manager_assign.apply(this, arguments);
};
/**
 * You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](https://github.com/GrapesJS/grapesjs/blob/master/src/device_manager/config/config.ts)
 * ```js
 * const editor = grapesjs.init({
 *  deviceManager: {
 *    // options
 *  }
 * })
 * ```
 *
 * Once the editor is instantiated you can use its API. Before using these methods you should get the module from the instance
 *
 * ```js
 * const deviceManager = editor.Devices;
 * ```
 * ## Available Events
 * * `device:add` - Added new device. The [Device] is passed as an argument to the callback
 * * `device:remove` - Device removed. The [Device] is passed as an argument to the callback
 * * `device:select` - New device selected. The newly selected [Device] and the previous one, are passed as arguments to the callback
 * * `device:update` - Device updated. The updated [Device] and the object containing changes are passed as arguments to the callback
 * * `device` - Catch-all event for all the events mentioned above. An object containing all the available data about the triggered event is passed as an argument to the callback
 *
 * ## Methods
 * * [add](#add)
 * * [get](#get)
 * * [getDevices](#getdevices)
 * * [remove](#remove)
 * * [select](#select)
 * * [getSelected](#getselected)
 *
 * [Device]: device.html
 *
 * @module Devices
 */






var evAll = 'device';
var evPfx = "".concat(evAll, ":");
var evSelect = "".concat(evPfx, "select");
var evSelectBefore = "".concat(evSelect, ":before");
var evUpdate = "".concat(evPfx, "update");
var evAdd = "".concat(evPfx, "add");
var evAddBefore = "".concat(evAdd, ":before");
var evRemove = "".concat(evPfx, "remove");
var evRemoveBefore = "".concat(evRemove, ":before");
var chnSel = 'change:device';
var deviceEvents = {
    all: evAll,
    select: evSelect,
    update: evUpdate,
    add: evAdd,
    remove: evRemove,
    removeBefore: evRemoveBefore,
};
var DeviceManager = /** @class */ (function (_super) {
    device_manager_extends(DeviceManager, _super);
    function DeviceManager(em) {
        var _a;
        var _this = _super.call(this, em, 'DeviceManager', new model_Devices(), deviceEvents, device_manager_config_config) || this;
        _this.Device = model_Device;
        _this.Devices = model_Devices;
        _this.storageKey = '';
        _this.devices = _this.all;
        (_a = _this.config.devices) === null || _a === void 0 ? void 0 : _a.forEach(function (device) { return _this.add(device, { silent: true }); });
        _this.select(_this.config.default || _this.devices.at(0));
        em.on(chnSel, _this._onSelect, _this);
        return _this;
    }
    DeviceManager.prototype._onSelect = function (m, deviceId, opts) {
        var _a = this, em = _a.em, events = _a.events;
        var prevId = m.previous('device');
        var newDevice = this.get(deviceId);
        var ev = events.select;
        em.trigger(ev, newDevice, this.get(prevId));
        this.__catchAllEvent(ev, newDevice, opts);
    };
    /**
     * Add new device
     * @param {Object} props Device properties
     * @returns {[Device]} Added device
     * @example
     * const device1 = deviceManager.add({
     *  // Without an explicit ID, the `name` will be taken. In case of missing `name`, a random ID will be created.
     *  id: 'tablet',
     *  name: 'Tablet',
     *  width: '900px', // This width will be applied on the canvas frame and for the CSS media
     * });
     * const device2 = deviceManager.add({
     *  id: 'tablet2',
     *  name: 'Tablet 2',
     *  width: '800px', // This width will be applied on the canvas frame
     *  widthMedia: '810px', // This width that will be used for the CSS media
     *  height: '600px', // Height will be applied on the canvas frame
     * });
     */
    DeviceManager.prototype.add = function (props, options) {
        if (options === void 0) { options = {}; }
        var result;
        var opts = options;
        // Support old API
        if ((0,index_all.isString)(props)) {
            var width = options;
            opts = arguments[2] || {};
            result = device_manager_assign(device_manager_assign({}, opts), { id: props, name: opts.name || props, width: width });
        }
        else {
            result = props;
        }
        if (!result.id) {
            result.id = result.name || this._createId();
        }
        return this.devices.add(result, opts);
    };
    /**
     * Return device by ID
     * @param  {String} id ID of the device
     * @returns {[Device]|null}
     * @example
     * const device = deviceManager.get('Tablet');
     * console.log(JSON.stringify(device));
     * // {name: 'Tablet', width: '900px'}
     */
    DeviceManager.prototype.get = function (id) {
        // Support old API
        var byName = this.getAll().filter(function (d) { return d.get('name') === id; })[0];
        return byName || this.devices.get(id) || null;
    };
    /**
     * Remove device
     * @param {String|[Device]} device Device or device id
     * @returns {[Device]} Removed device
     * @example
     * const removed = deviceManager.remove('device-id');
     * // or by passing the Device
     * const device = deviceManager.get('device-id');
     * deviceManager.remove(device);
     */
    DeviceManager.prototype.remove = function (device, opts) {
        if (opts === void 0) { opts = {}; }
        return this.__remove(device, opts);
    };
    /**
     * Return all devices
     * @returns {Array<[Device]>}
     * @example
     * const devices = deviceManager.getDevices();
     * console.log(JSON.stringify(devices));
     * // [{name: 'Desktop', width: ''}, ...]
     */
    DeviceManager.prototype.getDevices = function () {
        return this.devices.models;
    };
    /**
     * Change the selected device. This will update the frame in the canvas
     * @param {String|[Device]} device Device or device id
     * @example
     * deviceManager.select('some-id');
     * // or by passing the page
     * const device = deviceManager.get('some-id');
     * deviceManager.select(device);
     */
    DeviceManager.prototype.select = function (device, opts) {
        if (opts === void 0) { opts = {}; }
        var md = (0,index_all.isString)(device) ? this.get(device) : device;
        md && this.em.set('device', md.get('id'), opts);
        return this;
    };
    /**
     * Get the selected device
     * @returns {[Device]}
     * @example
     * const selected = deviceManager.getSelected();
     */
    DeviceManager.prototype.getSelected = function () {
        return this.get(this.em.get('device'));
    };
    DeviceManager.prototype.getAll = function () {
        return this.devices;
    };
    DeviceManager.prototype.render = function () {
        var _a;
        var em = this.em;
        (_a = this.view) === null || _a === void 0 ? void 0 : _a.remove();
        this.view = new view_DevicesView({
            collection: this.devices,
            config: device_manager_assign({ em: em }, this.config),
        });
        return this.view.render().el;
    };
    DeviceManager.prototype.destroy = function () {
        this.__destroy();
    };
    return DeviceManager;
}(ItemManagerModule));
/* harmony default export */ const device_manager = (DeviceManager);

;// CONCATENATED MODULE: ./src/pages/types.ts
/**{START_EVENTS}*/
var PagesEvents;
(function (PagesEvents) {
    /**
     * @event `page:add` Added new page. The page is passed as an argument to the callback.
     * @example
     * editor.on('page:add', (page) => { ... });
     */
    PagesEvents["add"] = "page:add";
    PagesEvents["addBefore"] = "page:add:before";
    /**
     * @event `page:remove` Page removed. The page is passed as an argument to the callback.
     * @example
     * editor.on('page:remove', (page) => { ... });
     */
    PagesEvents["remove"] = "page:remove";
    PagesEvents["removeBefore"] = "page:remove:before";
    /**
     * @event `page:select` New page selected. The newly selected page and the previous one, are passed as arguments to the callback.
     * @example
     * editor.on('page:select', (page, previousPage) => { ... });
     */
    PagesEvents["select"] = "page:select";
    PagesEvents["selectBefore"] = "page:select:before";
    /**
     * @event `page:update` Page updated. The updated page and the object containing changes are passed as arguments to the callback.
     * @example
     * editor.on('page:update', (page, changes) => { ... });
     */
    PagesEvents["update"] = "page:update";
    /**
     * @event `page` Catch-all event for all the events mentioned above. An object containing all the available data about the triggered event is passed as an argument to the callback.
     * @example
     * editor.on('page', ({ event, model, ... }) => { ... });
     */
    PagesEvents["all"] = "page";
})(PagesEvents || (PagesEvents = {}));
/**{END_EVENTS}*/
// need this to avoid the TS documentation generator to break
/* harmony default export */ const types = (PagesEvents);

;// CONCATENATED MODULE: ./src/abstract/ModuleCollection.ts
var ModuleCollection_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();


var ModuleCollection = /** @class */ (function (_super) {
    ModuleCollection_extends(ModuleCollection, _super);
    function ModuleCollection(module, models, modelConstructor) {
        return _super.call(this, models, { module: module, modelConstructor: modelConstructor }) || this;
    }
    ModuleCollection.prototype.add = function (model, options) {
        var _this = this;
        var _a;
        //Note: the undefined case needed because backbonejs not handle the reset() correctly
        var models = (0,index_all.isArray)(model) ? model : !(0,index_all.isUndefined)(model) ? [model] : undefined;
        models = (_a = models === null || models === void 0 ? void 0 : models.map(function (m) { return (m instanceof _this.newModel ? m : new _this.newModel(_this.module, m)); })) !== null && _a !== void 0 ? _a : [undefined];
        return _super.prototype.add.call(this, (0,index_all.isArray)(model) ? models : models[0], options);
    };
    ModuleCollection.prototype.preinitialize = function (models, options) {
        this.newModel = options.modelConstructor;
        this.module = options.module;
    };
    return ModuleCollection;
}(common/* Collection */.FE));
/* harmony default export */ const abstract_ModuleCollection = (ModuleCollection);

;// CONCATENATED MODULE: ./src/canvas/model/Frame.ts
var Frame_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var Frame_assign = (undefined && undefined.__assign) || function () {
    Frame_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return Frame_assign.apply(this, arguments);
};
var Frame_spreadArray = (undefined && undefined.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};



var keyAutoW = '__aw';
var keyAutoH = '__ah';
var getDimension = function (frame, type) {
    var _a;
    var dim = frame.get(type);
    var viewDim = (_a = frame.view) === null || _a === void 0 ? void 0 : _a.el[type === 'width' ? 'offsetWidth' : 'offsetHeight'];
    if ((0,index_all.isNumber)(dim)) {
        return dim;
    }
    else if ((0,index_all.isString)(dim) && dim.endsWith('px')) {
        return parseFloat(dim);
    }
    else if (viewDim) {
        return viewDim;
    }
    else {
        return 0;
    }
};
/**
 * @property {Object|String} component Wrapper component definition. You can also pass an HTML string as components of the default wrapper component.
 * @property {String} [width=''] Width of the frame. By default, the canvas width will be taken.
 * @property {String} [height=''] Height of the frame. By default, the canvas height will be taken.
 * @property {Number} [x=0] Horizontal position of the frame in the canvas.
 * @property {Number} [y=0] Vertical position of the frame in the canvas.
 *
 */
var Frame = /** @class */ (function (_super) {
    Frame_extends(Frame, _super);
    /**
     * @hideconstructor
     */
    function Frame(module, attr) {
        var _this = _super.call(this, module, attr) || this;
        var em = _this.em;
        var _a = _this.attributes, styles = _a.styles, component = _a.component;
        var domc = em.Components;
        var conf = domc.getConfig();
        var allRules = em.Css.getAll();
        var idMap = {};
        var modOpts = { em: em, config: conf, frame: _this, idMap: idMap };
        if (!(0,mixins.isComponent)(component)) {
            var wrp = (0,mixins.isObject)(component) ? component : { components: component };
            !wrp.type && (wrp.type = 'wrapper');
            var Wrapper = domc.getType('wrapper').model;
            _this.set('component', new Wrapper(wrp, modOpts));
        }
        if (!styles) {
            _this.set('styles', allRules);
        }
        else if (!(0,mixins.isObject)(styles)) {
            var newStyles = styles;
            // Avoid losing styles on remapped components
            if ((0,index_all.keys)(idMap).length) {
                newStyles = (0,index_all.isString)(newStyles) ? em.Parser.parseCss(newStyles) : newStyles;
                em.Css.checkId(newStyles, { idMap: idMap });
            }
            allRules.add(newStyles);
            _this.set('styles', allRules);
        }
        !attr.width && _this.set(keyAutoW, 1);
        !attr.height && _this.set(keyAutoH, 1);
        !_this.id && _this.set('id', (0,mixins.createId)());
        return _this;
    }
    Frame.prototype.defaults = function () {
        return {
            x: 0,
            y: 0,
            changesCount: 0,
            attributes: {},
            width: null,
            height: null,
            head: [],
            component: '',
            styles: '',
            refFrame: null,
            _undo: true,
            _undoexc: ['changesCount'],
        };
    };
    Object.defineProperty(Frame.prototype, "width", {
        get: function () {
            return getDimension(this, 'width');
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Frame.prototype, "height", {
        get: function () {
            return getDimension(this, 'height');
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Frame.prototype, "head", {
        get: function () {
            return this.get('head');
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Frame.prototype, "refFrame", {
        get: function () {
            return this.get('refFrame');
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Frame.prototype, "root", {
        get: function () {
            var refFrame = this.refFrame;
            return (refFrame === null || refFrame === void 0 ? void 0 : refFrame.getComponent()) || this.getComponent();
        },
        enumerable: false,
        configurable: true
    });
    Frame.prototype.initRefs = function () {
        var refFrame = this.refFrame;
        if ((0,index_all.isString)(refFrame)) {
            var frame = this.module.framesById[refFrame];
            frame && this.set({ refFrame: frame }, { silent: true });
        }
    };
    Frame.prototype.getBoxRect = function () {
        var _a = this.attributes, x = _a.x, y = _a.y;
        var _b = this, width = _b.width, height = _b.height;
        return {
            x: x,
            y: y,
            width: width,
            height: height,
        };
    };
    Frame.prototype.onRemove = function () {
        !this.refFrame && this.getComponent().remove({ root: 1 });
    };
    Frame.prototype.changesUp = function (opt) {
        if (opt === void 0) { opt = {}; }
        if (opt.temporary || opt.noCount || opt.avoidStore) {
            return;
        }
        this.set('changesCount', this.get('changesCount') + 1);
    };
    Frame.prototype.getComponent = function () {
        return this.get('component');
    };
    Frame.prototype.getStyles = function () {
        return this.get('styles');
    };
    Frame.prototype.disable = function () {
        this.trigger('disable');
    };
    Frame.prototype.remove = function () {
        var _a;
        (_a = this.view) === null || _a === void 0 ? void 0 : _a.remove();
        this.view = undefined;
        var coll = this.collection;
        return coll && coll.remove(this);
    };
    Frame.prototype.getHead = function () {
        return Frame_spreadArray([], this.head, true);
    };
    Frame.prototype.setHead = function (value) {
        return this.set('head', Frame_spreadArray([], value, true));
    };
    Frame.prototype.addHeadItem = function (item) {
        this.head.push(item);
    };
    Frame.prototype.getHeadByAttr = function (attr, value, tag) {
        return this.head.filter(function (item) { return item.attributes && item.attributes[attr] == value && (!tag || tag === item.tag); })[0];
    };
    Frame.prototype.removeHeadByAttr = function (attr, value, tag) {
        var item = this.getHeadByAttr(attr, value, tag);
        var index = this.head.indexOf(item);
        if (index >= 0) {
            this.head.splice(index, 1);
        }
    };
    Frame.prototype.addLink = function (href) {
        var tag = 'link';
        !this.getHeadByAttr('href', href, tag) &&
            this.addHeadItem({
                tag: tag,
                attributes: {
                    href: href,
                    rel: 'stylesheet',
                },
            });
    };
    Frame.prototype.removeLink = function (href) {
        this.removeHeadByAttr('href', href, 'link');
    };
    Frame.prototype.addScript = function (src) {
        var tag = 'script';
        !this.getHeadByAttr('src', src, tag) &&
            this.addHeadItem({
                tag: tag,
                attributes: { src: src },
            });
    };
    Frame.prototype.removeScript = function (src) {
        this.removeHeadByAttr('src', src, 'script');
    };
    Frame.prototype.getPage = function () {
        var _a;
        return (_a = this.collection) === null || _a === void 0 ? void 0 : _a.page;
    };
    Frame.prototype._emitUpdated = function (data) {
        if (data === void 0) { data = {}; }
        this.em.trigger('frame:updated', Frame_assign({ frame: this }, data));
    };
    Frame.prototype.hasAutoHeight = function () {
        var height = this.attributes.height;
        if (height === 'auto' || this.config.infiniteCanvas) {
            return true;
        }
        return false;
    };
    Frame.prototype.toJSON = function (opts) {
        if (opts === void 0) { opts = {}; }
        var obj = ModuleModel/* default */.Z.prototype.toJSON.call(this, opts);
        var defaults = (0,index_all.result)(this, 'defaults');
        if (opts.fromUndo)
            delete obj.component;
        delete obj.styles;
        delete obj.changesCount;
        obj[keyAutoW] && delete obj.width;
        obj[keyAutoH] && delete obj.height;
        if (obj.refFrame) {
            obj.refFrame = obj.refFrame.id;
            delete obj.component;
        }
        // Remove private keys
        (0,index_all.forEach)(obj, function (value, key) {
            key.indexOf('_') === 0 && delete obj[key];
        });
        (0,index_all.forEach)(defaults, function (value, key) {
            if (obj[key] === value)
                delete obj[key];
        });
        (0,index_all.forEach)(['attributes', 'head'], function (prop) {
            if ((0,index_all.isEmpty)(obj[prop]))
                delete obj[prop];
        });
        return obj;
    };
    return Frame;
}(ModuleModel/* default */.Z));
/* harmony default export */ const model_Frame = (Frame);

;// CONCATENATED MODULE: ./src/canvas/model/Frames.ts
var Frames_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();



var Frames = /** @class */ (function (_super) {
    Frames_extends(Frames, _super);
    function Frames(module, models) {
        if (models === void 0) { models = []; }
        var _this = _super.call(this, module, models, model_Frame) || this;
        _this.loadedItems = 0;
        _this.itemsToLoad = 0;
        (0,index_all.bindAll)(_this, 'itemLoaded');
        _this.on('add', _this.onAdd);
        _this.on('reset', _this.onReset);
        _this.on('remove', _this.onRemove);
        _this.forEach(function (frame) { return _this.onAdd(frame); });
        return _this;
    }
    Frames.prototype.onAdd = function (frame) {
        this.module.framesById[frame.id] = frame;
    };
    Frames.prototype.onReset = function (m, opts) {
        var _this = this;
        var prev = (opts === null || opts === void 0 ? void 0 : opts.previousModels) || [];
        prev.map(function (p) { return _this.onRemove(p); });
    };
    Frames.prototype.onRemove = function (frame) {
        frame.onRemove();
        delete this.module.framesById[frame.id];
    };
    Frames.prototype.initRefs = function () {
        this.forEach(function (frame) { return frame.initRefs(); });
    };
    Frames.prototype.itemLoaded = function () {
        this.loadedItems++;
        if (this.loadedItems >= this.itemsToLoad) {
            this.trigger('loaded:all');
            this.listenToLoadItems(false);
        }
    };
    Frames.prototype.listenToLoad = function () {
        this.loadedItems = 0;
        this.itemsToLoad = this.length;
        this.listenToLoadItems(true);
    };
    Frames.prototype.listenToLoadItems = function (on) {
        var _this = this;
        this.forEach(function (item) { return item[on ? 'on' : 'off']('loaded', _this.itemLoaded); });
    };
    return Frames;
}(abstract_ModuleCollection));
/* harmony default export */ const model_Frames = (Frames);

;// CONCATENATED MODULE: ./src/canvas/model/Canvas.ts
var Canvas_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();





var Canvas = /** @class */ (function (_super) {
    Canvas_extends(Canvas, _super);
    function Canvas(module) {
        var _this = this;
        var em = module.em, config = module.config;
        var scripts = config.scripts, styles = config.styles;
        _this = _super.call(this, module, { scripts: scripts, styles: styles }) || this;
        _this.set('frames', new model_Frames(module));
        _this.on('change:zoom', _this.onZoomChange);
        _this.on('change:x change:y', _this.onCoordsChange);
        _this.on('change:pointer change:pointerScreen', _this.onPointerChange);
        _this.listenTo(em, "change:device ".concat(evUpdate), _this.updateDevice);
        _this.listenTo(em, types.select, _this._pageUpdated);
        return _this;
    }
    Canvas.prototype.defaults = function () {
        return {
            frame: '',
            frames: [],
            rulers: false,
            zoom: 100,
            x: 0,
            y: 0,
            // Scripts to apply on all frames
            scripts: [],
            // Styles to apply on all frames
            styles: [],
            pointer: common/* DEFAULT_COORDS */.pH,
            pointerScreen: common/* DEFAULT_COORDS */.pH,
        };
    };
    Object.defineProperty(Canvas.prototype, "frames", {
        get: function () {
            return this.get('frames');
        },
        enumerable: false,
        configurable: true
    });
    Canvas.prototype.init = function () {
        var em = this.em;
        var mainPage = em.Pages._initPage();
        this.set('frames', mainPage.getFrames());
        this.updateDevice({ frame: mainPage.getMainFrame() });
    };
    Canvas.prototype._pageUpdated = function (page, prev) {
        var em = this.em;
        em.setSelected();
        em.get('readyCanvas') && em.stopDefault(); // We have to stop before changing current frames
        prev === null || prev === void 0 ? void 0 : prev.getFrames().map(function (frame) { return frame.disable(); });
        this.set('frames', page.getFrames());
        this.updateDevice({ frame: page.getMainFrame() });
    };
    Canvas.prototype.updateDevice = function (opts) {
        if (opts === void 0) { opts = {}; }
        var em = this.em;
        var device = em.getDeviceModel();
        var model = opts.frame || em.getCurrentFrameModel();
        if (model && device) {
            var _a = device.attributes, width = _a.width, height = _a.height;
            model.set({ width: width, height: height }, { noUndo: 1 });
        }
    };
    Canvas.prototype.onZoomChange = function () {
        var _a = this, em = _a.em, module = _a.module;
        var zoom = this.get('zoom');
        zoom < 1 && this.set('zoom', 1);
        em.trigger(module.events.zoom);
    };
    Canvas.prototype.onCoordsChange = function () {
        var _a = this, em = _a.em, module = _a.module;
        em.trigger(module.events.coords);
    };
    Canvas.prototype.onPointerChange = function () {
        var _a = this, em = _a.em, module = _a.module;
        em.trigger(module.events.pointer);
    };
    Canvas.prototype.getPointerCoords = function (type) {
        if (type === void 0) { type = common/* CoordinatesTypes */.vA.World; }
        var _a = this.attributes, pointer = _a.pointer, pointerScreen = _a.pointerScreen;
        return type === common/* CoordinatesTypes */.vA.World ? pointer : pointerScreen;
    };
    return Canvas;
}(ModuleModel/* default */.Z));
/* harmony default export */ const model_Canvas = (Canvas);

// EXTERNAL MODULE: ./src/canvas/model/CanvasSpot.ts
var CanvasSpot = __webpack_require__(675);
;// CONCATENATED MODULE: ./src/canvas/model/CanvasSpots.ts
var CanvasSpots_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();



var CanvasSpots = /** @class */ (function (_super) {
    CanvasSpots_extends(CanvasSpots, _super);
    function CanvasSpots(module, models) {
        if (models === void 0) { models = []; }
        var _this = _super.call(this, module, models, CanvasSpot/* default */.Z) || this;
        _this.on('add', _this.onAdd);
        _this.on('change', _this.onChange);
        _this.on('remove', _this.onRemove);
        var em = _this.em;
        _this.refreshDbn = (0,index_all.debounce)(function () { return _this.refresh(); }, 0);
        var evToRefreshDbn = 'component:resize styleable:change component:input component:update frame:updated undo redo';
        _this.listenTo(em, evToRefreshDbn, function () { return _this.refreshDbn(); });
        return _this;
    }
    Object.defineProperty(CanvasSpots.prototype, "em", {
        get: function () {
            return this.module.em;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(CanvasSpots.prototype, "events", {
        get: function () {
            return this.module.events;
        },
        enumerable: false,
        configurable: true
    });
    CanvasSpots.prototype.refresh = function () {
        var _a = this, em = _a.em, events = _a.events;
        em.trigger(events.spot);
    };
    CanvasSpots.prototype.onAdd = function (spot) {
        this.__trgEvent(this.events.spotAdd, { spot: spot });
    };
    CanvasSpots.prototype.onChange = function (spot) {
        this.__trgEvent(this.events.spotUpdate, { spot: spot });
    };
    CanvasSpots.prototype.onRemove = function (spot) {
        this.__trgEvent(this.events.spotRemove, { spot: spot });
    };
    CanvasSpots.prototype.__trgEvent = function (event, props) {
        var module = this.module;
        var em = module.em;
        em.trigger(event, props);
        this.refreshDbn();
    };
    return CanvasSpots;
}(abstract_ModuleCollection));
/* harmony default export */ const model_CanvasSpots = (CanvasSpots);

;// CONCATENATED MODULE: ./src/canvas/types.ts
/**{START_EVENTS}*/
var CanvasEvents;
(function (CanvasEvents) {
    /**
     * @event `canvas:dragenter` Something is dragged inside the canvas, `DataTransfer` instance passed as an argument.
     */
    CanvasEvents["dragEnter"] = "canvas:dragenter";
    /**
     * @event `canvas:dragover` Something is dragging on the canvas, `DataTransfer` instance passed as an argument.
     */
    CanvasEvents["dragOver"] = "canvas:dragover";
    /**
     * @event `canvas:dragend` When a drag operation is ended, `DataTransfer` instance passed as an argument.
     */
    CanvasEvents["dragEnd"] = "canvas:dragend";
    /**
     * @event `canvas:dragdata` On any dataTransfer parse, `DataTransfer` instance and the `result` are passed as arguments.
     * By changing `result.content` you're able to customize what is dropped.
     */
    CanvasEvents["dragData"] = "canvas:dragdata";
    /**
     * @event `canvas:drop` Something is dropped in canvas, `DataTransfer` instance and the dropped model are passed as arguments.
     */
    CanvasEvents["drop"] = "canvas:drop";
    /**
     * @event `canvas:spot` Spots updated.
     * @example
     * editor.on('canvas:spot', () => {
     *  console.log('Spots', editor.Canvas.getSpots());
     * });
     */
    CanvasEvents["spot"] = "canvas:spot";
    /**
     * @event `canvas:spot:add` New canvas spot added.
     * @example
     * editor.on('canvas:spot:add', ({ spot }) => {
     *  console.log('Spot added', spot);
     * });
     */
    CanvasEvents["spotAdd"] = "canvas:spot:add";
    /**
     * @event `canvas:spot:update` Canvas spot updated.
     * @example
     * editor.on('canvas:spot:update', ({ spot }) => {
     *  console.log('Spot updated', spot);
     * });
     */
    CanvasEvents["spotUpdate"] = "canvas:spot:update";
    /**
     * @event `canvas:spot:remove` Canvas spot removed.
     * @example
     * editor.on('canvas:spot:remove', ({ spot }) => {
     *  console.log('Spot removed', spot);
     * });
     */
    CanvasEvents["spotRemove"] = "canvas:spot:remove";
    /**
     * @event `canvas:coords` Canvas coordinates updated.
     * @example
     * editor.on('canvas:coords', () => {
     *  console.log('Canvas coordinates updated:', editor.Canvas.getCoords());
     * });
     */
    CanvasEvents["coords"] = "canvas:coords";
    /**
     * @event `canvas:zoom` Canvas zoom updated.
     * @example
     * editor.on('canvas:zoom', () => {
     *  console.log('Canvas zoom updated:', editor.Canvas.getZoom());
     * });
     */
    CanvasEvents["zoom"] = "canvas:zoom";
    /**
     * @event `canvas:pointer` Canvas pointer updated.
     * @example
     * editor.on('canvas:pointer', () => {
     *  console.log('Canvas pointer updated:', editor.Canvas.getPointer());
     * });
     */
    CanvasEvents["pointer"] = "canvas:pointer";
    /**
     * @event `canvas:refresh` Canvas was refreshed to update elements on top,
     * like spots/tools (eg. via `editor.Canvas.refresh()` or on frame resize).
     * @example
     * editor.on('canvas:refresh', (canvasRefreshOptions) => {
     *  console.log('Canvas refreshed with options:', canvasRefreshOptions);
     * });
     */
    CanvasEvents["refresh"] = "canvas:refresh";
    /**
     * @event `canvas:frame:load` Frame loaded in canvas.
     * The event is triggered right after iframe's `onload`.
     * @example
     * editor.on('canvas:frame:load', ({ window }) => {
     *  console.log('Frame loaded', window);
     * });
     */
    CanvasEvents["frameLoad"] = "canvas:frame:load";
    /**
     * @event `canvas:frame:load:head` Frame head loaded in canvas.
     * The event is triggered right after iframe's finished to load the head elemenets (eg. scripts)
     * @example
     * editor.on('canvas:frame:load:head', ({ window }) => {
     *  console.log('Frame head loaded', window);
     * });
     */
    CanvasEvents["frameLoadHead"] = "canvas:frame:load:head";
    /**
     * @event `canvas:frame:load:body` Frame body loaded in canvas.
     * The event is triggered when the body is rendered with components.
     * @example
     * editor.on('canvas:frame:load:body', ({ window }) => {
     *  console.log('Frame completed the body render', window);
     * });
     */
    CanvasEvents["frameLoadBody"] = "canvas:frame:load:body";
})(CanvasEvents || (CanvasEvents = {}));
/**{END_EVENTS}*/
// need this to avoid the TS documentation generator to break
/* harmony default export */ const canvas_types = (CanvasEvents);

;// CONCATENATED MODULE: ./src/abstract/ModuleView.ts
var ModuleView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();

// type TCollection<TItem extends ModuleModel | ModuleCollection> = TItem extends ModuleCollection ? TItem : unknown;
var ModuleView = /** @class */ (function (_super) {
    ModuleView_extends(ModuleView, _super);
    function ModuleView() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(ModuleView.prototype, "pfx", {
        get: function () {
            return this.ppfx + this.config.stylePrefix || '';
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ModuleView.prototype, "ppfx", {
        get: function () {
            return this.em.config.stylePrefix || '';
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ModuleView.prototype, "module", {
        get: function () {
            var _a, _b;
            return (_b = (_a = this.model) === null || _a === void 0 ? void 0 : _a.module) !== null && _b !== void 0 ? _b : this.collection.module;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ModuleView.prototype, "em", {
        get: function () {
            return this.module.em;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ModuleView.prototype, "config", {
        get: function () {
            return this.module.config;
        },
        enumerable: false,
        configurable: true
    });
    ModuleView.prototype.preinitialize = function (options) {
        this.className = '';
    };
    return ModuleView;
}(common/* View */.G7));
/* harmony default export */ const abstract_ModuleView = (ModuleView);

// EXTERNAL MODULE: ./src/utils/dom.ts
var dom = __webpack_require__(491);
;// CONCATENATED MODULE: ./src/abstract/ModuleDomainViews.ts
var ModuleDomainViews_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();


var ModuleDomainViews = /** @class */ (function (_super) {
    ModuleDomainViews_extends(ModuleDomainViews, _super);
    function ModuleDomainViews(opts, autoAdd) {
        if (opts === void 0) { opts = {}; }
        if (autoAdd === void 0) { autoAdd = false; }
        var _this = _super.call(this, opts) || this;
        // Defines the View per type
        _this.itemsView = '';
        _this.itemType = 'type';
        _this.reuseView = false;
        _this.viewCollection = [];
        autoAdd && _this.listenTo(_this.collection, 'add', _this.addTo);
        return _this;
    }
    /**
     * Add new model to the collection
     * @param {ModuleModel} model
     * @private
     * */
    ModuleDomainViews.prototype.addTo = function (model) {
        this.add(model);
    };
    ModuleDomainViews.prototype.itemViewNotFound = function (type) {
        /*const { em, ns } = this;
        const warn = `${ns ? `[${ns}]: ` : ''}'${type}' type not found`;
        em?.logWarning(warn);*/
    };
    /**
     * Render new model inside the view
     * @param {ModuleModel} model
     * @param {Object} fragment Fragment collection
     * @private
     * */
    ModuleDomainViews.prototype.add = function (model, fragment) {
        var _a = this, reuseView = _a.reuseView, viewCollection = _a.viewCollection;
        var frag = fragment || null;
        var typeField = model.get(this.itemType);
        var view;
        //@ts-ignore
        if (model.view && reuseView) {
            //@ts-ignore
            view = model.view;
        }
        else {
            view = this.renderView(model, typeField);
        }
        viewCollection.push(view);
        var rendered = view.render().el;
        if (frag)
            frag.appendChild(rendered);
        else
            this.$el.append(rendered);
    };
    ModuleDomainViews.prototype.render = function () {
        var _this = this;
        var frag = document.createDocumentFragment();
        this.clearItems();
        this.$el.empty();
        if (this.collection.length)
            this.collection.each(function (model) { return _this.add(model, frag); });
        this.$el.append(frag);
        this.onRender();
        return this;
    };
    ModuleDomainViews.prototype.onRender = function () { };
    ModuleDomainViews.prototype.onRemoveBefore = function (items, opts) { };
    ModuleDomainViews.prototype.onRemove = function (items, opts) { };
    ModuleDomainViews.prototype.remove = function (opts) {
        if (opts === void 0) { opts = {}; }
        var viewCollection = this.viewCollection;
        this.onRemoveBefore(viewCollection, opts);
        this.clearItems();
        common/* View */.G7.prototype.remove.apply(this, opts);
        this.onRemove(viewCollection, opts);
        return this;
    };
    ModuleDomainViews.prototype.clearItems = function () {
        var items = this.viewCollection || [];
        // TODO Traits do not update the target anymore
        // items.forEach(item => item.remove());
        // this.items = [];
    };
    return ModuleDomainViews;
}(abstract_ModuleView));
/* harmony default export */ const abstract_ModuleDomainViews = (ModuleDomainViews);

;// CONCATENATED MODULE: ./src/css_composer/view/CssRuleView.ts
var CssRuleView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();

var CssRuleView = /** @class */ (function (_super) {
    CssRuleView_extends(CssRuleView, _super);
    function CssRuleView(o) {
        if (o === void 0) { o = {}; }
        var _this = _super.call(this, o) || this;
        _this.config = o.config || {};
        var model = _this.model;
        _this.listenTo(model, 'change', _this.render);
        _this.listenTo(model, 'destroy remove', _this.remove);
        _this.listenTo(model.get('selectors'), 'change', _this.render);
        return _this;
    }
    // @ts-ignore
    CssRuleView.prototype.tagName = function () {
        return 'style';
    };
    CssRuleView.prototype.render = function () {
        var _a = this, model = _a.model, el = _a.el;
        var important = model.get('important');
        el.innerHTML = model.toCSS({ important: important });
        return this;
    };
    return CssRuleView;
}(common/* View */.G7));
/* harmony default export */ const view_CssRuleView = (CssRuleView);

;// CONCATENATED MODULE: ./src/css_composer/view/CssGroupRuleView.ts
var CssGroupRuleView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();

var CssGroupRuleView = /** @class */ (function (_super) {
    CssGroupRuleView_extends(CssGroupRuleView, _super);
    function CssGroupRuleView() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    CssGroupRuleView.prototype._createElement = function () {
        return document.createTextNode('');
    };
    CssGroupRuleView.prototype.render = function () {
        var model = this.model;
        var important = model.get('important');
        this.el.textContent = model.getDeclaration({ important: important });
        return this;
    };
    return CssGroupRuleView;
}(view_CssRuleView));
/* harmony default export */ const view_CssGroupRuleView = (CssGroupRuleView);

;// CONCATENATED MODULE: ./src/css_composer/view/CssRulesView.ts
var CssRulesView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();





var getBlockId = function (pfx, order) { return "".concat(pfx).concat(order ? "-".concat(parseFloat(order)) : ''); };
var CssRulesView = /** @class */ (function (_super) {
    CssRulesView_extends(CssRulesView, _super);
    function CssRulesView(o) {
        var _this = _super.call(this, o) || this;
        (0,index_all.bindAll)(_this, 'sortRules');
        var config = o.config || {};
        _this.atRules = {};
        _this.config = config;
        _this.em = config.em;
        _this.pfx = config.stylePrefix || '';
        _this.className = _this.pfx + 'rules';
        var coll = _this.collection;
        _this.listenTo(coll, 'add', _this.addTo);
        _this.listenTo(coll, 'reset', _this.render);
        return _this;
    }
    /**
     * Add to collection
     * @param {Object} model
     * @private
     * */
    CssRulesView.prototype.addTo = function (model) {
        this.addToCollection(model);
    };
    /**
     * Add new object to collection
     * @param {Object} model
     * @param {Object} fragmentEl
     * @return {Object}
     * @private
     * */
    CssRulesView.prototype.addToCollection = function (model, fragmentEl) {
        // If the render is not yet started
        if (!this.renderStarted) {
            return;
        }
        var fragment = fragmentEl || null;
        var config = this.config;
        var opts = { model: model, config: config };
        var rendered, view;
        // I have to render keyframes of the same name together
        // Unfortunately at the moment I didn't find the way of appending them
        // if not staticly, via appendData
        if (model.get('atRuleType') === 'keyframes') {
            var atRule = model.getAtRule();
            var atRuleEl = this.atRules[atRule];
            if (!atRuleEl) {
                var styleEl = document.createElement('style');
                atRuleEl = document.createTextNode('');
                styleEl.appendChild(document.createTextNode("".concat(atRule, "{")));
                styleEl.appendChild(atRuleEl);
                styleEl.appendChild(document.createTextNode('}'));
                this.atRules[atRule] = atRuleEl;
                rendered = styleEl;
            }
            view = new view_CssGroupRuleView(opts);
            atRuleEl.appendData(view.render().el.textContent);
        }
        else {
            view = new view_CssRuleView(opts);
            rendered = view.render().el;
        }
        var clsName = this.className;
        var mediaText = model.get('mediaText');
        var defaultBlockId = getBlockId(clsName);
        var blockId = defaultBlockId;
        // If the rule contains a media query it might have a different container
        // for it (eg. rules created with Device Manager)
        if (mediaText) {
            blockId = getBlockId(clsName, this.getMediaWidth(mediaText));
        }
        if (rendered) {
            var container = fragment || this.el;
            var contRules = void 0;
            // Try to find a specific container for the rule (if it
            // containes a media query), otherwise get the default one
            try {
                contRules = container.querySelector("#".concat(blockId));
            }
            catch (e) { }
            if (!contRules) {
                contRules = container.querySelector("#".concat(defaultBlockId));
            }
            contRules === null || contRules === void 0 ? void 0 : contRules.appendChild(rendered);
        }
        return rendered;
    };
    CssRulesView.prototype.getMediaWidth = function (mediaText) {
        return mediaText && mediaText.replace("(".concat(this.em.getConfig().mediaCondition, ": "), '').replace(')', '');
    };
    CssRulesView.prototype.sortRules = function (a, b) {
        var em = this.em;
        var isMobFirst = (em.getConfig().mediaCondition || '').indexOf('min-width') !== -1;
        if (!isMobFirst)
            return 0;
        var left = isMobFirst ? a : b;
        var right = isMobFirst ? b : a;
        return left - right;
    };
    CssRulesView.prototype.render = function () {
        var _this = this;
        this.renderStarted = true;
        this.atRules = {};
        var _a = this, em = _a.em, $el = _a.$el, collection = _a.collection;
        var cls = this.className;
        var frag = document.createDocumentFragment();
        $el.empty();
        // Create devices related DOM structure, ensure also to have a default container
        var prs = em.Devices.getAll().pluck('priority').sort(this.sortRules);
        prs.every(function (pr) { return pr; }) && prs.unshift(0);
        prs.forEach(function (pr) { return frag.appendChild((0,dom/* createEl */.ut)('div', { id: getBlockId(cls, pr) })); });
        collection.each(function (model) { return _this.addToCollection(model, frag); });
        $el.append(frag);
        $el.attr('class', cls);
        return this;
    };
    return CssRulesView;
}(common/* View */.G7));
/* harmony default export */ const view_CssRulesView = (CssRulesView);

;// CONCATENATED MODULE: ./src/utils/Droppable.ts
var Droppable_assign = (undefined && undefined.__assign) || function () {
    Droppable_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return Droppable_assign.apply(this, arguments);
};


/**
 * This class makes the canvas droppable
 */
var Droppable = /** @class */ (function () {
    function Droppable(em, rootEl) {
        var _this = this;
        this.em = em;
        this.canvas = em.Canvas;
        var el = rootEl || this.canvas.getFrames().map(function (frame) { return frame.getComponent().getEl(); });
        var els = Array.isArray(el) ? el : [el];
        this.el = els[0];
        this.counter = 0;
        (0,index_all.bindAll)(this, 'handleDragEnter', 'handleDragOver', 'handleDrop', 'handleDragLeave');
        els.forEach(function (el) { return _this.toggleEffects(el, true); });
    }
    Droppable.prototype.toggleEffects = function (el, enable) {
        var methods = { on: dom.on, off: dom/* off */.S1 };
        var method = enable ? 'on' : 'off';
        methods[method](el, 'dragenter', this.handleDragEnter);
        methods[method](el, 'dragover', this.handleDragOver);
        methods[method](el, 'drop', this.handleDrop);
        methods[method](el, 'dragleave', this.handleDragLeave);
    };
    Droppable.prototype.__customTglEff = function (enable) {
        var _a;
        var method = enable ? dom.on : dom/* off */.S1;
        var doc = this.el.ownerDocument;
        var frameEl = (_a = doc.defaultView) === null || _a === void 0 ? void 0 : _a.frameElement;
        this.sortOpts = enable
            ? {
                onStart: function (_a) {
                    var sorter = _a.sorter;
                    (0,dom.on)(frameEl, 'pointermove', sorter.onMove);
                },
                onEnd: function (_a) {
                    var sorter = _a.sorter;
                    (0,dom/* off */.S1)(frameEl, 'pointermove', sorter.onMove);
                },
                customTarget: function (_a) {
                    var event = _a.event;
                    return doc.elementFromPoint(event.clientX, event.clientY);
                },
            }
            : null;
        method(frameEl, 'pointerenter', this.handleDragEnter);
        method(frameEl, 'pointermove', this.handleDragOver);
        method(document, 'pointerup', this.handleDrop);
        method(frameEl, 'pointerout', this.handleDragLeave);
        // Test with touch devices (seems like frameEl is not capturing pointer events).
        // on/off(document, 'pointermove', sorter.onMove); // for the sorter
        // enable && this.handleDragEnter({}); // no way to use pointerenter/pointerout
    };
    Droppable.prototype.startCustom = function () {
        this.__customTglEff(true);
    };
    Droppable.prototype.endCustom = function (cancel) {
        this.over ? this.endDrop(cancel) : this.__customTglEff(false);
    };
    /**
     * This function is expected to be always executed at the end of d&d.
     */
    Droppable.prototype.endDrop = function (cancel, ev) {
        var _a = this, em = _a.em, dragStop = _a.dragStop;
        this.counter = 0;
        dragStop && dragStop(cancel || !this.over);
        this.__customTglEff(false);
        em.trigger('canvas:dragend', ev);
    };
    Droppable.prototype.handleDragLeave = function (ev) {
        this.updateCounter(-1, ev);
    };
    Droppable.prototype.updateCounter = function (value, ev) {
        this.counter += value;
        this.counter === 0 && this.endDrop(true, ev);
    };
    Droppable.prototype.handleDragEnter = function (ev) {
        var _this = this;
        var _a = this, em = _a.em, canvas = _a.canvas;
        var dt = ev.dataTransfer;
        var dragContentOrigin = em.get('dragContent');
        if (!dragContentOrigin && !canvas.getConfig().allowExternalDrop) {
            return;
        }
        this.updateCounter(1, ev);
        if (this.over)
            return;
        this.over = true;
        var utils = em.Utils;
        // For security reason I can't read the drag data on dragenter, but
        // as I need it for the Sorter context I will use `dragContent` or just
        // any not empty element
        var content = dragContentOrigin || '<br>';
        var dragStop;
        var dragContent;
        em.stopDefault();
        // Select the right drag provider
        if (em.inAbsoluteMode()) {
            var wrapper_1 = em.Components.getWrapper();
            var target_1 = wrapper_1.append({})[0];
            var dragger_1 = em.Commands.run('core:component-drag', {
                event: ev,
                guidesInfo: 1,
                center: 1,
                target: target_1,
                onEnd: function (ev, dragger, _a) {
                    var cancelled = _a.cancelled;
                    var comp;
                    if (!cancelled) {
                        comp = wrapper_1.append(content)[0];
                        var canvasOffset = canvas.getOffset();
                        var _b = target_1.getStyle(), top_1 = _b.top, left = _b.left, position = _b.position;
                        var scroll_1 = (0,dom/* getDocumentScroll */.GX)(ev.target);
                        var postLeft = parseInt("".concat(parseFloat(left) + scroll_1.x - canvasOffset.left), 10);
                        var posTop = parseInt("".concat(parseFloat(top_1) + scroll_1.y - canvasOffset.top), 10);
                        comp.addStyle({
                            left: postLeft + 'px',
                            top: posTop + 'px',
                            position: position,
                        });
                    }
                    _this.handleDragEnd(comp, dt);
                    target_1.remove();
                },
            });
            dragStop = function (cancel) { return dragger_1.stop(ev, { cancel: cancel }); };
            dragContent = function (cnt) { return (content = cnt); };
        }
        else {
            var sorter_1 = new utils.Sorter(Droppable_assign({ 
                // @ts-ignore
                em: em, wmargin: 1, nested: 1, canvasRelative: 1, direction: 'a', container: this.el, placer: canvas.getPlacerEl(), containerSel: '*', itemSel: '*', pfx: 'gjs-', onEndMove: function (model) { return _this.handleDragEnd(model, dt); }, document: this.el.ownerDocument }, (this.sortOpts || {})));
            sorter_1.setDropContent(content);
            sorter_1.startSort();
            this.sorter = sorter_1;
            dragStop = function (cancel) {
                cancel && (sorter_1.moved = false);
                sorter_1.endMove();
            };
            dragContent = function (content) { return sorter_1.setDropContent(content); };
        }
        this.dragStop = dragStop;
        this.dragContent = dragContent;
        em.trigger('canvas:dragenter', dt, content);
    };
    Droppable.prototype.handleDragEnd = function (model, dt) {
        var em = this.em;
        this.over = false;
        if (model) {
            em.set('dragResult', model);
            em.trigger('canvas:drop', dt, model);
        }
        em.runDefault({ preserveSelected: 1 });
    };
    /**
     * Always need to have this handler active for enabling the drop
     * @param {Event} ev
     */
    Droppable.prototype.handleDragOver = function (ev) {
        ev.preventDefault();
        this.em.trigger('canvas:dragover', ev);
    };
    /**
     * WARNING: This function might fail to run on drop, for example, when the
     * drop, accidentally, happens on some external element (DOM not inside the iframe)
     */
    Droppable.prototype.handleDrop = function (ev) {
        ev.preventDefault();
        var dragContent = this.dragContent;
        var dt = ev.dataTransfer;
        var content = this.getContentByData(dt).content;
        ev.target.style.border = '';
        content && dragContent && dragContent(content);
        this.endDrop(!content, ev);
    };
    Droppable.prototype.getContentByData = function (dt) {
        var em = this.em;
        var types = dt && dt.types;
        var files = (dt && dt.files) || [];
        var dragContent = em.get('dragContent');
        var content = dt && dt.getData('text');
        if (files.length) {
            content = [];
            for (var i = 0; i < files.length; i++) {
                var file = files[i];
                var type = file.type.split('/')[0];
                if (type == 'image') {
                    content.push({
                        type: type,
                        file: file,
                        attributes: { alt: file.name },
                    });
                }
            }
        }
        else if (dragContent) {
            content = dragContent;
        }
        else if ((0,index_all.indexOf)(types, 'text/html') >= 0) {
            content = dt && dt.getData('text/html').replace(/<\/?meta[^>]*>/g, '');
        }
        else if ((0,index_all.indexOf)(types, 'text/uri-list') >= 0) {
            content = {
                type: 'link',
                attributes: { href: content },
                content: content,
            };
        }
        else if ((0,index_all.indexOf)(types, 'text/json') >= 0) {
            var json = dt && dt.getData('text/json');
            json && (content = JSON.parse(json));
        }
        else if (types.length === 1 && types[0] === 'text/plain') {
            // Avoid dropping non-selectable and non-editable text nodes inside the editor
            content = "<div>".concat(content, "</div>");
        }
        var result = { content: content };
        em.trigger('canvas:dragdata', dt, result);
        return result;
    };
    return Droppable;
}());
/* harmony default export */ const utils_Droppable = (Droppable);

;// CONCATENATED MODULE: ./src/canvas/view/FrameView.ts
var FrameView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var FrameView_assign = (undefined && undefined.__assign) || function () {
    FrameView_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return FrameView_assign.apply(this, arguments);
};
var FrameView_spreadArray = (undefined && undefined.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};







var FrameView = /** @class */ (function (_super) {
    FrameView_extends(FrameView, _super);
    function FrameView(model, view) {
        var _this = _super.call(this, { model: model }) || this;
        _this.dragging = false;
        _this.loaded = false;
        _this.lastMaxHeight = 0;
        _this.tools = {};
        (0,index_all.bindAll)(_this, 'updateClientY', 'stopAutoscroll', 'autoscroll', '_emitUpdate');
        var el = _this.el;
        //@ts-ignore
        _this.module._config = FrameView_assign(FrameView_assign({}, (_this.config || {})), { 
            //@ts-ignore
            frameView: _this });
        _this.frameWrapView = view;
        _this.showGlobalTools = (0,index_all.debounce)(_this.showGlobalTools.bind(_this), 50);
        var cvModel = _this.getCanvasModel();
        _this.listenTo(model, 'change:head', _this.updateHead);
        _this.listenTo(cvModel, 'change:styles', _this.renderStyles);
        model.view = _this;
        (0,mixins.setViewEl)(el, _this);
        return _this;
    }
    Object.defineProperty(FrameView.prototype, "tagName", {
        /** @ts-ignore */
        get: function () {
            return 'iframe';
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(FrameView.prototype, "attributes", {
        /** @ts-ignore */
        get: function () {
            return { allowfullscreen: 'allowfullscreen' };
        },
        enumerable: false,
        configurable: true
    });
    FrameView.prototype.getBoxRect = function () {
        var _a = this, el = _a.el, module = _a.module;
        var canvasView = module.getCanvasView();
        var coords = module.getCoords();
        var frameRect = el.getBoundingClientRect();
        var canvasRect = canvasView.getCanvasOffset();
        var vwDelta = canvasView.getViewportDelta();
        var zoomM = module.getZoomMultiplier();
        var x = (frameRect.x - canvasRect.left - vwDelta.x - coords.x) * zoomM;
        var y = (frameRect.y - canvasRect.top - vwDelta.y - coords.y) * zoomM;
        var width = frameRect.width * zoomM;
        var height = frameRect.height * zoomM;
        return {
            x: x,
            y: y,
            width: width,
            height: height,
        };
    };
    /**
     * Update `<head>` content of the frame
     */
    FrameView.prototype.updateHead = function () {
        var model = this.model;
        var headEl = this.getHead();
        var toRemove = [];
        var toAdd = [];
        var current = model.head;
        var prev = model.previous('head');
        var attrStr = function (attr) {
            if (attr === void 0) { attr = {}; }
            return Object.keys(attr)
                .sort()
                .map(function (i) { return "[".concat(i, "=\"").concat(attr[i], "\"]"); })
                .join('');
        };
        var find = function (items, stack, res) {
            items.forEach(function (item) {
                var tag = item.tag, attributes = item.attributes;
                var has = stack.some(function (s) { return s.tag === tag && attrStr(s.attributes) === attrStr(attributes); });
                !has && res.push(item);
            });
        };
        find(current, prev, toAdd);
        find(prev, current, toRemove);
        toRemove.forEach(function (stl) {
            var _a;
            var el = headEl.querySelector("".concat(stl.tag).concat(attrStr(stl.attributes)));
            (_a = el === null || el === void 0 ? void 0 : el.parentNode) === null || _a === void 0 ? void 0 : _a.removeChild(el);
        });
        (0,dom/* appendVNodes */.SJ)(headEl, toAdd);
    };
    FrameView.prototype.getEl = function () {
        return this.el;
    };
    FrameView.prototype.getCanvasModel = function () {
        return this.em.Canvas.getModel();
    };
    FrameView.prototype.getWindow = function () {
        return this.getEl().contentWindow;
    };
    FrameView.prototype.getDoc = function () {
        return this.getEl().contentDocument;
    };
    FrameView.prototype.getHead = function () {
        return this.getDoc().querySelector('head');
    };
    FrameView.prototype.getBody = function () {
        return this.getDoc().querySelector('body');
    };
    FrameView.prototype.getWrapper = function () {
        return this.getBody().querySelector('[data-gjs-type=wrapper]');
    };
    FrameView.prototype.getJsContainer = function () {
        if (!this.jsContainer) {
            this.jsContainer = (0,dom/* createEl */.ut)('div', { class: "".concat(this.ppfx, "js-cont") });
        }
        return this.jsContainer;
    };
    FrameView.prototype.getToolsEl = function () {
        var _a;
        return (_a = this.frameWrapView) === null || _a === void 0 ? void 0 : _a.elTools;
    };
    FrameView.prototype.getGlobalToolsEl = function () {
        return this.em.Canvas.getGlobalToolsEl();
    };
    FrameView.prototype.getHighlighter = function () {
        return this._getTool('[data-hl]');
    };
    FrameView.prototype.getBadgeEl = function () {
        return this._getTool('[data-badge]');
    };
    FrameView.prototype.getOffsetViewerEl = function () {
        return this._getTool('[data-offset]');
    };
    FrameView.prototype.getRect = function () {
        if (!this.rect) {
            this.rect = this.el.getBoundingClientRect();
        }
        return this.rect;
    };
    /**
     * Get rect data, not affected by the canvas zoom
     */
    FrameView.prototype.getOffsetRect = function () {
        var el = this.el;
        var _a = this.getBody(), scrollTop = _a.scrollTop, scrollLeft = _a.scrollLeft;
        var height = el.offsetHeight;
        var width = el.offsetWidth;
        return {
            top: el.offsetTop,
            left: el.offsetLeft,
            height: height,
            width: width,
            scrollTop: scrollTop,
            scrollLeft: scrollLeft,
            scrollBottom: scrollTop + height,
            scrollRight: scrollLeft + width,
        };
    };
    FrameView.prototype._getTool = function (name) {
        var tools = this.tools;
        var toolsEl = this.getToolsEl();
        if (!tools[name]) {
            tools[name] = toolsEl.querySelector(name);
        }
        return tools[name];
    };
    FrameView.prototype.remove = function () {
        var _a;
        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            args[_i] = arguments[_i];
        }
        this._toggleEffects(false);
        this.tools = {};
        (_a = this.wrapper) === null || _a === void 0 ? void 0 : _a.remove();
        abstract_ModuleView.prototype.remove.apply(this, args);
        return this;
    };
    FrameView.prototype.startAutoscroll = function () {
        var _this = this;
        this.lastMaxHeight = this.getWrapper().offsetHeight - this.el.offsetHeight;
        // By detaching those from the stack avoid browsers lags
        // Noticeable with "fast" drag of blocks
        setTimeout(function () {
            _this._toggleAutoscrollFx(true);
            requestAnimationFrame(_this.autoscroll);
        }, 0);
    };
    FrameView.prototype.autoscroll = function () {
        if (this.dragging) {
            var lastClientY = this.lastClientY;
            var canvas = this.em.Canvas;
            var win = this.getWindow();
            var actualTop = win.pageYOffset;
            var clientY = lastClientY || 0;
            var limitTop = canvas.getConfig().autoscrollLimit;
            var limitBottom = this.getRect().height - limitTop;
            var nextTop = actualTop;
            if (clientY < limitTop) {
                nextTop -= limitTop - clientY;
            }
            if (clientY > limitBottom) {
                nextTop += clientY - limitBottom;
            }
            if (!(0,index_all.isUndefined)(lastClientY) && // Fixes #3134
                nextTop !== actualTop &&
                nextTop > 0 &&
                nextTop < this.lastMaxHeight) {
                var toolsEl = this.getGlobalToolsEl();
                toolsEl.style.opacity = '0';
                this.showGlobalTools();
                win.scrollTo(0, nextTop);
                canvas.spots.refreshDbn();
            }
            requestAnimationFrame(this.autoscroll);
        }
    };
    FrameView.prototype.updateClientY = function (ev) {
        ev.preventDefault();
        this.lastClientY = (0,dom/* getPointerEvent */.VB)(ev).clientY * this.em.getZoomDecimal();
    };
    FrameView.prototype.showGlobalTools = function () {
        this.getGlobalToolsEl().style.opacity = '';
    };
    FrameView.prototype.stopAutoscroll = function () {
        this.dragging && this._toggleAutoscrollFx(false);
    };
    FrameView.prototype._toggleAutoscrollFx = function (enable) {
        this.dragging = enable;
        var win = this.getWindow();
        var method = enable ? 'on' : 'off';
        var mt = { on: dom.on, off: dom/* off */.S1 };
        mt[method](win, 'mousemove dragover', this.updateClientY);
        mt[method](win, 'mouseup', this.stopAutoscroll);
    };
    FrameView.prototype.render = function () {
        var _a = this, $el = _a.$el, ppfx = _a.ppfx, em = _a.em;
        $el.attr({ class: "".concat(ppfx, "frame") });
        this.renderScripts();
        em.trigger('frame:render', this); // deprecated
        return this;
    };
    FrameView.prototype.renderScripts = function () {
        var _this = this;
        var _a = this, el = _a.el, model = _a.model, em = _a.em;
        var evLoad = 'frame:load';
        var evOpts = { el: el, model: model, view: this };
        var canvas = this.getCanvasModel();
        var appendScript = function (scripts) {
            var _a;
            if (scripts.length > 0) {
                var src = scripts.shift();
                var scriptEl = (0,dom/* createEl */.ut)('script', FrameView_assign({ type: 'text/javascript' }, ((0,index_all.isString)(src) ? { src: src } : src)));
                (_a = el.contentDocument) === null || _a === void 0 ? void 0 : _a.head.appendChild(scriptEl);
                if (scriptEl.hasAttribute('nomodule') && 'noModule' in HTMLScriptElement.prototype) {
                    appendScript(scripts);
                }
                else {
                    scriptEl.onerror = scriptEl.onload = appendScript.bind(null, scripts);
                }
            }
            else {
                em === null || em === void 0 ? void 0 : em.trigger(canvas_types.frameLoadHead, evOpts);
                _this.renderBody();
                em === null || em === void 0 ? void 0 : em.trigger(canvas_types.frameLoadBody, evOpts);
                em === null || em === void 0 ? void 0 : em.trigger(evLoad, evOpts); // deprecated
            }
        };
        el.onload = function () {
            var frameContent = _this.config.frameContent;
            if (frameContent) {
                var doc = _this.getDoc();
                doc.open();
                doc.write(frameContent);
                doc.close();
            }
            evOpts.window = _this.getWindow();
            em === null || em === void 0 ? void 0 : em.trigger("".concat(evLoad, ":before"), evOpts); // deprecated
            em === null || em === void 0 ? void 0 : em.trigger(canvas_types.frameLoad, evOpts);
            appendScript(FrameView_spreadArray([], canvas.get('scripts'), true));
        };
    };
    FrameView.prototype.renderStyles = function (opts) {
        if (opts === void 0) { opts = {}; }
        var head = this.getHead();
        var canvas = this.getCanvasModel();
        var normalize = function (stls) {
            return stls.map(function (href) { return ({
                tag: 'link',
                attributes: FrameView_assign({ rel: 'stylesheet' }, ((0,index_all.isString)(href) ? { href: href } : href)),
            }); });
        };
        var prevStyles = normalize(opts.prev || canvas.previous('styles'));
        var styles = normalize(canvas.get('styles'));
        var toRemove = [];
        var toAdd = [];
        var find = function (items, stack, res) {
            items.forEach(function (item) {
                var href = item.attributes.href;
                var has = stack.some(function (s) { return s.attributes.href === href; });
                !has && res.push(item);
            });
        };
        find(styles, prevStyles, toAdd);
        find(prevStyles, styles, toRemove);
        toRemove.forEach(function (stl) {
            var _a;
            var el = head.querySelector("link[href=\"".concat(stl.attributes.href, "\"]"));
            (_a = el === null || el === void 0 ? void 0 : el.parentNode) === null || _a === void 0 ? void 0 : _a.removeChild(el);
        });
        (0,dom/* appendVNodes */.SJ)(head, toAdd);
    };
    FrameView.prototype.renderBody = function () {
        var _this = this;
        var _a, _b;
        var _c = this, config = _c.config, em = _c.em, model = _c.model, ppfx = _c.ppfx;
        var doc = this.getDoc();
        var body = this.getBody();
        var win = this.getWindow();
        var hasAutoHeight = model.hasAutoHeight();
        var conf = em.config;
        //@ts-ignore This could be used inside component-related scripts to check if the
        // script is executed inside the editor.
        win._isEditor = true;
        this.renderStyles({ prev: [] });
        var colorWarn = '#ffca6f';
        (0,dom/* append */.R3)(body, "<style>\n      ".concat(conf.baseCss || config.frameStyle || '', "\n\n      ").concat(hasAutoHeight ? 'body { overflow: hidden }' : '', "\n\n      [data-gjs-type=\"wrapper\"] {\n        ").concat(!hasAutoHeight ? 'min-height: 100vh;' : '', "\n        padding-top: 0.001em;\n      }\n\n      .").concat(ppfx, "dashed *[data-gjs-highlightable] {\n        outline: 1px dashed rgba(170,170,170,0.7);\n        outline-offset: -2px;\n      }\n\n      .").concat(ppfx, "selected {\n        outline: 2px solid #3b97e3 !important;\n        outline-offset: -2px;\n      }\n\n      .").concat(ppfx, "selected-parent {\n        outline: 2px solid ").concat(colorWarn, " !important\n      }\n\n      .").concat(ppfx, "no-select {\n        user-select: none;\n        -webkit-user-select:none;\n        -moz-user-select: none;\n      }\n\n      .").concat(ppfx, "freezed {\n        opacity: 0.5;\n        pointer-events: none;\n      }\n\n      .").concat(ppfx, "no-pointer {\n        pointer-events: none;\n      }\n\n      .").concat(ppfx, "pointer-init {\n        pointer-events: initial;\n      }\n\n      .").concat(ppfx, "plh-image {\n        background: #f5f5f5;\n        border: none;\n        height: 100px;\n        width: 100px;\n        display: block;\n        outline: 3px solid #ffca6f;\n        cursor: pointer;\n        outline-offset: -2px\n      }\n\n      .").concat(ppfx, "grabbing {\n        cursor: grabbing;\n        cursor: -webkit-grabbing;\n      }\n\n      .").concat(ppfx, "is__grabbing {\n        overflow-x: hidden;\n      }\n\n      .").concat(ppfx, "is__grabbing,\n      .").concat(ppfx, "is__grabbing * {\n        cursor: grabbing !important;\n      }\n\n      ").concat(conf.canvasCss || '', "\n      ").concat(conf.protectedCss || '', "\n    </style>"));
        var root = model.root;
        var view = em.Components.getType('wrapper').view;
        this.wrapper = new view({
            model: root,
            config: FrameView_assign(FrameView_assign({}, root.config), { em: em, frameView: this }),
        }).render();
        (0,dom/* append */.R3)(body, (_a = this.wrapper) === null || _a === void 0 ? void 0 : _a.el);
        (0,dom/* append */.R3)(body, new view_CssRulesView({
            collection: model.getStyles(),
            //@ts-ignore
            config: FrameView_assign(FrameView_assign({}, em.Css.getConfig()), { frameView: this }),
        }).render().el);
        (0,dom/* append */.R3)(body, this.getJsContainer());
        // em.trigger('loaded'); // I need to manage only the first one maybe
        //this.updateOffset(); // TOFIX (check if I need it)
        // Avoid some default behaviours
        //@ts-ignore
        (0,dom.on)(body, 'click', function (ev) { var _a; return ev && ((_a = ev.target) === null || _a === void 0 ? void 0 : _a.tagName) == 'A' && ev.preventDefault(); });
        (0,dom.on)(body, 'submit', function (ev) { return ev && ev.preventDefault(); });
        // When the iframe is focused the event dispatcher is not the same so
        // I need to delegate all events to the parent document
        [
            { event: 'keydown keyup keypress', class: 'KeyboardEvent' },
            { event: 'mousedown mousemove mouseup', class: 'MouseEvent' },
            { event: 'pointerdown pointermove pointerup', class: 'PointerEvent' },
            { event: 'wheel', class: 'WheelEvent', opts: { passive: !config.infiniteCanvas } },
        ].forEach(function (obj) {
            return obj.event.split(' ').forEach(function (event) {
                doc.addEventListener(event, function (ev) { return _this.el.dispatchEvent((0,dom/* createCustomEvent */.t3)(ev, obj.class)); }, obj.opts);
            });
        });
        this._toggleEffects(true);
        if ((0,mixins.hasDnd)(em)) {
            this.droppable = new utils_Droppable(em, (_b = this.wrapper) === null || _b === void 0 ? void 0 : _b.el);
        }
        this.loaded = true;
        model.trigger('loaded');
    };
    FrameView.prototype._toggleEffects = function (enable) {
        var method = enable ? dom.on : dom/* off */.S1;
        var win = this.getWindow();
        win && method(win, "".concat(dom/* motionsEv */.G1, " resize"), this._emitUpdate);
    };
    FrameView.prototype._emitUpdate = function () {
        this.model._emitUpdated();
    };
    return FrameView;
}(abstract_ModuleView));
/* harmony default export */ const view_FrameView = (FrameView);

// EXTERNAL MODULE: ./src/utils/Dragger.ts
var Dragger = __webpack_require__(668);
;// CONCATENATED MODULE: ./src/canvas/view/FrameWrapView.ts
var FrameWrapView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var FrameWrapView_assign = (undefined && undefined.__assign) || function () {
    FrameWrapView_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return FrameWrapView_assign.apply(this, arguments);
};





var FrameWrapView = /** @class */ (function (_super) {
    FrameWrapView_extends(FrameWrapView, _super);
    function FrameWrapView(model, canvasView) {
        var _this = _super.call(this, { model: model }) || this;
        (0,index_all.bindAll)(_this, 'onScroll', 'frameLoaded', 'updateOffset', 'remove', 'startDrag');
        var config = FrameWrapView_assign(FrameWrapView_assign({}, model.config), { frameWrapView: _this });
        _this.cv = canvasView;
        _this.frame = new view_FrameView(model, _this);
        _this.classAnim = "".concat(_this.ppfx, "frame-wrapper--anim");
        _this.updateOffset = (0,index_all.debounce)(_this.updateOffset.bind(_this), 0);
        _this.updateSize = (0,index_all.debounce)(_this.updateSize.bind(_this), 0);
        _this.listenTo(model, 'loaded', _this.frameLoaded);
        _this.listenTo(model, 'change:x change:y', _this.updatePos);
        _this.listenTo(model, 'change:width change:height', _this.updateSize);
        _this.listenTo(model, 'destroy remove', _this.remove);
        _this.updatePos();
        _this.setupDragger();
        return _this;
    }
    FrameWrapView.prototype.events = function () {
        return {
            'click [data-action-remove]': 'remove',
            'mousedown [data-action-move]': 'startDrag',
        };
    };
    FrameWrapView.prototype.setupDragger = function () {
        var _this = this;
        var _a = this, module = _a.module, model = _a.model;
        var dragX, dragY, zoom;
        var toggleEffects = function (on) {
            module.toggleFramesEvents(on);
        };
        this.dragger = new Dragger/* default */.Z({
            onStart: function () {
                var _a = model.attributes, x = _a.x, y = _a.y;
                zoom = _this.em.getZoomMultiplier();
                dragX = x;
                dragY = y;
                toggleEffects(false);
            },
            onEnd: function () { return toggleEffects(true); },
            setPosition: function (posOpts) {
                model.set({
                    x: dragX + posOpts.x * zoom,
                    y: dragY + posOpts.y * zoom,
                });
            },
        });
    };
    FrameWrapView.prototype.startDrag = function (ev) {
        var _a;
        ev && ((_a = this.dragger) === null || _a === void 0 ? void 0 : _a.start(ev));
    };
    FrameWrapView.prototype.__clear = function (opts) {
        var frame = this.frame;
        frame && frame.remove(opts);
        (0,dom/* removeEl */.L_)(this.elTools);
    };
    FrameWrapView.prototype.remove = function (opts) {
        var _this = this;
        this.__clear(opts);
        abstract_ModuleView.prototype.remove.apply(this, opts);
        //@ts-ignore
        ['frame', 'dragger', 'cv', 'elTools'].forEach(function (i) { return (_this[i] = 0); });
        return this;
    };
    FrameWrapView.prototype.updateOffset = function () {
        var _a;
        var _b = this, em = _b.em, $el = _b.$el, frame = _b.frame;
        if (!em || em.destroyed)
            return;
        em.runDefault({ preserveSelected: 1 });
        $el.removeClass(this.classAnim);
        (_a = frame === null || frame === void 0 ? void 0 : frame.model) === null || _a === void 0 ? void 0 : _a._emitUpdated();
    };
    FrameWrapView.prototype.updatePos = function (md) {
        var _a = this, model = _a.model, el = _a.el;
        var _b = model.attributes, x = _b.x, y = _b.y;
        var style = el.style;
        this.frame.rect = undefined;
        style.left = isNaN(x) ? x : "".concat(x, "px");
        style.top = isNaN(y) ? y : "".concat(y, "px");
        md && this.updateOffset();
    };
    FrameWrapView.prototype.updateSize = function () {
        this.updateDim();
    };
    /**
     * Update dimensions of the frame
     * @private
     */
    FrameWrapView.prototype.updateDim = function () {
        var _a = this, em = _a.em, el = _a.el, $el = _a.$el, model = _a.model, classAnim = _a.classAnim, frame = _a.frame;
        if (!frame)
            return;
        frame.rect = undefined;
        $el.addClass(classAnim);
        var _b = this.__handleSize(), noChanges = _b.noChanges, width = _b.width, height = _b.height;
        // Set width and height from DOM (should be done only once)
        if ((0,index_all.isNull)(width) || (0,index_all.isNull)(height)) {
            model.set(FrameWrapView_assign(FrameWrapView_assign({}, (!width ? { width: el.offsetWidth } : {})), (!height ? { height: el.offsetHeight } : {})), { silent: 1 });
        }
        // Prevent fixed highlighting box which appears when on
        // component hover during the animation
        em.stopDefault({ preserveSelected: 1 });
        noChanges ? this.updateOffset() : setTimeout(this.updateOffset, 350);
    };
    FrameWrapView.prototype.onScroll = function () {
        var _a = this, frame = _a.frame, em = _a.em;
        em.trigger('frame:scroll', {
            frame: frame,
            body: frame.getBody(),
            target: frame.getWindow(),
        });
    };
    FrameWrapView.prototype.frameLoaded = function () {
        var _a = this, frame = _a.frame, config = _a.config;
        frame.getWindow().onscroll = this.onScroll;
        this.updateDim();
    };
    FrameWrapView.prototype.__handleSize = function () {
        var _a, _b;
        var un = 'px';
        var _c = this, model = _c.model, el = _c.el;
        var style = el.style;
        var _d = model.attributes, width = _d.width, height = _d.height;
        var currW = style.width || '';
        var currH = style.height || '';
        var newW = width || '';
        var newH = height || '';
        var noChanges = currW == newW && currH == newH;
        var newWidth = (0,index_all.isNumber)(newW) ? "".concat(newW).concat(un) : newW;
        var newHeight = (0,index_all.isNumber)(newH) ? "".concat(newH).concat(un) : newH;
        style.width = newWidth;
        if (model.hasAutoHeight()) {
            var iframe = this.frame.el;
            if (iframe.contentDocument
            // this doesn't work always
            // && !this.sizeObserver
            ) {
                var contentDocument_1 = iframe.contentDocument;
                var observer = new ResizeObserver(function () {
                    style.height = "".concat(contentDocument_1.body.scrollHeight, "px");
                });
                observer.observe(contentDocument_1.body);
                (_a = this.sizeObserver) === null || _a === void 0 ? void 0 : _a.disconnect();
                this.sizeObserver = observer;
            }
        }
        else {
            style.height = newHeight;
            (_b = this.sizeObserver) === null || _b === void 0 ? void 0 : _b.disconnect();
            delete this.sizeObserver;
        }
        return { noChanges: noChanges, width: width, height: height, newW: newW, newH: newH };
    };
    FrameWrapView.prototype.render = function () {
        var _a = this, frame = _a.frame, $el = _a.$el, ppfx = _a.ppfx, cv = _a.cv, model = _a.model, el = _a.el;
        var onRender = model.attributes.onRender;
        this.__clear();
        this.__handleSize();
        frame.render();
        $el
            .empty()
            .attr({ class: "".concat(ppfx, "frame-wrapper") })
            .append("\n      <div class=\"".concat(ppfx, "frame-wrapper__top gjs-two-color\" data-frame-top>\n        <div class=\"").concat(ppfx, "frame-wrapper__name\" data-action-move>\n          ").concat(model.get('name') || '', "\n        </div>\n        <div class=\"").concat(ppfx, "frame-wrapper__top-r\">\n          <div class=\"").concat(ppfx, "frame-wrapper__icon\" data-action-remove style=\"display: none\">\n            <svg viewBox=\"0 0 24 24\"><path d=\"M19 4h-3.5l-1-1h-5l-1 1H5v2h14M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12z\"></path></svg>\n          </div>\n        </div>\n      </div>\n      <div class=\"").concat(ppfx, "frame-wrapper__right\" data-frame-right></div>\n      <div class=\"").concat(ppfx, "frame-wrapper__left\" data-frame-left></div>\n      <div class=\"").concat(ppfx, "frame-wrapper__bottom\" data-frame-bottom></div>\n      "))
            .append(frame.el);
        var elTools = (0,dom/* createEl */.ut)('div', {
            class: "".concat(ppfx, "tools"),
            style: 'pointer-events:none; display: none',
        }, "\n      <div class=\"".concat(ppfx, "highlighter\" data-hl></div>\n      <div class=\"").concat(ppfx, "badge\" data-badge></div>\n      <div class=\"").concat(ppfx, "placeholder\">\n        <div class=\"").concat(ppfx, "placeholder-int\"></div>\n      </div>\n      <div class=\"").concat(ppfx, "ghost\"></div>\n      <div class=\"").concat(ppfx, "toolbar\" style=\"pointer-events:all\"></div>\n      <div class=\"").concat(ppfx, "resizer\"></div>\n      <div class=\"").concat(ppfx, "offset-v\" data-offset>\n        <div class=\"gjs-marginName\" data-offset-m>\n          <div class=\"gjs-margin-v-el gjs-margin-v-top\" data-offset-m-t></div>\n          <div class=\"gjs-margin-v-el gjs-margin-v-bottom\" data-offset-m-b></div>\n          <div class=\"gjs-margin-v-el gjs-margin-v-left\" data-offset-m-l></div>\n          <div class=\"gjs-margin-v-el gjs-margin-v-right\" data-offset-m-r></div>\n        </div>\n        <div class=\"gjs-paddingName\" data-offset-m>\n          <div class=\"gjs-padding-v-el gjs-padding-v-top\" data-offset-p-t></div>\n          <div class=\"gjs-padding-v-el gjs-padding-v-bottom\" data-offset-p-b></div>\n          <div class=\"gjs-padding-v-el gjs-padding-v-left\" data-offset-p-l></div>\n          <div class=\"gjs-padding-v-el gjs-padding-v-right\" data-offset-p-r></div>\n        </div>\n      </div>\n      <div class=\"").concat(ppfx, "offset-fixed-v\"></div>\n    "));
        this.elTools = elTools;
        var twrp = cv === null || cv === void 0 ? void 0 : cv.toolsWrapper;
        twrp && twrp.appendChild(elTools); // TODO remove on frame remove
        onRender &&
            onRender({
                el: el,
                elTop: el.querySelector('[data-frame-top]'),
                elRight: el.querySelector('[data-frame-right]'),
                elBottom: el.querySelector('[data-frame-bottom]'),
                elLeft: el.querySelector('[data-frame-left]'),
                frame: model,
                frameWrapperView: this,
                remove: this.remove,
                startDrag: this.startDrag,
            });
        return this;
    };
    return FrameWrapView;
}(abstract_ModuleView));
/* harmony default export */ const view_FrameWrapView = (FrameWrapView);

;// CONCATENATED MODULE: ./src/canvas/view/FramesView.ts
var FramesView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();


var FramesView = /** @class */ (function (_super) {
    FramesView_extends(FramesView, _super);
    function FramesView(opts, config) {
        if (opts === void 0) { opts = {}; }
        var _this = _super.call(this, opts, true) || this;
        _this.listenTo(_this.collection, 'reset', _this.render);
        _this.canvasView = config.canvasView;
        _this._module = config.module;
        return _this;
    }
    FramesView.prototype.onRemoveBefore = function (items, opts) {
        if (opts === void 0) { opts = {}; }
        items.forEach(function (item) { return item.remove(opts); });
    };
    FramesView.prototype.onRender = function () {
        var _a = this, $el = _a.$el, ppfx = _a.ppfx;
        $el.attr({ class: "".concat(ppfx, "frames") });
    };
    FramesView.prototype.clearItems = function () {
        var items = this.viewCollection || [];
        items.forEach(function (item) { return item.remove(); });
        this.viewCollection = [];
    };
    FramesView.prototype.renderView = function (item, type) {
        return new view_FrameWrapView(item, this.canvasView);
    };
    return FramesView;
}(abstract_ModuleDomainViews));
/* harmony default export */ const view_FramesView = (FramesView);

;// CONCATENATED MODULE: ./src/canvas/view/CanvasView.ts
var CanvasView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var CanvasView_assign = (undefined && undefined.__assign) || function () {
    CanvasView_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return CanvasView_assign.apply(this, arguments);
};






var CanvasView = /** @class */ (function (_super) {
    CanvasView_extends(CanvasView, _super);
    function CanvasView(model) {
        var _this = _super.call(this, { model: model }) || this;
        _this.ready = false;
        (0,index_all.bindAll)(_this, 'clearOff', 'onKeyPress', 'onWheel', 'onPointer');
        var _a = _this, em = _a.em, pfx = _a.pfx, ppfx = _a.ppfx;
        var events = _this.module.events;
        _this.className = "".concat(pfx, "canvas ").concat(ppfx, "no-touch-actions").concat(!em.config.customUI ? " ".concat(pfx, "canvas-bg") : '');
        _this.clsUnscale = "".concat(pfx, "unscale");
        _this._initFrames();
        _this.listenTo(em, events.refresh, _this.clearOff);
        _this.listenTo(em, 'component:selected', _this.checkSelected);
        _this.listenTo(em, "".concat(events.coords, " ").concat(events.zoom), _this.updateFrames);
        _this.listenTo(model, 'change:frames', _this._onFramesUpdate);
        _this.toggleListeners(true);
        return _this;
    }
    CanvasView.prototype.template = function () {
        var pfx = this.pfx;
        return "\n      <div class=\"".concat(pfx, "canvas__frames\" data-frames>\n        <div class=\"").concat(pfx, "canvas__spots\" data-spots></div>\n      </div>\n      <div id=\"").concat(pfx, "tools\" class=\"").concat(pfx, "canvas__tools\" data-tools></div>\n      <style data-canvas-style></style>\n    ");
    };
    CanvasView.prototype._onFramesUpdate = function () {
        this._initFrames();
        this._renderFrames();
    };
    CanvasView.prototype._initFrames = function () {
        var _a = this, frames = _a.frames, model = _a.model, config = _a.config, em = _a.em;
        var collection = model.frames;
        em.set('readyCanvas', 0);
        collection.once('loaded:all', function () { return em.set('readyCanvas', 1); });
        frames === null || frames === void 0 ? void 0 : frames.remove();
        this.frames = new view_FramesView({ collection: collection }, CanvasView_assign(CanvasView_assign({}, config), { canvasView: this }));
    };
    CanvasView.prototype.checkSelected = function (component, opts) {
        var _a;
        if (opts === void 0) { opts = {}; }
        var scroll = opts.scroll;
        var currFrame = this.em.getCurrentFrame();
        scroll &&
            ((_a = component.views) === null || _a === void 0 ? void 0 : _a.forEach(function (view) {
                view.frameView === currFrame && view.scrollIntoView(scroll);
            }));
    };
    CanvasView.prototype.remove = function () {
        var _a;
        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            args[_i] = arguments[_i];
        }
        (_a = this.frames) === null || _a === void 0 ? void 0 : _a.remove();
        //@ts-ignore
        this.frames = undefined;
        abstract_ModuleView.prototype.remove.apply(this, args);
        this.toggleListeners(false);
        return this;
    };
    CanvasView.prototype.preventDefault = function (ev) {
        var _a;
        if (ev) {
            ev.preventDefault();
            (_a = ev._parentEvent) === null || _a === void 0 ? void 0 : _a.preventDefault();
        }
    };
    CanvasView.prototype.toggleListeners = function (enable) {
        var _a = this, el = _a.el, config = _a.config;
        var fn = enable ? dom.on : dom/* off */.S1;
        fn(document, 'keypress', this.onKeyPress);
        fn(window, 'scroll resize', this.clearOff);
        fn(el, 'wheel', this.onWheel, { passive: !config.infiniteCanvas });
        fn(el, 'pointermove', this.onPointer);
    };
    CanvasView.prototype.screenToWorld = function (x, y) {
        var module = this.module;
        var coords = module.getCoords();
        var zoom = module.getZoomMultiplier();
        var vwDelta = this.getViewportDelta();
        return {
            x: (x - coords.x - vwDelta.x) * zoom,
            y: (y - coords.y - vwDelta.y) * zoom,
        };
    };
    CanvasView.prototype.onPointer = function (ev) {
        if (!this.config.infiniteCanvas)
            return;
        var canvasRect = this.getCanvasOffset();
        var docScroll = (0,dom/* getDocumentScroll */.GX)();
        var screenCoords = {
            x: ev.clientX - canvasRect.left + docScroll.x,
            y: ev.clientY - canvasRect.top + docScroll.y,
        };
        if (ev._parentEvent) {
            // with _parentEvent means was triggered from the iframe
            var frameRect = ev.target.getBoundingClientRect();
            var zoom = this.module.getZoomDecimal();
            screenCoords.x = frameRect.left - canvasRect.left + docScroll.x + ev.clientX * zoom;
            screenCoords.y = frameRect.top - canvasRect.top + docScroll.y + ev.clientY * zoom;
        }
        this.model.set({
            pointerScreen: screenCoords,
            pointer: this.screenToWorld(screenCoords.x, screenCoords.y),
        });
    };
    CanvasView.prototype.onKeyPress = function (ev) {
        var em = this.em;
        var key = (0,dom/* getKeyChar */.sN)(ev);
        if (key === ' ' && em.getZoomDecimal() !== 1 && !em.Canvas.isInputFocused()) {
            this.preventDefault(ev);
            em.Editor.runCommand('core:canvas-move');
        }
    };
    CanvasView.prototype.onWheel = function (ev) {
        var _a = this, module = _a.module, config = _a.config;
        if (config.infiniteCanvas) {
            this.preventDefault(ev);
            var deltaX = ev.deltaX, deltaY = ev.deltaY;
            var zoom = module.getZoomDecimal();
            var isZooming = (0,dom/* hasModifierKey */.Vb)(ev);
            var coords = module.getCoords();
            if (isZooming) {
                var newZoom = zoom - deltaY * zoom * 0.01;
                module.setZoom(newZoom * 100);
                // Update coordinates based on pointer
                var pointer = this.model.getPointerCoords(common/* CoordinatesTypes */.vA.Screen);
                var canvasRect = this.getCanvasOffset();
                var pointerX = pointer.x - canvasRect.width / 2;
                var pointerY = pointer.y - canvasRect.height / 2;
                var zoomDelta = newZoom / zoom;
                var x = pointerX - (pointerX - coords.x) * zoomDelta;
                var y = pointerY - (pointerY - coords.y) * zoomDelta;
                module.setCoords(x, y);
            }
            else {
                this.onPointer(ev);
                module.setCoords(coords.x - deltaX, coords.y - deltaY);
            }
        }
    };
    CanvasView.prototype.updateFrames = function (ev) {
        var em = this.em;
        var toolsWrpEl = this.toolsWrapper;
        var defOpts = { preserveSelected: 1 };
        this.updateFramesArea();
        this.clearOff();
        toolsWrpEl.style.display = 'none';
        em.trigger('canvas:update', ev);
        this.timerZoom && clearTimeout(this.timerZoom);
        this.timerZoom = setTimeout(function () {
            em.stopDefault(defOpts);
            em.runDefault(defOpts);
            toolsWrpEl.style.display = '';
        }, 300);
    };
    CanvasView.prototype.updateFramesArea = function () {
        var _a = this, framesArea = _a.framesArea, model = _a.model, module = _a.module, cvStyle = _a.cvStyle, clsUnscale = _a.clsUnscale;
        var mpl = module.getZoomMultiplier();
        if (framesArea) {
            var _b = model.attributes, x = _b.x, y = _b.y;
            var zoomDc = module.getZoomDecimal();
            framesArea.style.transform = "scale(".concat(zoomDc, ") translate(").concat(x * mpl, "px, ").concat(y * mpl, "px)");
        }
        if (cvStyle) {
            cvStyle.innerHTML = "\n        .".concat(clsUnscale, " { scale: ").concat(mpl, " }\n      ");
        }
    };
    CanvasView.prototype.fitViewport = function (opts) {
        var _a, _b;
        if (opts === void 0) { opts = {}; }
        var _c = this, em = _c.em, module = _c.module, model = _c.model;
        var canvasRect = this.getCanvasOffset();
        var el = opts.el;
        var elFrame = el && ((_a = (0,mixins.getComponentView)(el)) === null || _a === void 0 ? void 0 : _a.frameView);
        var frame = elFrame ? elFrame.model : opts.frame || em.getCurrentFrameModel() || model.frames.at(0);
        var _d = frame.attributes, x = _d.x, y = _d.y;
        var boxRect = {
            x: x !== null && x !== void 0 ? x : 0,
            y: y !== null && y !== void 0 ? y : 0,
            width: frame.width,
            height: frame.height,
        };
        if (el) {
            var elRect = this.getElBoxRect(el);
            boxRect.x = boxRect.x + elRect.x;
            boxRect.y = boxRect.y + elRect.y;
            boxRect.width = elRect.width;
            boxRect.height = elRect.height;
        }
        var noHeight = opts.ignoreHeight;
        var gap = (_b = opts.gap) !== null && _b !== void 0 ? _b : 0;
        var gapIsNum = (0,index_all.isNumber)(gap);
        var gapX = gapIsNum ? gap : gap.x;
        var gapY = gapIsNum ? gap : gap.y;
        var boxWidth = boxRect.width + gapX * 2;
        var boxHeight = boxRect.height + gapY * 2;
        var canvasWidth = canvasRect.width;
        var canvasHeight = canvasRect.height;
        var widthRatio = canvasWidth / boxWidth;
        var heightRatio = canvasHeight / boxHeight;
        var zoomRatio = noHeight ? widthRatio : Math.min(widthRatio, heightRatio);
        var zoom = zoomRatio * 100;
        module.setZoom(zoom);
        // check for the frame witdh is necessary as we're centering the frame via CSS
        var coordX = -boxRect.x + (frame.width >= canvasWidth ? canvasWidth / 2 - boxWidth / 2 : -gapX);
        var coordY = -boxRect.y + canvasHeight / 2 - boxHeight / 2;
        var coords = {
            x: (coordX + gapX) * zoomRatio,
            y: (coordY + gapY) * zoomRatio,
        };
        if (noHeight) {
            var zoomMltp = module.getZoomMultiplier();
            var canvasWorldHeight = canvasHeight * zoomMltp;
            var canvasHeightDiff = canvasWorldHeight - canvasHeight;
            var yDelta = canvasHeightDiff / 2;
            coords.y = (-boxRect.y + gapY) * zoomRatio - yDelta / zoomMltp;
        }
        module.setCoords(coords.x, coords.y);
    };
    /**
     * Checks if the element is visible in the canvas's viewport
     * @param  {HTMLElement}  el
     * @return {Boolean}
     */
    CanvasView.prototype.isElInViewport = function (el) {
        var elem = (0,mixins.getElement)(el);
        var rect = (0,dom/* getElRect */.Ut)(elem);
        var frameRect = this.getFrameOffset(elem);
        var rTop = rect.top;
        var rLeft = rect.left;
        return rTop >= 0 && rLeft >= 0 && rTop <= frameRect.height && rLeft <= frameRect.width;
    };
    /**
     * Get the offset of the element
     * @param  {HTMLElement} el
     * @return { {top: number, left: number, width: number, height: number} }
     */
    CanvasView.prototype.offset = function (el, opts) {
        if (opts === void 0) { opts = {}; }
        var noScroll = opts.noScroll;
        var rect = (0,dom/* getElRect */.Ut)(el);
        var scroll = noScroll ? { x: 0, y: 0 } : (0,dom/* getDocumentScroll */.GX)(el);
        return {
            top: rect.top + scroll.y,
            left: rect.left + scroll.x,
            width: rect.width,
            height: rect.height,
        };
    };
    CanvasView.prototype.getRectToScreen = function (boxRect) {
        var _a, _b, _c, _d;
        var zoom = this.module.getZoomDecimal();
        var coords = this.module.getCoords();
        var vwDelta = this.getViewportDelta();
        var x = ((_a = boxRect.x) !== null && _a !== void 0 ? _a : 0) * zoom + coords.x + vwDelta.x || 0;
        var y = ((_b = boxRect.y) !== null && _b !== void 0 ? _b : 0) * zoom + coords.y + vwDelta.y || 0;
        return {
            x: x,
            y: y,
            width: ((_c = boxRect.width) !== null && _c !== void 0 ? _c : 0) * zoom,
            height: ((_d = boxRect.height) !== null && _d !== void 0 ? _d : 0) * zoom,
        };
    };
    CanvasView.prototype.getElBoxRect = function (el, opts) {
        var _a, _b, _c;
        if (opts === void 0) { opts = {}; }
        var module = this.module;
        var _d = (0,dom/* getElRect */.Ut)(el), width = _d.width, height = _d.height, left = _d.left, top = _d.top;
        var frameView = (_a = (0,mixins.getComponentView)(el)) === null || _a === void 0 ? void 0 : _a.frameView;
        var frameRect = frameView === null || frameView === void 0 ? void 0 : frameView.getBoxRect();
        var zoomMlt = module.getZoomMultiplier();
        var frameX = (_b = frameRect === null || frameRect === void 0 ? void 0 : frameRect.x) !== null && _b !== void 0 ? _b : 0;
        var frameY = (_c = frameRect === null || frameRect === void 0 ? void 0 : frameRect.y) !== null && _c !== void 0 ? _c : 0;
        var canvasEl = this.el;
        var docScroll = (0,dom/* getDocumentScroll */.GX)();
        var xWithFrame = left + frameX + (canvasEl.scrollLeft + docScroll.x) * zoomMlt;
        var yWithFrame = top + frameY + (canvasEl.scrollTop + docScroll.y) * zoomMlt;
        var boxRect = {
            x: xWithFrame,
            y: yWithFrame,
            width: width,
            height: height,
        };
        if (opts.local) {
            boxRect.x = left;
            boxRect.y = top;
        }
        return opts.toScreen ? this.getRectToScreen(boxRect) : boxRect;
    };
    CanvasView.prototype.getViewportRect = function (opts) {
        if (opts === void 0) { opts = {}; }
        var _a = this.getCanvasOffset(), top = _a.top, left = _a.left, width = _a.width, height = _a.height;
        var module = this.module;
        if (opts.toWorld) {
            var zoom = module.getZoomMultiplier();
            var coords = module.getCoords();
            var vwDelta = this.getViewportDelta();
            var x = -coords.x - vwDelta.x || 0;
            var y = -coords.y - vwDelta.y || 0;
            return {
                x: x * zoom,
                y: y * zoom,
                width: width * zoom,
                height: height * zoom,
            };
        }
        else {
            return {
                x: left,
                y: top,
                width: width,
                height: height,
            };
        }
    };
    CanvasView.prototype.getViewportDelta = function (opts) {
        if (opts === void 0) { opts = {}; }
        var zoom = this.module.getZoomMultiplier();
        var _a = this.getCanvasOffset(), width = _a.width, height = _a.height;
        var worldWidth = width * zoom;
        var worldHeight = height * zoom;
        var widthDelta = worldWidth - width;
        var heightDelta = worldHeight - height;
        return {
            x: widthDelta / 2 / zoom,
            y: heightDelta / 2 / zoom,
        };
    };
    /**
     * Cleare cached offsets
     * @private
     */
    CanvasView.prototype.clearOff = function () {
        this.frmOff = undefined;
        this.cvsOff = undefined;
    };
    /**
     * Return frame offset
     * @return { {top: number, left: number, width: number, height: number} }
     * @public
     */
    CanvasView.prototype.getFrameOffset = function (el) {
        var _a;
        if (!this.frmOff || el) {
            var frame = (_a = this.frame) === null || _a === void 0 ? void 0 : _a.el;
            var winEl = el === null || el === void 0 ? void 0 : el.ownerDocument.defaultView;
            var frEl = winEl ? winEl.frameElement : frame;
            this.frmOff = this.offset(frEl || frame);
        }
        return this.frmOff;
    };
    /**
     * Return canvas offset
     * @return { {top: number, left: number, width: number, height: number} }
     * @public
     */
    CanvasView.prototype.getCanvasOffset = function () {
        if (!this.cvsOff)
            this.cvsOff = this.offset(this.el);
        return this.cvsOff;
    };
    /**
     * Returns element's rect info
     * @param {HTMLElement} el
     * @param {object} opts
     * @return { {top: number, left: number, width: number, height: number, zoom: number, rect: any} }
     * @public
     */
    CanvasView.prototype.getElementPos = function (el, opts) {
        if (opts === void 0) { opts = {}; }
        var zoom = this.module.getZoomDecimal();
        var frameOffset = this.getFrameOffset(el);
        var canvasEl = this.el;
        var canvasOffset = this.getCanvasOffset();
        var elRect = this.offset(el, opts);
        var frameTop = opts.avoidFrameOffset ? 0 : frameOffset.top;
        var frameLeft = opts.avoidFrameOffset ? 0 : frameOffset.left;
        var elTop = opts.avoidFrameZoom ? elRect.top : elRect.top * zoom;
        var elLeft = opts.avoidFrameZoom ? elRect.left : elRect.left * zoom;
        var top = opts.avoidFrameOffset ? elTop : elTop + frameTop - canvasOffset.top + canvasEl.scrollTop;
        var left = opts.avoidFrameOffset ? elLeft : elLeft + frameLeft - canvasOffset.left + canvasEl.scrollLeft;
        var height = opts.avoidFrameZoom ? elRect.height : elRect.height * zoom;
        var width = opts.avoidFrameZoom ? elRect.width : elRect.width * zoom;
        return { top: top, left: left, height: height, width: width, zoom: zoom, rect: elRect };
    };
    /**
     * Returns element's offsets like margins and paddings
     * @param {HTMLElement} el
     * @return { MarginPaddingOffsets }
     * @public
     */
    CanvasView.prototype.getElementOffsets = function (el) {
        if (!el || (0,dom/* isTextNode */.BM)(el))
            return {};
        var result = {};
        var styles = window.getComputedStyle(el);
        var zoom = this.module.getZoomDecimal();
        var marginPaddingOffsets = [
            'marginTop',
            'marginRight',
            'marginBottom',
            'marginLeft',
            'paddingTop',
            'paddingRight',
            'paddingBottom',
            'paddingLeft',
            'borderTopWidth',
            'borderRightWidth',
            'borderBottomWidth',
            'borderLeftWidth',
        ];
        marginPaddingOffsets.forEach(function (offset) {
            result[offset] = parseFloat(styles[offset]) * zoom;
        });
        return result;
    };
    /**
     * Returns position data of the canvas element
     * @return { {top: number, left: number, width: number, height: number} } obj Position object
     * @public
     */
    CanvasView.prototype.getPosition = function (opts) {
        var _a;
        if (opts === void 0) { opts = {}; }
        var doc = (_a = this.frame) === null || _a === void 0 ? void 0 : _a.el.contentDocument;
        if (!doc) {
            return {
                top: 0,
                left: 0,
                width: 0,
                height: 0,
            };
        }
        var bEl = doc.body;
        var zoom = this.module.getZoomDecimal();
        var fo = this.getFrameOffset();
        var co = this.getCanvasOffset();
        var noScroll = opts.noScroll;
        return {
            top: fo.top + (noScroll ? 0 : bEl.scrollTop) * zoom - co.top,
            left: fo.left + (noScroll ? 0 : bEl.scrollLeft) * zoom - co.left,
            width: co.width,
            height: co.height,
        };
    };
    /**
     * Update javascript of a specific component passed by its View
     * @param {ModuleView} view Component's View
     * @private
     */
    //TODO change type after the ComponentView was updated to ts
    CanvasView.prototype.updateScript = function (view) {
        var model = view.model;
        var id = model.getId();
        if (!view.scriptContainer) {
            view.scriptContainer = (0,dom/* createEl */.ut)('div', { 'data-id': id });
            var jsEl = this.getJsContainer();
            jsEl === null || jsEl === void 0 ? void 0 : jsEl.appendChild(view.scriptContainer);
        }
        view.el.id = id;
        view.scriptContainer.innerHTML = '';
        // In editor, I make use of setTimeout as during the append process of elements
        // those will not be available immediately, therefore 'item' variable
        var script = document.createElement('script');
        var scriptFn = model.getScriptString();
        var scriptFnStr = model.get('script-props') ? scriptFn : "function(){\n".concat(scriptFn, "\n;}");
        var scriptProps = JSON.stringify(model.__getScriptProps());
        script.innerHTML = "\n      setTimeout(function() {\n        var item = document.getElementById('".concat(id, "');\n        if (!item) return;\n        (").concat(scriptFnStr, ".bind(item))(").concat(scriptProps, ")\n      }, 1);");
        // #873
        // Adding setTimeout will make js components work on init of the editor
        setTimeout(function () {
            var scr = view.scriptContainer;
            scr === null || scr === void 0 ? void 0 : scr.appendChild(script);
        }, 0);
    };
    /**
     * Get javascript container
     * @private
     */
    CanvasView.prototype.getJsContainer = function (view) {
        var frameView = this.getFrameView(view);
        return frameView === null || frameView === void 0 ? void 0 : frameView.getJsContainer();
    };
    CanvasView.prototype.getFrameView = function (view) {
        return (view === null || view === void 0 ? void 0 : view.frameView) || this.em.getCurrentFrame();
    };
    CanvasView.prototype._renderFrames = function () {
        if (!this.ready)
            return;
        var _a = this, model = _a.model, frames = _a.frames, em = _a.em, framesArea = _a.framesArea;
        var frms = model.frames;
        frms.listenToLoad();
        frames.render();
        var mainFrame = frms.at(0);
        var currFrame = mainFrame === null || mainFrame === void 0 ? void 0 : mainFrame.view;
        em.setCurrentFrame(currFrame);
        framesArea === null || framesArea === void 0 ? void 0 : framesArea.appendChild(frames.el);
        this.frame = currFrame;
        this.updateFramesArea();
    };
    CanvasView.prototype.renderFrames = function () {
        this._renderFrames();
    };
    CanvasView.prototype.render = function () {
        var _a = this, el = _a.el, $el = _a.$el, ppfx = _a.ppfx, config = _a.config, em = _a.em;
        $el.html(this.template());
        var $frames = $el.find('[data-frames]');
        this.framesArea = $frames.get(0);
        var toolsWrp = $el.find('[data-tools]');
        this.toolsWrapper = toolsWrp.get(0);
        toolsWrp.append("\n      <div class=\"".concat(ppfx, "tools ").concat(ppfx, "tools-gl\" style=\"pointer-events:none\">\n        <div class=\"").concat(ppfx, "placeholder\">\n          <div class=\"").concat(ppfx, "placeholder-int\"></div>\n        </div>\n      </div>\n      <div id=\"").concat(ppfx, "tools\" style=\"pointer-events:none\">\n        ").concat(config.extHl ? "<div class=\"".concat(ppfx, "highlighter-sel\"></div>") : '', "\n        <div class=\"").concat(ppfx, "badge\"></div>\n        <div class=\"").concat(ppfx, "ghost\"></div>\n        <div class=\"").concat(ppfx, "toolbar\" style=\"pointer-events:all\"></div>\n        <div class=\"").concat(ppfx, "resizer\"></div>\n        <div class=\"").concat(ppfx, "offset-v\"></div>\n        <div class=\"").concat(ppfx, "offset-fixed-v\"></div>\n      </div>\n    "));
        this.toolsEl = el.querySelector("#".concat(ppfx, "tools"));
        this.hlEl = el.querySelector(".".concat(ppfx, "highlighter"));
        this.badgeEl = el.querySelector(".".concat(ppfx, "badge"));
        this.placerEl = el.querySelector(".".concat(ppfx, "placeholder"));
        this.ghostEl = el.querySelector(".".concat(ppfx, "ghost"));
        this.toolbarEl = el.querySelector(".".concat(ppfx, "toolbar"));
        this.resizerEl = el.querySelector(".".concat(ppfx, "resizer"));
        this.offsetEl = el.querySelector(".".concat(ppfx, "offset-v"));
        this.fixedOffsetEl = el.querySelector(".".concat(ppfx, "offset-fixed-v"));
        this.toolsGlobEl = el.querySelector(".".concat(ppfx, "tools-gl"));
        this.spotsEl = el.querySelector('[data-spots]');
        this.cvStyle = el.querySelector('[data-canvas-style]');
        this.el.className = (0,mixins.getUiClass)(em, this.className);
        this.ready = true;
        this._renderFrames();
        return this;
    };
    return CanvasView;
}(abstract_ModuleView));
/* harmony default export */ const view_CanvasView = (CanvasView);

;// CONCATENATED MODULE: ./src/canvas/index.ts
/**
 * You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](https://github.com/GrapesJS/grapesjs/blob/master/src/canvas/config/config.ts)
 * ```js
 * const editor = grapesjs.init({
 *  canvas: {
 *    // options
 *  }
 * })
 * ```
 *
 * Once the editor is instantiated you can use its API and listen to its events. Before using these methods, you should get the module from the instance.
 *
 * ```js
 * // Listen to events
 * editor.on('canvas:drop', () => { ... });
 *
 * // Use the API
 * const canvas = editor.Canvas;
 * canvas.setCoords(...);
 * ```
 *
 * {REPLACE_EVENTS}
 *
 * [Component]: component.html
 * [Frame]: frame.html
 * [CanvasSpot]: canvas_spot.html
 *
 * @module Canvas
 */
var canvas_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var canvas_assign = (undefined && undefined.__assign) || function () {
    canvas_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return canvas_assign.apply(this, arguments);
};
var canvas_spreadArray = (undefined && undefined.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};










var CanvasModule = /** @class */ (function (_super) {
    canvas_extends(CanvasModule, _super);
    /**
     * Initialize module. Automatically called with a new instance of the editor
     * @param {Object} config Configurations
     * @private
     */
    function CanvasModule(em) {
        var _this = _super.call(this, em, 'Canvas', canvas_config_config) || this;
        _this.events = CanvasEvents;
        _this.framesById = {};
        _this.canvas = new model_Canvas(_this);
        _this.spots = new model_CanvasSpots(_this);
        _this.model = _this.canvas;
        _this.startAutoscroll = _this.startAutoscroll.bind(_this);
        _this.stopAutoscroll = _this.stopAutoscroll.bind(_this);
        return _this;
    }
    /**
     * Get configuration object
     * @name getConfig
     * @function
     * @return {Object}
     */
    /**
     * Used inside RTE
     * @private
     */
    CanvasModule.prototype.getCanvasView = function () {
        return this.canvasView;
    };
    CanvasModule.prototype.postLoad = function () {
        this.model.init();
    };
    CanvasModule.prototype.getModel = function () {
        return this.canvas;
    };
    /**
     * Get the canvas element
     * @returns {HTMLElement}
     */
    CanvasModule.prototype.getElement = function () {
        return this.getCanvasView().el;
    };
    CanvasModule.prototype.getFrame = function (index) {
        return this.getFrames()[index || 0];
    };
    /**
     * Get the main frame element of the canvas
     * @returns {HTMLIFrameElement}
     */
    CanvasModule.prototype.getFrameEl = function () {
        var frame = (this.canvasView || {}).frame;
        return frame === null || frame === void 0 ? void 0 : frame.el;
    };
    CanvasModule.prototype.getFramesEl = function () {
        var _a;
        return (_a = this.canvasView) === null || _a === void 0 ? void 0 : _a.framesArea;
    };
    /**
     * Get the main frame window instance
     * @returns {Window}
     */
    CanvasModule.prototype.getWindow = function () {
        var frame = (this.canvasView || {}).frame;
        return frame === null || frame === void 0 ? void 0 : frame.getWindow();
    };
    /**
     * Get the main frame document element
     * @returns {HTMLDocument}
     */
    CanvasModule.prototype.getDocument = function () {
        var frame = this.getFrameEl();
        return frame === null || frame === void 0 ? void 0 : frame.contentDocument;
    };
    /**
     * Get the main frame body element
     * @return {HTMLBodyElement}
     */
    CanvasModule.prototype.getBody = function () {
        var doc = this.getDocument();
        return doc === null || doc === void 0 ? void 0 : doc.body;
    };
    CanvasModule.prototype._getLocalEl = function (globalEl, compView, method) {
        var result = globalEl;
        var frameView = compView === null || compView === void 0 ? void 0 : compView.frameView;
        result = frameView ? frameView[method]() : result;
        return result;
    };
    /**
     * Returns element containing all global canvas tools
     * @returns {HTMLElement}
     * @private
     */
    CanvasModule.prototype.getGlobalToolsEl = function () {
        var _a;
        return (_a = this.canvasView) === null || _a === void 0 ? void 0 : _a.toolsGlobEl;
    };
    /**
     * Returns element containing all canvas tools
     * @returns {HTMLElement}
     * @private
     */
    CanvasModule.prototype.getToolsEl = function (compView) {
        return this._getLocalEl(this.getCanvasView().toolsEl, compView, 'getToolsEl');
    };
    /**
     * Returns highlighter element
     * @returns {HTMLElement}
     * @private
     */
    CanvasModule.prototype.getHighlighter = function (compView) {
        return this._getLocalEl(this.getCanvasView().hlEl, compView, 'getHighlighter');
    };
    /**
     * Returns badge element
     * @returns {HTMLElement}
     * @private
     */
    CanvasModule.prototype.getBadgeEl = function (compView) {
        return this._getLocalEl(this.getCanvasView().badgeEl, compView, 'getBadgeEl');
    };
    /**
     * Returns placer element
     * @returns {HTMLElement}
     * @private
     */
    CanvasModule.prototype.getPlacerEl = function () {
        return this.getCanvasView().placerEl;
    };
    /**
     * Returns ghost element
     * @returns {HTMLElement}
     * @private
     */
    CanvasModule.prototype.getGhostEl = function () {
        return this.getCanvasView().ghostEl;
    };
    /**
     * Returns toolbar element
     * @returns {HTMLElement}
     * @private
     */
    CanvasModule.prototype.getToolbarEl = function () {
        return this.getCanvasView().toolbarEl;
    };
    /**
     * Returns resizer element
     * @returns {HTMLElement}
     * @private
     */
    CanvasModule.prototype.getResizerEl = function () {
        return this.getCanvasView().resizerEl;
    };
    /**
     * Returns offset viewer element
     * @returns {HTMLElement}
     * @private
     */
    CanvasModule.prototype.getOffsetViewerEl = function (compView) {
        return this._getLocalEl(this.getCanvasView().offsetEl, compView, 'getOffsetViewerEl');
    };
    /**
     * Returns fixed offset viewer element
     * @returns {HTMLElement}
     * @private
     */
    CanvasModule.prototype.getFixedOffsetViewerEl = function () {
        return this.getCanvasView().fixedOffsetEl;
    };
    CanvasModule.prototype.getSpotsEl = function () {
        var _a;
        return (_a = this.canvasView) === null || _a === void 0 ? void 0 : _a.spotsEl;
    };
    CanvasModule.prototype.render = function () {
        var _a;
        (_a = this.canvasView) === null || _a === void 0 ? void 0 : _a.remove();
        this.canvasView = new view_CanvasView(this.canvas);
        return this.canvasView.render().el;
    };
    /**
     * Get frame position
     * @returns {Object}
     * @private
     */
    CanvasModule.prototype.getOffset = function () {
        var frameOff = this.offset(this.getFrameEl());
        var canvasOff = this.offset(this.getElement());
        return {
            top: frameOff.top - canvasOff.top,
            left: frameOff.left - canvasOff.left,
        };
    };
    /**
     * Get the offset of the passed component element
     * @param  {HTMLElement} el
     * @returns {Object}
     * @private
     */
    CanvasModule.prototype.offset = function (el) {
        return this.getCanvasView().offset(el);
    };
    /**
     * Set custom badge naming strategy
     * @param  {Function} f
     * @example
     * canvas.setCustomBadgeLabel(function(component){
     *  return component.getName();
     * });
     */
    CanvasModule.prototype.setCustomBadgeLabel = function (f) {
        //@ts-ignore
        this.config.customBadgeLabel = f;
    };
    /**
     * Get element position relative to the canvas
     * @param {HTMLElement} el
     * @returns {Object}
     * @private
     */
    CanvasModule.prototype.getElementPos = function (el, opts) {
        return this.getCanvasView().getElementPos(el, opts);
    };
    /**
     * Returns element's offsets like margins and paddings
     * @param {HTMLElement} el
     * @returns {Object}
     * @private
     */
    CanvasModule.prototype.getElementOffsets = function (el) {
        return this.getCanvasView().getElementOffsets(el);
    };
    /**
     * Get canvas rectangular data
     * @returns {Object}
     */
    CanvasModule.prototype.getRect = function () {
        var _a;
        var _b = (_a = this.getCanvasView().getPosition()) !== null && _a !== void 0 ? _a : {}, _c = _b.top, top = _c === void 0 ? 0 : _c, _d = _b.left, left = _d === void 0 ? 0 : _d;
        return canvas_assign(canvas_assign({}, this.getCanvasView().getCanvasOffset()), { topScroll: top, leftScroll: left });
    };
    /**
     * This method comes handy when you need to attach something like toolbars
     * to elements inside the canvas, dealing with all relative position,
     * offsets, etc. and returning as result the object with positions which are
     * viewable by the user (when the canvas is scrolled the top edge of the element
     * is not viewable by the user anymore so the new top edge is the one of the canvas)
     *
     * The target should be visible before being passed here as invisible elements
     * return empty string as width
     * @param {HTMLElement} target The target in this case could be the toolbar
     * @param {HTMLElement} element The element on which I'd attach the toolbar
     * @param {Object} options Custom options
     * @param {Boolean} options.toRight Set to true if you want the toolbar attached to the right
     * @return {Object}
     * @private
     */
    CanvasModule.prototype.getTargetToElementDim = function (target, element, options) {
        if (options === void 0) { options = {}; }
        var opts = options || {};
        var canvasPos = this.getCanvasView().getPosition();
        if (!canvasPos)
            return;
        var pos = opts.elPos || this.getCanvasView().getElementPos(element);
        var toRight = options.toRight || 0;
        var targetHeight = opts.targetHeight || target.offsetHeight;
        var targetWidth = opts.targetWidth || target.offsetWidth;
        var eventToTrigger = opts.event || null;
        var elTop = pos.top - targetHeight;
        var elLeft = pos.left;
        elLeft += toRight ? pos.width : 0;
        elLeft = toRight ? elLeft - targetWidth : elLeft;
        var leftPos = elLeft < canvasPos.left ? canvasPos.left : elLeft;
        var topPos = elTop < canvasPos.top ? canvasPos.top : elTop;
        topPos = topPos > pos.top + pos.height ? pos.top + pos.height : topPos;
        var result = {
            top: topPos,
            left: leftPos,
            elementTop: pos.top,
            elementLeft: pos.left,
            elementWidth: pos.width,
            elementHeight: pos.height,
            targetWidth: target.offsetWidth,
            targetHeight: target.offsetHeight,
            canvasTop: canvasPos.top,
            canvasLeft: canvasPos.left,
            canvasWidth: canvasPos.width,
            canvasHeight: canvasPos.height,
        };
        // In this way I can catch data and also change the position strategy
        if (eventToTrigger && this.em) {
            this.em.trigger(eventToTrigger, result);
        }
        return result;
    };
    CanvasModule.prototype.canvasRectOffset = function (el, pos, opts) {
        var _this = this;
        if (opts === void 0) { opts = {}; }
        var getFrameElFromDoc = function (doc) {
            var defaultView = doc.defaultView;
            return defaultView === null || defaultView === void 0 ? void 0 : defaultView.frameElement;
        };
        var rectOff = function (el, top, pos) {
            if (top === void 0) { top = 1; }
            var zoom = _this.em.getZoomDecimal();
            var side = top ? 'top' : 'left';
            var doc = el.ownerDocument;
            var _a = opts.offset ? getFrameElFromDoc(doc) : {}, _b = _a.offsetTop, offsetTop = _b === void 0 ? 0 : _b, _c = _a.offsetLeft, offsetLeft = _c === void 0 ? 0 : _c;
            var _d = doc.body || {}, _e = _d.scrollTop, scrollTop = _e === void 0 ? 0 : _e, _f = _d.scrollLeft, scrollLeft = _f === void 0 ? 0 : _f;
            var scroll = top ? scrollTop : scrollLeft;
            var offset = top ? offsetTop : offsetLeft;
            return pos[side] - (scroll - offset) * zoom;
        };
        return {
            top: rectOff(el, 1, pos),
            left: rectOff(el, 0, pos),
        };
    };
    /**
     *
     * @param {HTMLElement} el The component element in the canvas
     * @param {HTMLElement} targetEl The target element to position (eg. toolbar)
     * @param {Object} opts
     * @private
     */
    CanvasModule.prototype.getTargetToElementFixed = function (el, targetEl, opts) {
        if (opts === void 0) { opts = {}; }
        var elRect = opts.pos || this.getElementPos(el, { noScroll: true });
        var canvasOffset = opts.canvasOff || this.canvasRectOffset(el, elRect);
        var targetHeight = targetEl.offsetHeight || 0;
        var targetWidth = targetEl.offsetWidth || 0;
        var elRight = elRect.left + elRect.width;
        var canvasView = this.getCanvasView();
        var canvasRect = canvasView.getPosition();
        var frameOffset = canvasView.getFrameOffset(el);
        var event = opts.event;
        var top = -targetHeight;
        var left = !(0,index_all.isUndefined)(opts.left) ? opts.left : elRect.width - targetWidth;
        left = elRect.left < -left ? -elRect.left : left;
        left = elRight > canvasRect.width ? left - (elRight - canvasRect.width) : left;
        // Check when the target top edge reaches the top of the viewable canvas
        if (canvasOffset.top < targetHeight) {
            var fullHeight = elRect.height + targetHeight;
            var elIsShort = fullHeight < frameOffset.height;
            // Scroll with the window if the top edge is reached and the
            // element is bigger than the canvas
            if (elIsShort) {
                top = top + fullHeight;
            }
            else {
                top = -canvasOffset.top < elRect.height ? -canvasOffset.top : elRect.height;
            }
        }
        var result = {
            top: top,
            left: left,
            canvasOffsetTop: canvasOffset.top,
            canvasOffsetLeft: canvasOffset.left,
            elRect: elRect,
            canvasOffset: canvasOffset,
            canvasRect: canvasRect,
            targetWidth: targetWidth,
            targetHeight: targetHeight,
        };
        // In this way I can catch data and also change the position strategy
        event && this.em.trigger(event, result);
        return result;
    };
    /**
     * Instead of simply returning e.clientX and e.clientY this function
     * calculates also the offset based on the canvas. This is helpful when you
     * need to get X and Y position while moving between the editor area and
     * canvas area, which is in the iframe
     * @param {Event} e
     * @return {Object}
     * @private
     */
    CanvasModule.prototype.getMouseRelativePos = function (e, opts) {
        if (opts === void 0) { opts = {}; }
        var subWinOffset = opts.subWinOffset;
        var doc = e.target.ownerDocument;
        var win = doc.defaultView || doc.parentWindow;
        var frame = win.frameElement;
        var yOffset = subWinOffset ? win.pageYOffset : 0;
        var xOffset = subWinOffset ? win.pageXOffset : 0;
        var zoomMlt = this.getZoomMultiplier();
        var addTop = 0;
        var addLeft = 0;
        if (frame) {
            var frameRect = frame.getBoundingClientRect();
            addTop = frameRect.top || 0;
            addLeft = frameRect.left || 0;
        }
        return {
            y: (e.clientY + addTop - yOffset) * zoomMlt,
            x: (e.clientX + addLeft - xOffset) * zoomMlt,
        };
    };
    /**
     * X and Y mouse position relative to the canvas
     * @param {Event} ev
     * @return {Object}
     * @private
     */
    CanvasModule.prototype.getMouseRelativeCanvas = function (ev, opts) {
        var _a;
        var zoom = this.getZoomDecimal();
        var _b = (_a = this.getCanvasView().getPosition(opts)) !== null && _a !== void 0 ? _a : {}, _c = _b.top, top = _c === void 0 ? 0 : _c, _d = _b.left, left = _d === void 0 ? 0 : _d;
        return {
            y: ev.clientY * zoom + top,
            x: ev.clientX * zoom + left,
        };
    };
    /**
     * Check if the canvas is focused
     * @returns {Boolean}
     */
    CanvasModule.prototype.hasFocus = function () {
        return this.getDocument().hasFocus();
    };
    /**
     * Detects if some input is focused (input elements, text components, etc.)
     * @return {Boolean}
     * @private
     */
    CanvasModule.prototype.isInputFocused = function () {
        var doc = this.getDocument();
        var frame = this.getFrameEl();
        var toIgnore = canvas_spreadArray(['body'], this.config.notTextable, true);
        var docActive = frame && document.activeElement === frame;
        var focused = docActive ? doc && doc.activeElement : document.activeElement;
        return focused && !toIgnore.some(function (item) { return focused.matches(item); });
    };
    /**
     * Scroll canvas to the element if it's not visible. The scrolling is
     * executed via `scrollIntoView` API and options of this method are
     * passed to it. For instance, you can scroll smoothly by using
     * `{ behavior: 'smooth' }`.
     * @param  {HTMLElement|[Component]} el
     * @param  {Object} [opts={}] Options, same as options for `scrollIntoView`
     * @param  {Boolean} [opts.force=false] Force the scroll, even if the element is already visible
     * @example
     * const selected = editor.getSelected();
     * // Scroll smoothly (this behavior can be polyfilled)
     * canvas.scrollTo(selected, { behavior: 'smooth' });
     * // Force the scroll, even if the element is alredy visible
     * canvas.scrollTo(selected, { force: true });
     */
    CanvasModule.prototype.scrollTo = function (el, opts) {
        if (opts === void 0) { opts = {}; }
        var elem = (0,mixins.getElement)(el);
        var view = elem && (0,mixins.getViewEl)(elem);
        view && view.scrollIntoView(opts);
    };
    /**
     * Start autoscroll
     * @private
     */
    CanvasModule.prototype.startAutoscroll = function (frame) {
        var fr = (frame && frame.view) || this.em.getCurrentFrame();
        fr && fr.startAutoscroll();
    };
    /**
     * Stop autoscroll
     * @private
     */
    CanvasModule.prototype.stopAutoscroll = function (frame) {
        var fr = (frame && frame.view) || this.em.getCurrentFrame();
        fr && fr.stopAutoscroll();
    };
    /**
     * Set canvas zoom value
     * @param {Number} value The zoom value, from 0 to 100
     * @returns {this}
     * @example
     * canvas.setZoom(50); // set zoom to 50%
     */
    CanvasModule.prototype.setZoom = function (value) {
        this.canvas.set('zoom', typeof value === 'string' ? parseFloat(value) : value);
        return this;
    };
    /**
     * Get canvas zoom value
     * @returns {Number}
     * @example
     * canvas.setZoom(50); // set zoom to 50%
     * const zoom = canvas.getZoom(); // 50
     */
    CanvasModule.prototype.getZoom = function () {
        return parseFloat(this.canvas.get('zoom'));
    };
    /**
     * Set canvas position coordinates
     * @param {Number} x Horizontal position
     * @param {Number} y Vertical position
     * @returns {this}
     * @example
     * canvas.setCoords(100, 100);
     */
    CanvasModule.prototype.setCoords = function (x, y, opts) {
        var _a;
        if (opts === void 0) { opts = {}; }
        var hasX = x || x === 0;
        var hasY = y || y === 0;
        var coords = {
            x: this.canvas.get('x'),
            y: this.canvas.get('y'),
        };
        if (hasX)
            coords.x = parseFloat("".concat(x));
        if (hasY)
            coords.y = parseFloat("".concat(y));
        if (opts.toWorld) {
            var delta = (_a = this.canvasView) === null || _a === void 0 ? void 0 : _a.getViewportDelta();
            if (delta) {
                if (hasX)
                    coords.x = coords.x - delta.x;
                if (hasY)
                    coords.y = coords.y - delta.y;
            }
        }
        this.canvas.set(coords);
        return this;
    };
    /**
     * Get canvas position coordinates
     * @returns {Object} Object containing coordinates
     * @example
     * canvas.setCoords(100, 100);
     * const coords = canvas.getCoords();
     * // { x: 100, y: 100 }
     */
    CanvasModule.prototype.getCoords = function () {
        var _a = this.canvas.attributes, x = _a.x, y = _a.y;
        return { x: x, y: y };
    };
    /**
     * Get canvas pointer position coordinates.
     * @returns {Object} Object containing pointer coordinates
     * @private
     * @example
     * const worldPointer = canvas.getPointer();
     * const screenPointer = canvas.getPointer(true);
     */
    CanvasModule.prototype.getPointer = function (screen) {
        var _a = this.canvas.attributes, pointer = _a.pointer, pointerScreen = _a.pointerScreen;
        return screen ? pointerScreen : pointer;
    };
    CanvasModule.prototype.getZoomDecimal = function () {
        return this.getZoom() / 100;
    };
    CanvasModule.prototype.getZoomMultiplier = function () {
        var zoom = this.getZoomDecimal();
        return zoom ? 1 / zoom : 1;
    };
    CanvasModule.prototype.fitViewport = function (opts) {
        var _a;
        (_a = this.canvasView) === null || _a === void 0 ? void 0 : _a.fitViewport(opts);
    };
    CanvasModule.prototype.toggleFramesEvents = function (on) {
        var style = this.getFramesEl().style;
        style.pointerEvents = on ? '' : 'none';
    };
    CanvasModule.prototype.getFrames = function () {
        return this.canvas.frames.map(function (item) { return item; });
    };
    /**
     * Add new frame to the canvas
     * @param {Object} props Frame properties
     * @returns {[Frame]}
     * @private
     * @example
     * canvas.addFrame({
     *   name: 'Mobile home page',
     *   x: 100, // Position in canvas
     *   y: 100,
     *   width: 500, // Frame dimensions
     *   height: 600,
     *   // device: 'DEVICE-ID',
     *   components: [
     *     '<h1 class="testh">Title frame</h1>',
     *     '<p class="testp">Paragraph frame</p>',
     *   ],
     *   styles: `
     *     .testh { color: red; }
     *     .testp { color: blue; }
     *   `,
     * });
     */
    CanvasModule.prototype.addFrame = function (props, opts) {
        if (props === void 0) { props = {}; }
        if (opts === void 0) { opts = {}; }
        return this.canvas.frames.add(new model_Frame(this, canvas_assign({}, props)), opts);
    };
    /**
     * Get the last created Component from a drag & drop to the canvas.
     * @returns {[Component]|undefined}
     */
    CanvasModule.prototype.getLastDragResult = function () {
        return this.em.get('dragResult');
    };
    /**
     * Add or update canvas spot.
     * @param {Object} props Canvas spot properties.
     * @param opts
     * @returns {[CanvasSpot]}
     * @example
     * // Add new canvas spot
     * const spot = canvas.addSpot({
     *  type: 'select', // 'select' is one of the built-in spots
     *  component: editor.getSelected(),
     * });
     *
     * // Add custom canvas spot
     * const spot = canvas.addSpot({
     *  type: 'my-custom-spot',
     *  component: editor.getSelected(),
     * });
     * // Update the same spot by reusing its ID
     * canvas.addSpot({
     *  id: spot.id,
     *  component: anotherComponent,
     * });
     */
    CanvasModule.prototype.addSpot = function (props, opts) {
        var _a;
        if (opts === void 0) { opts = {}; }
        var spotProps = props;
        var spots = this.getSpots(spotProps);
        if (spots.length) {
            var spot_1 = spots[0];
            spot_1.set(spotProps);
            return spot_1;
        }
        var cmpView = spotProps.componentView || ((_a = spotProps.component) === null || _a === void 0 ? void 0 : _a.view);
        var spot = new CanvasSpot/* default */.Z(this, canvas_assign(canvas_assign({}, spotProps), { id: spotProps.id || "cs_".concat(spotProps.type, "_").concat(cmpView === null || cmpView === void 0 ? void 0 : cmpView.cid), type: spotProps.type || '' }));
        this.spots.add(spot, opts);
        return spot;
    };
    /**
     * Get canvas spots.
     * @param {Object} [spotProps] Canvas spot properties for filtering the result. With no properties, all available spots will be returned.
     * @returns {[CanvasSpot][]}
     * @example
     * canvas.addSpot({ type: 'select', component: cmp1 });
     * canvas.addSpot({ type: 'select', component: cmp2 });
     * canvas.addSpot({ type: 'target', component: cmp3 });
     *
     * // Get all spots
     * const allSpots = canvas.getSpots();
     * allSpots.length; // 3
     *
     * // Get all 'select' spots
     * const allSelectSpots = canvas.getSpots({ type: 'select' });
     * allSelectSpots.length; // 2
     */
    CanvasModule.prototype.getSpots = function (spotProps) {
        if (spotProps === void 0) { spotProps = {}; }
        return this.spots.where(spotProps.id ? { id: spotProps.id } : spotProps);
    };
    /**
     * Remove canvas spots.
     * @param {Object|[CanvasSpot][]} [spotProps] Canvas spot properties for filtering spots to remove or an array of spots to remove. With no properties, all available spots will be removed.
     * @returns {[CanvasSpot][]}
     * @example
     * canvas.addSpot({ type: 'select', component: cmp1 });
     * canvas.addSpot({ type: 'select', component: cmp2 });
     * canvas.addSpot({ type: 'target', component: cmp3 });
     *
     * // Remove all 'select' spots
     * canvas.removeSpots({ type: 'select' });
     *
     * // Remove spots by an array of canvas spots
     * const filteredSpots = canvas.getSpots().filter(spot => myCustomCondition);
     * canvas.removeSpots(filteredSpots);
     *
     * // Remove all spots
     * canvas.removeSpots();
     */
    CanvasModule.prototype.removeSpots = function (spotProps) {
        if (spotProps === void 0) { spotProps = {}; }
        var spots = (0,index_all.isArray)(spotProps) ? spotProps : this.getSpots(spotProps);
        var removed = this.spots.remove(spots);
        return removed;
    };
    /**
     * Check if the built-in canvas spot has a declared custom rendering.
     * @param {String} type Built-in canvas spot type
     * @returns {Boolean}
     * @example
     * grapesjs.init({
     *  // ...
     *  canvas: {
     *    // avoid rendering the built-in 'target' canvas spot
     *    customSpots: { target: true }
     *  }
     * });
     * // ...
     * canvas.hasCustomSpot('select'); // false
     * canvas.hasCustomSpot('target'); // true
     */
    CanvasModule.prototype.hasCustomSpot = function (type) {
        var customSpots = this.config.customSpots;
        if (customSpots === true || (customSpots && type && customSpots[type])) {
            return true;
        }
        return false;
    };
    /**
     * Transform a box rect from the world coordinate system to the screen one.
     * @param {Object} boxRect
     * @returns {Object}
     */
    CanvasModule.prototype.getWorldRectToScreen = function (boxRect) {
        var _a;
        return (_a = this.canvasView) === null || _a === void 0 ? void 0 : _a.getRectToScreen(boxRect);
    };
    /**
     * Update canvas for spots/tools positioning.
     * @param {Object} [opts] Options.
     * @param {Object} [opts.spots=false] Update the position of spots.
     */
    CanvasModule.prototype.refresh = function (opts) {
        if (opts === void 0) { opts = {}; }
        var _a = this, em = _a.em, events = _a.events, canvasView = _a.canvasView;
        canvasView === null || canvasView === void 0 ? void 0 : canvasView.clearOff();
        if (opts.spots || opts.all) {
            this.refreshSpots();
            em.trigger('canvas:updateTools'); // this should be deprecated
        }
        em.set('canvasOffset', this.getOffset()); // this should be deprecated
        em.trigger(events.refresh, opts);
    };
    CanvasModule.prototype.refreshSpots = function () {
        this.spots.refresh();
    };
    CanvasModule.prototype.destroy = function () {
        var _this = this;
        var _a;
        this.canvas.stopListening();
        (_a = this.canvasView) === null || _a === void 0 ? void 0 : _a.remove();
        //[this.canvas, this.canvasView].forEach(i => (i = {}));
        //@ts-ignore
        ['model', 'droppable'].forEach(function (i) { return (_this[i] = {}); });
    };
    return CanvasModule;
}(abstract_Module));
/* harmony default export */ const canvas = (CanvasModule);

;// CONCATENATED MODULE: ./src/dom_components/config/config.ts
/* harmony default export */ const dom_components_config_config = ({
    stylePrefix: 'comp-',
    components: [],
    draggableComponents: true,
    disableTextInnerChilds: false,
    processor: undefined,
    useFrameDoc: false,
    voidElements: [
        'area',
        'base',
        'br',
        'col',
        'embed',
        'hr',
        'img',
        'input',
        'keygen',
        'link',
        'menuitem',
        'meta',
        'param',
        'source',
        'track',
        'wbr',
    ],
});

;// CONCATENATED MODULE: ./src/parser/model/BrowserParserHtml.ts

var htmlType = 'text/html';
var defaultType = htmlType; // 'application/xml';
/* harmony default export */ const BrowserParserHtml = (function (str, config) {
    if (config === void 0) { config = {}; }
    var parser = new DOMParser();
    var mimeType = config.htmlType || defaultType;
    var toHTML = mimeType === htmlType;
    var strF = toHTML ? str : "<div>".concat(str, "</div>");
    var doc = parser.parseFromString(strF, mimeType);
    var res;
    if (toHTML) {
        // Replicate the old parser in order to avoid breaking changes
        var head = doc.head, body_1 = doc.body;
        // Move all scripts at the bottom of the page
        var scripts = head.querySelectorAll('script');
        (0,index_all.each)(scripts, function (node) { return body_1.appendChild(node); });
        // Move inside body all head children
        var hEls_1 = [];
        (0,index_all.each)(head.children, function (n) { return hEls_1.push(n); });
        (0,index_all.each)(hEls_1, function (node, i) { return body_1.insertBefore(node, body_1.children[i]); });
        res = body_1;
    }
    else {
        res = doc.firstChild;
    }
    return res;
});
/**
 * POC, custom html parser specs
 * Parse an HTML string to an array of nodes
 * example
 * parse(`<div class="mycls" data-test>Hello</div><span>World <b>example</b></span>`)
 * // result
 * [
 *  {
 *      tagName: 'div',
 *      attributes: { class: 'mycls', 'data-test': '' },
 *      childNodes: ['Hello'],
 *  },{
 *      tagName: 'span',
 *      childNodes: [
 *          'World ',
 *          {
 *              tagName: 'b',
 *              childNodes: ['example'],
 *          }
 *       ],
 *  }
 * ]
 *

export const parseNodes = nodes => {
  const result = [];

  for (let i = 0; i < nodes.length; i++) {
    result.push(parseNode(nodes[i]));
  }

  return result;
};

export const parseAttributes = attrs => {
  const result = {};

  for (let j = 0; j < attrs.length; j++) {
    const attr = attrs[j];
    const nodeName = attr.nodeName;
    const nodeValue = attr.nodeValue;
    result[nodeName] = nodeValue;
  }

  return result;
};

export const parseNode = el => {
  // Return the string of the textnode element
  if (el.nodeType === 3) {
    return el.nodeValue;
  }

  const tagName = node.tagName ? node.tagName.toLowerCase() : '';
  const attrs = el.attributes || [];
  const nodes = el.childNodes || [];

  return {
    ...(tagName && { tagName }),
    ...(attrs.length && {
      attributes: parseAttributes(attrs)
    }),
    ...(nodes.length && {
      childNodes: parseNodes(nodes)
    })
  };
};

export default (str, config = {}) => {
  const result = [];
  const el = document.createElement('div');
  el.innerHTML = str;
  const nodes = el.childNodes;
  const len = nodes.length;

  for (let i = 0; i < len; i++) {
    result.push(parseNode(nodes[i]));
  }

  return result;
};
 */

;// CONCATENATED MODULE: ./src/parser/model/ParserHtml.ts
var ParserHtml_assign = (undefined && undefined.__assign) || function () {
    ParserHtml_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return ParserHtml_assign.apply(this, arguments);
};


var modelAttrStart = 'data-gjs-';
var ParserHtml_event = 'parse:html';
var ParserHtml = function (em, config) {
    if (config === void 0) { config = {}; }
    return {
        compTypes: '',
        modelAttrStart: modelAttrStart,
        getPropAttribute: function (attrName, attrValue) {
            var name = attrName.replace(this.modelAttrStart, '');
            var valueLen = (attrValue === null || attrValue === void 0 ? void 0 : attrValue.length) || 0;
            var firstChar = attrValue === null || attrValue === void 0 ? void 0 : attrValue.substring(0, 1);
            var lastChar = attrValue === null || attrValue === void 0 ? void 0 : attrValue.substring(valueLen - 1);
            var value = attrValue === 'true' ? true : attrValue === 'false' ? false : attrValue;
            // Try to parse JSON where it's possible
            // I can get false positive here (eg. a selector '[data-attr]')
            // so put it under try/catch and let fail silently
            try {
                value =
                    (firstChar == '{' && lastChar == '}') || (firstChar == '[' && lastChar == ']') ? JSON.parse(value) : value;
            }
            catch (e) { }
            return {
                name: name,
                value: value,
            };
        },
        /**
         * Extract component props from an attribute object
         * @param {Object} attr
         * @returns {Object} An object containing props and attributes without them
         */
        splitPropsFromAttr: function (attr) {
            var _this = this;
            if (attr === void 0) { attr = {}; }
            var props = {};
            var attrs = {};
            (0,index_all.each)(attr, function (value, key) {
                if (key.indexOf(_this.modelAttrStart) === 0) {
                    var propsResult = _this.getPropAttribute(key, value);
                    props[propsResult.name] = propsResult.value;
                }
                else {
                    attrs[key] = value;
                }
            });
            return {
                props: props,
                attrs: attrs,
            };
        },
        /**
         * Parse style string to object
         * @param {string} str
         * @return {Object}
         * @example
         * var stl = ParserHtml.parseStyle('color:black; width:100px; test:value;');
         * console.log(stl);
         * // {color: 'black', width: '100px', test: 'value'}
         */
        parseStyle: function (str) {
            var result = {};
            while (str.indexOf('/*') >= 0) {
                var start = str.indexOf('/*');
                var end = str.indexOf('*/') + 2;
                str = str.replace(str.slice(start, end), '');
            }
            var decls = str.split(';');
            for (var i = 0, len = decls.length; i < len; i++) {
                var decl = decls[i].trim();
                if (!decl)
                    continue;
                var prop = decl.split(':');
                var key = prop[0].trim();
                var value = prop.slice(1).join(':').trim();
                // Support multiple values for the same key
                if (result[key]) {
                    if (!(0,index_all.isArray)(result[key])) {
                        result[key] = [result[key]];
                    }
                    result[key].push(value);
                }
                else {
                    result[key] = value;
                }
            }
            return result;
        },
        /**
         * Parse class string to array
         * @param {string} str
         * @return {Array<string>}
         * @example
         * var res = ParserHtml.parseClass('test1 test2 test3');
         * console.log(res);
         * // ['test1', 'test2', 'test3']
         */
        parseClass: function (str) {
            var result = [];
            var cls = str.split(' ');
            for (var i = 0, len = cls.length; i < len; i++) {
                var cl = cls[i].trim();
                if (!cl)
                    continue;
                result.push(cl);
            }
            return result;
        },
        /**
         * Get data from the node element
         * @param  {HTMLElement} el DOM element to traverse
         * @return {Array<Object>}
         */
        parseNode: function (el, opts) {
            if (opts === void 0) { opts = {}; }
            var result = [];
            var nodes = el.childNodes;
            for (var i = 0, len = nodes.length; i < len; i++) {
                var node = nodes[i];
                var attrs = node.attributes || [];
                var attrsLen = attrs.length;
                var nodePrev = result[result.length - 1];
                var nodeChild = node.childNodes.length;
                var ct = this.compTypes;
                var model = {}; // TODO use component properties
                // Start with understanding what kind of component it is
                if (ct) {
                    var obj = '';
                    var type = node.getAttribute && node.getAttribute("".concat(this.modelAttrStart, "type"));
                    // If the type is already defined, use it
                    if (type) {
                        model = { type: type };
                    }
                    else {
                        // Iterate over all available Component Types and
                        // the first with a valid result will be that component
                        for (var it_1 = 0; it_1 < ct.length; it_1++) {
                            var compType = ct[it_1];
                            // @ts-ignore
                            obj = compType.model.isComponent(node, opts);
                            if (obj) {
                                if (typeof obj !== 'object') {
                                    // @ts-ignore
                                    obj = { type: compType.id };
                                }
                                break;
                            }
                        }
                        model = obj;
                    }
                }
                // Set tag name if not yet done
                if (!model.tagName) {
                    var tag = node.tagName || '';
                    var ns = node.namespaceURI || '';
                    model.tagName = tag && ns === 'http://www.w3.org/1999/xhtml' ? tag.toLowerCase() : tag;
                }
                if (attrsLen) {
                    model.attributes = {};
                }
                // Parse attributes
                for (var j = 0; j < attrsLen; j++) {
                    var nodeName = attrs[j].nodeName;
                    var nodeValue = attrs[j].nodeValue;
                    // Isolate attributes
                    if (nodeName == 'style') {
                        model.style = this.parseStyle(nodeValue);
                    }
                    else if (nodeName == 'class') {
                        model.classes = this.parseClass(nodeValue);
                    }
                    else if (nodeName == 'contenteditable') {
                        continue;
                    }
                    else if (nodeName.indexOf(this.modelAttrStart) === 0) {
                        var propsResult = this.getPropAttribute(nodeName, nodeValue);
                        model[propsResult.name] = propsResult.value;
                    }
                    else {
                        // @ts-ignore Check for attributes from props (eg. required, disabled)
                        if (nodeValue === '' && node[nodeName] === true) {
                            nodeValue = true;
                        }
                        model.attributes[nodeName] = nodeValue;
                    }
                }
                // Check for nested elements but avoid it if already provided
                if (nodeChild && !model.components) {
                    // Avoid infinite nested text nodes
                    var firstChild = node.childNodes[0];
                    // If there is only one child and it's a TEXTNODE
                    // just make it content of the current node
                    if (nodeChild === 1 && firstChild.nodeType === 3) {
                        !model.type && (model.type = 'text');
                        model.components = {
                            type: 'textnode',
                            content: firstChild.nodeValue,
                        };
                    }
                    else {
                        model.components = this.parseNode(node, ParserHtml_assign(ParserHtml_assign({}, opts), { inSvg: opts.inSvg || model.type === 'svg' }));
                    }
                }
                // Check if it's a text node and if could be moved to the prevous model
                if (model.type == 'textnode') {
                    if (nodePrev && nodePrev.type == 'textnode') {
                        nodePrev.content += model.content;
                        continue;
                    }
                    // Throw away empty nodes (keep spaces)
                    if (!opts.keepEmptyTextNodes) {
                        var content = node.nodeValue;
                        if (content != ' ' && !content.trim()) {
                            continue;
                        }
                    }
                }
                // Check for custom void elements (valid in XML)
                if (!nodeChild && "".concat(node.outerHTML).slice(-2) === '/>') {
                    model.void = true;
                }
                // If all children are texts and there is some textnode the parent should
                // be text too otherwise I'm unable to edit texnodes
                var comps = model.components;
                if (!model.type && comps) {
                    var _a = config.textTypes, textTypes = _a === void 0 ? [] : _a, _b = config.textTags, textTags = _b === void 0 ? [] : _b;
                    var allTxt = 1;
                    var foundTextNode = 0;
                    for (var ci = 0; ci < comps.length; ci++) {
                        var comp = comps[ci];
                        var cType = comp.type;
                        if (!textTypes.includes(cType) && !textTags.includes(comp.tagName)) {
                            allTxt = 0;
                            break;
                        }
                        if (cType === 'textnode') {
                            foundTextNode = 1;
                        }
                    }
                    if (allTxt && foundTextNode) {
                        model.type = 'text';
                    }
                }
                // If tagName is still empty and is not a textnode, do not push it
                if (!model.tagName && (0,index_all.isUndefined)(model.content)) {
                    continue;
                }
                result.push(model);
            }
            return result;
        },
        /**
         * Parse HTML string to a desired model object
         * @param  {string} str HTML string
         * @param  {ParserCss} parserCss In case there is style tags inside HTML
         * @return {Object}
         */
        parse: function (str, parserCss, opts) {
            var _a;
            if (opts === void 0) { opts = {}; }
            var conf = (em === null || em === void 0 ? void 0 : em.get('Config')) || {};
            var res = { html: [] };
            var cf = ParserHtml_assign(ParserHtml_assign({}, config), opts);
            var options = ParserHtml_assign(ParserHtml_assign(ParserHtml_assign({}, config.optionsHtml), { 
                // @ts-ignore Support previous `configParser.htmlType` option
                htmlType: ((_a = config.optionsHtml) === null || _a === void 0 ? void 0 : _a.htmlType) || config.htmlType }), opts);
            var preParser = options.preParser;
            var input = (0,index_all.isFunction)(preParser) ? preParser(str, { editor: em === null || em === void 0 ? void 0 : em.getEditor() }) : str;
            var el = (0,index_all.isFunction)(cf.parserHtml) ? cf.parserHtml(input, options) : BrowserParserHtml(input, options);
            var scripts = el.querySelectorAll('script');
            var i = scripts.length;
            // Support previous `configMain.allowScripts` option
            var allowScripts = !(0,index_all.isUndefined)(conf.allowScripts) ? conf.allowScripts : options.allowScripts;
            // Remove script tags
            if (!allowScripts) {
                while (i--)
                    scripts[i].parentNode.removeChild(scripts[i]);
            }
            // Remove unsafe attributes
            if (!options.allowUnsafeAttr || !options.allowUnsafeAttrValue) {
                this.__sanitizeNode(el, options);
            }
            // Detach style tags and parse them
            if (parserCss) {
                var styles = el.querySelectorAll('style');
                var j = styles.length;
                var styleStr = '';
                while (j--) {
                    styleStr = styles[j].innerHTML + styleStr;
                    styles[j].parentNode.removeChild(styles[j]);
                }
                if (styleStr)
                    res.css = parserCss.parse(styleStr);
            }
            em === null || em === void 0 ? void 0 : em.trigger("".concat(ParserHtml_event, ":root"), { input: input, root: el });
            var result = this.parseNode(el, cf);
            // I have to keep it otherwise it breaks the DomComponents.addComponent (returns always array)
            var resHtml = result.length === 1 && !cf.returnArray ? result[0] : result;
            res.html = resHtml;
            em === null || em === void 0 ? void 0 : em.trigger(ParserHtml_event, { input: input, output: res });
            return res;
        },
        __sanitizeNode: function (node, opts) {
            var _this = this;
            var attrs = node.attributes || [];
            var nodes = node.childNodes || [];
            var toRemove = [];
            (0,index_all.each)(attrs, function (attr) {
                var name = attr.nodeName || '';
                var value = attr.nodeValue || '';
                !opts.allowUnsafeAttr && name.startsWith('on') && toRemove.push(name);
                !opts.allowUnsafeAttrValue && value.startsWith('javascript:') && toRemove.push(name);
            });
            toRemove.map(function (name) { return node.removeAttribute(name); });
            (0,index_all.each)(nodes, function (node) { return _this.__sanitizeNode(node, opts); });
        },
    };
};
/* harmony default export */ const model_ParserHtml = (ParserHtml);

;// CONCATENATED MODULE: ./src/domain_abstract/model/StyleableModel.ts
var StyleableModel_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var StyleableModel_assign = (undefined && undefined.__assign) || function () {
    StyleableModel_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return StyleableModel_assign.apply(this, arguments);
};




var parserHtml = model_ParserHtml();
var getLastStyleValue = function (value) {
    return (0,index_all.isArray)(value) ? value[value.length - 1] : value;
};
var StyleableModel = /** @class */ (function (_super) {
    StyleableModel_extends(StyleableModel, _super);
    function StyleableModel() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    /**
     * Forward style string to `parseStyle` to be parse to an object
     * @param  {string} str
     * @returns
     */
    StyleableModel.prototype.parseStyle = function (str) {
        return parserHtml.parseStyle(str);
    };
    /**
     * To trigger the style change event on models I have to
     * pass a new object instance
     * @param {Object} prop
     * @return {Object}
     */
    StyleableModel.prototype.extendStyle = function (prop) {
        return StyleableModel_assign(StyleableModel_assign({}, this.getStyle()), prop);
    };
    /**
     * Get style object
     * @return {Object}
     */
    StyleableModel.prototype.getStyle = function (prop) {
        var style = this.get('style') || {};
        var result = StyleableModel_assign({}, style);
        return prop && (0,index_all.isString)(prop) ? result[prop] : result;
    };
    /**
     * Set new style object
     * @param {Object|string} prop
     * @param {Object} opts
     * @return {Object} Applied properties
     */
    StyleableModel.prototype.setStyle = function (prop, opts) {
        var _this = this;
        if (prop === void 0) { prop = {}; }
        if (opts === void 0) { opts = {}; }
        if ((0,index_all.isString)(prop)) {
            prop = this.parseStyle(prop);
        }
        var propOrig = this.getStyle(opts);
        if (opts.partial || opts.avoidStore) {
            opts.avoidStore = true;
            prop.__p = true;
        }
        else {
            delete prop.__p;
        }
        var propNew = StyleableModel_assign({}, prop);
        var newStyle = StyleableModel_assign({}, propNew);
        // Remove empty style properties
        (0,index_all.keys)(newStyle).forEach(function (prop) {
            if (newStyle[prop] === '') {
                delete newStyle[prop];
            }
        });
        this.set('style', newStyle, opts);
        var diff = (0,mixins.shallowDiff)(propOrig, propNew);
        // Delete the property used for partial updates
        delete diff.__p;
        (0,index_all.keys)(diff).forEach(function (pr) {
            // @ts-ignore
            var em = _this.em;
            if (opts.noEvent)
                return;
            _this.trigger("change:style:".concat(pr));
            if (em) {
                em.trigger('styleable:change', _this, pr, opts);
                em.trigger("styleable:change:".concat(pr), _this, pr, opts);
            }
        });
        return propNew;
    };
    /**
     * Add style property
     * @param {Object|string} prop
     * @param {string} value
     * @example
     * this.addStyle({color: 'red'});
     * this.addStyle('color', 'blue');
     */
    StyleableModel.prototype.addStyle = function (prop, value, opts) {
        var _a;
        if (value === void 0) { value = ''; }
        if (opts === void 0) { opts = {}; }
        if (typeof prop == 'string') {
            prop = (_a = {},
                _a[prop] = value,
                _a);
        }
        else {
            opts = value || {};
        }
        opts.addStyle = prop;
        prop = this.extendStyle(prop);
        this.setStyle(prop, opts);
    };
    /**
     * Remove style property
     * @param {string} prop
     */
    StyleableModel.prototype.removeStyle = function (prop) {
        var style = this.getStyle();
        delete style[prop];
        this.setStyle(style);
    };
    /**
     * Returns string of style properties
     * @param {Object} [opts={}] Options
     * @return {String}
     */
    StyleableModel.prototype.styleToString = function (opts) {
        if (opts === void 0) { opts = {}; }
        var result = [];
        var style = this.getStyle(opts);
        var imp = opts.important;
        var _loop_1 = function (prop) {
            var important = (0,index_all.isArray)(imp) ? imp.indexOf(prop) >= 0 : imp;
            var firstChars = prop.substring(0, 2);
            var isPrivate = firstChars === '__';
            if (isPrivate)
                return "continue";
            var value = style[prop];
            var values = (0,index_all.isArray)(value) ? value : [value];
            values.forEach(function (val) {
                var value = "".concat(val).concat(important ? ' !important' : '');
                value && result.push("".concat(prop, ":").concat(value, ";"));
            });
        };
        for (var prop in style) {
            _loop_1(prop);
        }
        return result.join('');
    };
    StyleableModel.prototype.getSelectors = function () {
        return (this.get('selectors') || this.get('classes'));
    };
    StyleableModel.prototype.getSelectorsString = function (opts) {
        // @ts-ignore
        return this.selectorsToString ? this.selectorsToString(opts) : this.getSelectors().getFullString();
    };
    return StyleableModel;
}(common/* Model */.Hn));
/* harmony default export */ const model_StyleableModel = (StyleableModel);

;// CONCATENATED MODULE: ./src/dom_components/model/Components.ts
var Components_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var Components_assign = (undefined && undefined.__assign) || function () {
    Components_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return Components_assign.apply(this, arguments);
};
var __rest = (undefined && undefined.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
var Components_spreadArray = (undefined && undefined.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};



var getComponentIds = function (cmp, res) {
    if (res === void 0) { res = []; }
    if (!cmp)
        return [];
    var cmps = ((0,index_all.isArray)(cmp) || (0,index_all.isFunction)(cmp.map) ? cmp : [cmp]);
    cmps.map(function (cmp) {
        res.push(cmp.getId());
        getComponentIds(cmp.components().models, res);
    });
    return res;
};
var getComponentsFromDefs = function (items, all, opts) {
    if (all === void 0) { all = {}; }
    if (opts === void 0) { opts = {}; }
    opts.visitedCmps = opts.visitedCmps || {};
    var visitedCmps = opts.visitedCmps;
    var itms = (0,index_all.isArray)(items) ? items : [items];
    return itms.map(function (item) {
        var _a = item.attributes, attributes = _a === void 0 ? {} : _a, components = item.components, tagName = item.tagName, style = item.style;
        var id = attributes.id, draggable = attributes.draggable, restAttr = __rest(attributes, ["id", "draggable"]);
        var result = item;
        if (id) {
            // Detect components with the same ID
            if (!visitedCmps[id]) {
                visitedCmps[id] = [];
                // Update the component if exists already
                if (all[id]) {
                    result = all[id];
                    var cmp = result;
                    tagName && cmp.set({ tagName: tagName }, Components_assign(Components_assign({}, opts), { silent: true }));
                    (0,index_all.keys)(restAttr).length && cmp.addAttributes(restAttr, Components_assign({}, opts));
                    (0,index_all.keys)(style).length && cmp.addStyle(style, opts);
                }
            }
            else {
                // Found another component with the same ID, treat it as a new component
                visitedCmps[id].push(result);
                id = model_Component.getNewId(all);
                result.attributes.id = id;
            }
        }
        if (components) {
            var newComponents = getComponentsFromDefs(components, all);
            if ((0,index_all.isFunction)(result.components)) {
                var cmps = result.components();
                cmps.length > 0 && cmps.reset(newComponents, opts);
            }
            else {
                result.components = newComponents;
            }
        }
        return result;
    });
};
var Components = /** @class */ (function (_super) {
    Components_extends(Components, _super);
    function Components() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Components.prototype.initialize = function (models, opt) {
        if (opt === void 0) { opt = {}; }
        this.opt = opt;
        this.listenTo(this, 'add', this.onAdd);
        this.listenTo(this, 'remove', this.removeChildren);
        this.listenTo(this, 'reset', this.resetChildren);
        var em = opt.em, config = opt.config;
        this.config = config;
        this.em = em;
        this.domc = opt.domc || (em === null || em === void 0 ? void 0 : em.Components);
    };
    Components.prototype.resetChildren = function (models, opts) {
        var _this = this;
        if (opts === void 0) { opts = {}; }
        var coll = this;
        var prev = opts.previousModels || [];
        var toRemove = prev.filter(function (prev) { return !models.get(prev.cid); });
        var newIds = getComponentIds(models);
        var idsToKeep = getComponentIds(prev).filter(function (pr) { return newIds.indexOf(pr) >= 0; });
        opts.keepIds = (opts.keepIds || []).concat(idsToKeep);
        toRemove.forEach(function (md) { return _this.removeChildren(md, coll, opts); });
        models.each(function (model) { return _this.onAdd(model); });
    };
    Components.prototype.resetFromString = function (input, opts) {
        var _a, _b;
        if (input === void 0) { input = ''; }
        if (opts === void 0) { opts = {}; }
        opts.keepIds = getComponentIds(this);
        var _c = this, domc = _c.domc, em = _c.em, parent = _c.parent;
        var cssc = em === null || em === void 0 ? void 0 : em.Css;
        var allByID = (domc === null || domc === void 0 ? void 0 : domc.allById()) || {};
        var parsed = this.parseString(input, opts);
        var newCmps = getComponentsFromDefs(parsed, allByID, opts);
        var _d = opts.visitedCmps, visitedCmps = _d === void 0 ? {} : _d;
        // Clone styles for duplicated components
        Object.keys(visitedCmps).forEach(function (id) {
            var cmps = visitedCmps[id];
            if (cmps.length) {
                // Get all available rules of the component
                var rulesToClone_1 = (cssc === null || cssc === void 0 ? void 0 : cssc.getRules("#".concat(id))) || [];
                if (rulesToClone_1.length) {
                    cmps.forEach(function (cmp) {
                        rulesToClone_1.forEach(function (rule) {
                            var newRule = rule.clone();
                            // @ts-ignore
                            newRule.set('selectors', ["#".concat(cmp.attributes.id)]);
                            cssc.getAll().add(newRule);
                        });
                    });
                }
            }
        });
        this.reset(newCmps, opts);
        em === null || em === void 0 ? void 0 : em.trigger('component:content', parent, opts, input);
        (_b = (_a = parent).__checkInnerChilds) === null || _b === void 0 ? void 0 : _b.call(_a);
    };
    Components.prototype.removeChildren = function (removed, coll, opts) {
        var _this = this;
        if (opts === void 0) { opts = {}; }
        // Removing a parent component can cause this function
        // to be called with an already removed child element
        if (!removed) {
            return;
        }
        var _a = this, domc = _a.domc, em = _a.em;
        var isTemp = opts.temporary || opts.fromUndo;
        removed.prevColl = this; // This one is required for symbols
        if (!isTemp) {
            // Remove the component from the global list
            var id_1 = removed.getId();
            var sels = em.Selectors.getAll();
            var rules = em.Css.getAll();
            var canRemoveStyle = (opts.keepIds || []).indexOf(id_1) < 0;
            var allByID = domc ? domc.allById() : {};
            delete allByID[id_1];
            // Remove all component related styles
            var rulesRemoved = (canRemoveStyle
                ? rules.remove(rules.filter(function (r) { return r.getSelectors().getFullString() === "#".concat(id_1); }), opts)
                : []);
            // Clean selectors
            sels.remove(rulesRemoved.map(function (rule) { return rule.getSelectors().at(0); }));
            if (!removed.opt.temporary) {
                em.Commands.run('core:component-style-clear', {
                    target: removed,
                });
                removed.removed();
                removed.trigger('removed');
                em.trigger('component:remove', removed);
            }
            var inner_1 = removed.components();
            inner_1.forEach(function (it) { return _this.removeChildren(it, coll, opts); });
        }
        // Remove stuff registered in DomComponents.handleChanges
        var inner = removed.components();
        em.stopListening(inner);
        em.stopListening(removed);
        em.stopListening(removed.get('classes'));
        removed.__postRemove();
    };
    /** @ts-ignore */
    Components.prototype.model = function (attrs, options) {
        var opt = options.collection.opt;
        var em = opt.em;
        var model;
        var df = em.Components.componentTypes;
        options.em = em;
        options.config = opt.config;
        options.componentTypes = df;
        options.domc = opt.domc;
        for (var it_1 = 0; it_1 < df.length; it_1++) {
            var dfId = df[it_1].id;
            if (dfId == attrs.type) {
                model = df[it_1].model;
                break;
            }
        }
        // If no model found, get the default one
        if (!model) {
            model = df[df.length - 1].model;
            em &&
                attrs.type &&
                em.logWarning("Component type '".concat(attrs.type, "' not found"), {
                    attrs: attrs,
                    options: options,
                });
        }
        return new model(attrs, options);
    };
    Components.prototype.parseString = function (value, opt) {
        if (opt === void 0) { opt = {}; }
        var _a = this, em = _a.em, domc = _a.domc;
        var cssc = em.Css;
        var parsed = em.Parser.parseHtml(value);
        // We need this to avoid duplicate IDs
        model_Component.checkId(parsed.html, parsed.css, domc.componentsById, opt);
        if (parsed.css && cssc && !opt.temporary) {
            var at = opt.at, optsToPass = __rest(opt, ["at"]);
            cssc.addCollection(parsed.css, Components_assign(Components_assign({}, optsToPass), { extend: 1 }));
        }
        return parsed.html;
    };
    /** @ts-ignore */
    Components.prototype.add = function (models, opt) {
        var _this = this;
        if (opt === void 0) { opt = {}; }
        opt.keepIds = Components_spreadArray(Components_spreadArray([], (opt.keepIds || []), true), getComponentIds(opt.previousModels), true);
        if ((0,index_all.isString)(models)) {
            models = this.parseString(models, opt);
        }
        else if ((0,index_all.isArray)(models)) {
            models = Components_spreadArray([], models, true);
            models.forEach(function (item, index) {
                if ((0,index_all.isString)(item)) {
                    var nodes = _this.parseString(item, opt);
                    models[index] = (0,index_all.isArray)(nodes) && !nodes.length ? null : nodes;
                }
            });
        }
        var isMult = (0,index_all.isArray)(models);
        // @ts-ignore
        models = (isMult ? models : [models]).filter(Boolean).map(function (model) { return _this.processDef(model); });
        // @ts-ignore
        models = isMult ? (0,index_all.flatten)(models, 1) : models[0];
        var result = common/* Collection */.FE.prototype.add.apply(this, [models, opt]);
        this.__firstAdd = result;
        return result;
    };
    /**
     * Process component definition.
     */
    Components.prototype.processDef = function (mdl) {
        // Avoid processing Models
        if (mdl.cid && mdl.ccid)
            return mdl;
        var _a = this, em = _a.em, _b = _a.config, config = _b === void 0 ? {} : _b;
        var processor = config.processor;
        var model = mdl;
        if (processor) {
            model = Components_assign({}, model); // Avoid 'Cannot delete property ...'
            var modelPr = processor(model);
            if (modelPr) {
                (0,index_all.each)(model, function (val, key) { return delete model[key]; });
                (0,index_all.extend)(model, modelPr);
            }
        }
        // React JSX preset
        if (model.$$typeof && typeof model.props == 'object') {
            model = Components_assign({}, model);
            model.props = Components_assign({}, model.props);
            var domc = em.Components;
            var parser = em.Parser;
            var parserHtml = parser.parserHtml;
            (0,index_all.each)(model, function (value, key) {
                if (!(0,index_all.includes)(['props', 'type'], key))
                    delete model[key];
            });
            var props = model.props;
            var comps = props.children;
            delete props.children;
            delete model.props;
            var res = parserHtml.splitPropsFromAttr(props);
            model.attributes = res.attrs;
            if (comps) {
                model.components = comps;
            }
            if (!model.type) {
                model.type = 'textnode';
            }
            else if (!domc.getType(model.type)) {
                model.tagName = model.type;
                delete model.type;
            }
            (0,index_all.extend)(model, res.props);
        }
        return model;
    };
    Components.prototype.onAdd = function (model, c, opts) {
        if (opts === void 0) { opts = {}; }
        var _a = this, domc = _a.domc, em = _a.em;
        var style = model.getStyle();
        var avoidInline = em && em.getConfig().avoidInlineStyle;
        domc && domc.Component.ensureInList(model);
        // @ts-ignore
        if (!(0,index_all.isEmpty)(style) && !avoidInline && em && em.get && em.getConfig().forceClass && !opts.temporary) {
            var name_1 = model.cid;
            em.Css.setClassRule(name_1, style);
            model.setStyle({});
            model.addClass(name_1);
        }
        model.__postAdd({ recursive: true });
        // this.__onAddEnd();
    };
    return Components;
}(common/* Collection */.FE));
/* harmony default export */ const model_Components = (Components);

;// CONCATENATED MODULE: ./src/selector_manager/model/Selector.ts
var Selector_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();


var TYPE_CLASS = 1;
var TYPE_ID = 2;
/**
 * @typedef Selector
 * @property {String} name Selector name, eg. `my-class`
 * @property {String} label Selector label, eg. `My Class`
 * @property {Number} [type=1] Type of the selector. 1 (class) | 2 (id)
 * @property {Boolean} [active=true] If not active, it's not selectable by the Style Manager.
 * @property {Boolean} [private=false] If true, it can't be seen by the Style Manager, but it will be rendered in the canvas and in export code.
 * @property {Boolean} [protected=false] If true, it can't be removed from the attached component.
 */
var Selector = /** @class */ (function (_super) {
    Selector_extends(Selector, _super);
    /**
     * @hideconstructor
     */
    function Selector(props, opts) {
        if (opts === void 0) { opts = {}; }
        var _this = _super.call(this, props, opts) || this;
        var _a = opts.config, config = _a === void 0 ? {} : _a;
        var name = _this.get('name');
        var label = _this.get('label');
        if (!name) {
            _this.set('name', label);
        }
        else if (!label) {
            _this.set('label', name);
        }
        var namePreEsc = _this.get('name');
        var escapeName = config.escapeName;
        var nameEsc = escapeName ? escapeName(namePreEsc) : Selector.escapeName(namePreEsc);
        _this.set('name', nameEsc);
        _this.em = opts.em;
        return _this;
    }
    Selector.prototype.defaults = function () {
        return {
            name: '',
            label: '',
            type: TYPE_CLASS,
            active: true,
            private: false,
            protected: false,
            _undo: true,
        };
    };
    Selector.prototype.isId = function () {
        return this.get('type') === TYPE_ID;
    };
    Selector.prototype.isClass = function () {
        return this.get('type') === TYPE_CLASS;
    };
    Selector.prototype.getFullName = function (opts) {
        if (opts === void 0) { opts = {}; }
        var escape = opts.escape;
        var name = this.get('name');
        var pfx = '';
        switch (this.get('type')) {
            case TYPE_CLASS:
                pfx = '.';
                break;
            case TYPE_ID:
                pfx = '#';
                break;
        }
        return pfx + (escape ? escape(name) : name);
    };
    /**
     * Get selector as a string.
     * @returns {String}
     * @example
     * // Given such selector: { name: 'my-selector', type: 2 }
     * console.log(selector.toString());
     * // -> `#my-selector`
     */
    Selector.prototype.toString = function () {
        return this.getFullName();
    };
    /**
     * Get selector name.
     * @returns {String}
     * @example
     * // Given such selector: { name: 'my-selector', label: 'My selector' }
     * console.log(selector.getName());
     * // -> `my-selector`
     */
    Selector.prototype.getName = function () {
        return this.get('name') || '';
    };
    /**
     * Get selector label.
     * @returns {String}
     * @example
     * // Given such selector: { name: 'my-selector', label: 'My selector' }
     * console.log(selector.getLabel());
     * // -> `My selector`
     */
    Selector.prototype.getLabel = function () {
        return this.get('label') || '';
    };
    /**
     * Update selector label.
     * @param {String} label New label
     * @example
     * // Given such selector: { name: 'my-selector', label: 'My selector' }
     * selector.setLabel('New Label')
     * console.log(selector.getLabel());
     * // -> `New Label`
     */
    Selector.prototype.setLabel = function (label) {
        return this.set('label', label);
    };
    /**
     * Get selector active state.
     * @returns {Boolean}
     */
    Selector.prototype.getActive = function () {
        return !!this.get('active');
    };
    /**
     * Update selector active state.
     * @param {Boolean} value New active state
     */
    Selector.prototype.setActive = function (value) {
        return this.set('active', value);
    };
    Selector.prototype.toJSON = function (opts) {
        if (opts === void 0) { opts = {}; }
        var em = this.em;
        var obj = common/* Model */.Hn.prototype.toJSON.call(this, [opts]);
        var defaults = (0,index_all.result)(this, 'defaults');
        if (em && em.getConfig().avoidDefaults) {
            (0,index_all.forEach)(defaults, function (value, key) {
                if (obj[key] === value) {
                    delete obj[key];
                }
            });
            if (obj.label === obj.name) {
                delete obj.label;
            }
            var objLen = (0,index_all.keys)(obj).length;
            if (objLen === 1 && obj.name) {
                obj = obj.name;
            }
            if (objLen === 2 && obj.name && obj.type) {
                obj = this.getFullName();
            }
        }
        return obj;
    };
    /**
     * Escape string
     * @param {string} name
     * @return {string}
     * @private
     */
    Selector.escapeName = function (name) {
        return "".concat(name).trim().replace(/([^a-z0-9\w-\\:@\\/]+)/gi, '-');
    };
    // Type selectors: https://developer.mozilla.org/it/docs/Web/CSS/CSS_Selectors
    Selector.TYPE_CLASS = TYPE_CLASS;
    Selector.TYPE_ID = TYPE_ID;
    return Selector;
}(common/* Model */.Hn));
/* harmony default export */ const model_Selector = (Selector);
Selector.prototype.idAttribute = 'name';

;// CONCATENATED MODULE: ./src/selector_manager/model/Selectors.ts
var Selectors_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();



var combine = function (tail, curr) {
    return tail.reduce(function (acc, item, n) {
        return acc.concat(combine(tail.slice(n + 1), "".concat(curr).concat(item)));
    }, [curr]);
};
var Selectors = /** @class */ (function (_super) {
    Selectors_extends(Selectors, _super);
    function Selectors() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Selectors.prototype.modelId = function (attr) {
        return "".concat(attr.name, "_").concat(attr.type || model_Selector.TYPE_CLASS);
    };
    Selectors.prototype.getStyleable = function () {
        return (0,index_all.filter)(this.models, function (item) { return item.getActive() && !item.get('private'); });
    };
    Selectors.prototype.getValid = function (_a) {
        var _b = _a === void 0 ? {} : _a, noDisabled = _b.noDisabled;
        return (0,index_all.filter)(this.models, function (item) { return !item.get('private'); }).filter(function (item) { return (noDisabled ? item.get('active') : 1); });
    };
    Selectors.prototype.getFullString = function (collection, opts) {
        if (opts === void 0) { opts = {}; }
        var result = [];
        var coll = collection || this;
        coll.forEach(function (selector) { return result.push(selector.getFullName(opts)); });
        opts.sort && result.sort();
        return result.join('').trim();
    };
    Selectors.prototype.getFullName = function (opts) {
        if (opts === void 0) { opts = {}; }
        var combination = opts.combination, array = opts.array;
        var result = [];
        var sels = this.map(function (s) { return s.getFullName(opts); }).sort();
        if (combination) {
            sels.forEach(function (sel, n) {
                result = result.concat(combine(sels.slice(n + 1), sel));
            });
        }
        else {
            result = sels;
        }
        return (array ? result : combination ? result.join(',') : result.join(''));
    };
    return Selectors;
}(common/* Collection */.FE));
/* harmony default export */ const model_Selectors = (Selectors);
Selectors.prototype.model = model_Selector;

;// CONCATENATED MODULE: ./src/abstract/ModuleCategory.ts
var ModuleCategory_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var ModuleCategory_spreadArray = (undefined && undefined.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};

var Category = /** @class */ (function (_super) {
    ModuleCategory_extends(Category, _super);
    function Category() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Category.prototype.defaults = function () {
        return {
            id: '',
            label: '',
            open: true,
            attributes: {},
        };
    };
    Category.prototype.getId = function () {
        return this.get('id');
    };
    Category.prototype.getLabel = function () {
        return this.get('label');
    };
    return Category;
}(common/* Model */.Hn));
/* harmony default export */ const ModuleCategory = (Category);
function getItemsByCategory(allItems) {
    var categorySet = new Set();
    var categoryMap = new Map();
    var emptyItem = { items: [] };
    allItems.forEach(function (item) {
        var category = item.category;
        if (category) {
            categorySet.add(category);
            var categoryItems = categoryMap.get(category);
            if (categoryItems) {
                categoryItems.push(item);
            }
            else {
                categoryMap.set(category, [item]);
            }
        }
        else {
            emptyItem.items.push(item);
        }
    });
    var categoryWithItems = Array.from(categorySet).map(function (category) { return ({
        category: category,
        items: categoryMap.get(category) || [],
    }); });
    return ModuleCategory_spreadArray(ModuleCategory_spreadArray([], categoryWithItems, true), [emptyItem], false);
}

;// CONCATENATED MODULE: ./src/abstract/CollectionWithCategories.ts
var CollectionWithCategories_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();




var CATEGORY_KEY = 'category';
var CollectionWithCategories = /** @class */ (function (_super) {
    CollectionWithCategories_extends(CollectionWithCategories, _super);
    function CollectionWithCategories() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    CollectionWithCategories.prototype.initCategory = function (model) {
        var category = model.get(CATEGORY_KEY);
        var isDefined = category instanceof ModuleCategory;
        // Ensure the category exists and it's not already initialized
        if (category && !isDefined) {
            if ((0,index_all.isString)(category)) {
                category = { id: category, label: category };
            }
            else if ((0,mixins.isObject)(category) && !category.id) {
                category.id = category.label;
            }
            var catModel = this.getCategories().add(category);
            model.set(CATEGORY_KEY, catModel, { silent: true });
            return catModel;
        }
        else if (isDefined) {
            var catModel = category;
            this.getCategories().add(catModel);
            return catModel;
        }
    };
    return CollectionWithCategories;
}(common/* Collection */.FE));


;// CONCATENATED MODULE: ./src/abstract/ModuleCategories.ts
var ModuleCategories_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();




var Categories = /** @class */ (function (_super) {
    ModuleCategories_extends(Categories, _super);
    function Categories() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    /** @ts-ignore */
    Categories.prototype.add = function (model, opts) {
        var models = (0,index_all.isArray)(model) ? model : [model];
        models.forEach(function (md) { return md && (md.id = (0,mixins.normalizeKey)("".concat(md.id))); });
        return _super.prototype.add.call(this, model, opts);
    };
    Categories.prototype.get = function (id) {
        return _super.prototype.get.call(this, (0,index_all.isString)(id) ? (0,mixins.normalizeKey)(id) : id);
    };
    return Categories;
}(common/* Collection */.FE));
/* harmony default export */ const ModuleCategories = (Categories);
Categories.prototype.model = ModuleCategory;

;// CONCATENATED MODULE: ./src/trait_manager/types.ts
/**{START_EVENTS}*/
var TraitsEvents;
(function (TraitsEvents) {
    /**
     * @event `trait:select` New traits selected (eg. by changing a component).
     * @example
     * editor.on('trait:select', ({ traits, component }) => { ... });
     */
    TraitsEvents["select"] = "trait:select";
    /**
     * @event `trait:value` Trait value updated.
     * @example
     * editor.on('trait:value', ({ trait, component, value }) => { ... });
     */
    TraitsEvents["value"] = "trait:value";
    /**
     * @event `trait:custom` Event to use in case of [custom Trait Manager UI](https://grapesjs.com/docs/modules/Traits.html#custom-trait-manager).
     * @example
     * editor.on('trait:custom', ({ container }) => { ... });
     */
    TraitsEvents["custom"] = "trait:custom";
    /**
     * @event `trait` Catch-all event for all the events mentioned above. An object containing all the available data about the triggered event is passed as an argument to the callback.
     * @example
     * editor.on('trait', ({ event, model, ... }) => { ... });
     */
    TraitsEvents["all"] = "trait";
})(TraitsEvents || (TraitsEvents = {}));
/**{END_EVENTS}*/
// need this to avoid the TS documentation generator to break
/* harmony default export */ const trait_manager_types = (TraitsEvents);

;// CONCATENATED MODULE: ./src/trait_manager/model/Trait.ts
var Trait_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var Trait_assign = (undefined && undefined.__assign) || function () {
    Trait_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return Trait_assign.apply(this, arguments);
};





/**
 * @property {String} id Trait id, eg. `my-trait-id`.
 * @property {String} type Trait type, defines how the trait should be rendered. Possible values: `text` (default), `number`, `select`, `checkbox`, `color`, `button`
 * @property {String} label The trait label to show for the rendered trait.
 * @property {String} name The name of the trait used as a key for the attribute/property. By default, the name is used as attribute name or property in case `changeProp` in enabled.
 * @property {String} default Default value to use in case the value is not defined on the component.
 * @property {String} placeholder Placeholder to show inside the default input (if the UI type allows it).
 * @property {String} [category=''] Trait category.
 * @property {Boolean} changeProp If `true`, the trait value is applied on the component property, otherwise, on component attributes.
 *
 * @module docsjs.Trait
 *
 */
var Trait = /** @class */ (function (_super) {
    Trait_extends(Trait, _super);
    function Trait(prop, em) {
        var _this = _super.call(this, prop) || this;
        var _a = _this.attributes, target = _a.target, name = _a.name;
        !_this.get('id') && _this.set('id', name);
        if (target) {
            _this.setTarget(target);
        }
        _this.em = em;
        return _this;
    }
    Trait.prototype.defaults = function () {
        return {
            type: 'text',
            label: '',
            name: '',
            unit: '',
            step: 1,
            value: '',
            default: '',
            placeholder: '',
            category: '',
            changeProp: false,
            options: [],
        };
    };
    Object.defineProperty(Trait.prototype, "parent", {
        get: function () {
            return this.collection;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Trait.prototype, "category", {
        get: function () {
            var cat = this.get('category');
            return cat instanceof ModuleCategory ? cat : undefined;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Trait.prototype, "component", {
        get: function () {
            return this.target;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Trait.prototype, "changeProp", {
        get: function () {
            return !!this.get('changeProp');
        },
        enumerable: false,
        configurable: true
    });
    Trait.prototype.setTarget = function (component) {
        if (component) {
            var _a = this.attributes, name_1 = _a.name, changeProp = _a.changeProp, initValue = _a.value, getValue = _a.getValue;
            this.target = component;
            this.unset('target');
            var targetEvent = changeProp ? "change:".concat(name_1) : "change:attributes:".concat(name_1);
            this.listenTo(component, targetEvent, this.targetUpdated);
            var value = initValue ||
                // Avoid the risk of loops in case the trait has a custom getValue
                (!getValue ? this.getValue() : undefined);
            !(0,index_all.isUndefined)(value) && this.set({ value: value }, { silent: true });
        }
    };
    /**
     * Get the trait id.
     * @returns {String}
     */
    Trait.prototype.getId = function () {
        return this.get('id');
    };
    /**
     * Get the trait type.
     * @returns {String}
     */
    Trait.prototype.getType = function () {
        return this.get('type');
    };
    /**
     * Get the trait name.
     * @returns {String}
     */
    Trait.prototype.getName = function () {
        return this.get('name');
    };
    /**
     * Get the trait label.
     * @param {Object} [opts={}] Options.
     * @param {Boolean} [opts.locale=true] Use the locale string from i18n module.
     * @returns {String}
     */
    Trait.prototype.getLabel = function (opts) {
        var _a;
        if (opts === void 0) { opts = {}; }
        var _b = opts.locale, locale = _b === void 0 ? true : _b;
        var id = this.getId();
        var name = this.get('label') || this.getName();
        return (locale && ((_a = this.em) === null || _a === void 0 ? void 0 : _a.t("traitManager.traits.labels.".concat(id)))) || name;
    };
    /**
     * Get the trait value.
     * The value is taken from component attributes by default or from properties if the trait has the `changeProp` enabled.
     * @param {Object} [opts={}] Options.
     * @param {Boolean} [opts.useType=false] Get the value based on type (eg. the checkbox will always return a boolean).
     * @returns {any}
     */
    Trait.prototype.getValue = function (opts) {
        return this.getTargetValue(opts);
    };
    /**
     * Update the trait value.
     * The value is applied on component attributes by default or on properties if the trait has the `changeProp` enabled.
     * @param {any} value Value of the trait.
     * @param {Object} [opts={}] Options.
     * @param {Boolean} [opts.partial] If `true` the update won't be considered complete (not stored in UndoManager).
     */
    Trait.prototype.setValue = function (value, opts) {
        var _this = this;
        if (opts === void 0) { opts = {}; }
        var _a = this, component = _a.component, em = _a.em;
        var partial = opts.partial;
        var valueOpts = {};
        var setValue = this.attributes.setValue;
        if (setValue) {
            setValue({
                value: value,
                component: component,
                editor: em === null || em === void 0 ? void 0 : em.getEditor(),
                trait: this,
                partial: !!partial,
                options: opts,
                emitUpdate: function () { return _this.targetUpdated(); },
            });
            return;
        }
        if (partial) {
            valueOpts.avoidStore = true;
        }
        this.setTargetValue(value, valueOpts);
    };
    /**
     * Get default value.
     */
    Trait.prototype.getDefault = function () {
        return this.get('default');
    };
    /**
     * Get trait options.
     */
    Trait.prototype.getOptions = function () {
        return this.get('options') || [];
    };
    /**
     * Get current selected option or by id.
     * @param {String} [id] Option id.
     * @returns {Object | null}
     */
    Trait.prototype.getOption = function (id) {
        var _this = this;
        var idSel = (0,mixins.isDef)(id) ? id : this.getValue();
        return this.getOptions().filter(function (o) { return _this.getOptionId(o) === idSel; })[0];
    };
    /**
     * Get the option id from the option object.
     * @param {Object} option Option object
     * @returns {String} Option id
     */
    Trait.prototype.getOptionId = function (option) {
        return option.id || option.value;
    };
    /**
     * Get option label.
     * @param {String|Object} id Option id or the option object
     * @param {Object} [opts={}] Options
     * @param {Boolean} [opts.locale=true] Use the locale string from i18n module
     * @returns {String} Option label
     */
    Trait.prototype.getOptionLabel = function (id, opts) {
        var _a;
        if (opts === void 0) { opts = {}; }
        var _b = opts.locale, locale = _b === void 0 ? true : _b;
        var option = ((0,index_all.isString)(id) ? this.getOption(id) : id);
        var optId = this.getOptionId(option);
        var label = option.label || option.name || optId;
        var propName = this.getName();
        return (locale && ((_a = this.em) === null || _a === void 0 ? void 0 : _a.t("traitManager.traits.options.".concat(propName, ".").concat(optId)))) || label;
    };
    /**
     * Get category label.
     * @param {Object} [opts={}] Options.
     * @param {Boolean} [opts.locale=true] Use the locale string from i18n module.
     * @returns {String}
     */
    Trait.prototype.getCategoryLabel = function (opts) {
        if (opts === void 0) { opts = {}; }
        var _a = this, em = _a.em, category = _a.category;
        var _b = opts.locale, locale = _b === void 0 ? true : _b;
        var catId = category === null || category === void 0 ? void 0 : category.getId();
        var catLabel = category === null || category === void 0 ? void 0 : category.getLabel();
        return (locale && (em === null || em === void 0 ? void 0 : em.t("traitManager.categories.".concat(catId)))) || catLabel || '';
    };
    /**
     * Run the trait command (used on the button trait type).
     */
    Trait.prototype.runCommand = function () {
        var em = this.em;
        var command = this.attributes.command;
        if (command && em) {
            if ((0,index_all.isString)(command)) {
                return em.Commands.run(command);
            }
            else {
                return command(em.Editor, this);
            }
        }
    };
    Trait.prototype.props = function () {
        return this.attributes;
    };
    Trait.prototype.targetUpdated = function () {
        var _a = this, component = _a.component, em = _a.em;
        var value = this.getTargetValue({ useType: true });
        this.set({ value: value }, { fromTarget: 1 });
        var props = { trait: this, component: component, value: value };
        component.trigger(trait_manager_types.value, props);
        em === null || em === void 0 ? void 0 : em.trigger(trait_manager_types.value, props);
        // This should be triggered for any trait prop change
        em === null || em === void 0 ? void 0 : em.trigger('trait:update', props);
    };
    Trait.prototype.getTargetValue = function (opts) {
        if (opts === void 0) { opts = {}; }
        var _a = this, component = _a.component, em = _a.em;
        var name = this.getName();
        var getValue = this.get('getValue');
        var value;
        if (getValue) {
            value = getValue({
                editor: em === null || em === void 0 ? void 0 : em.getEditor(),
                trait: this,
                component: component,
            });
        }
        else if (this.changeProp) {
            value = component.get(name);
        }
        else {
            value = component.getAttributes()[name];
        }
        if (opts.useType) {
            var type = this.getType();
            if (type === 'checkbox') {
                var _b = this.attributes, valueTrue = _b.valueTrue, valueFalse = _b.valueFalse;
                if (!(0,index_all.isUndefined)(valueTrue) && valueTrue === value) {
                    value = true;
                }
                else if (!(0,index_all.isUndefined)(valueFalse) && valueFalse === value) {
                    value = false;
                }
            }
        }
        return !(0,index_all.isUndefined)(value) ? value : '';
    };
    Trait.prototype.setTargetValue = function (value, opts) {
        var _a;
        if (opts === void 0) { opts = {}; }
        var _b = this, component = _b.component, attributes = _b.attributes;
        var name = this.getName();
        if ((0,index_all.isUndefined)(value))
            return;
        var valueToSet = value;
        if (value === 'false') {
            valueToSet = false;
        }
        else if (value === 'true') {
            valueToSet = true;
        }
        if (this.getType() === 'checkbox') {
            var valueTrue = attributes.valueTrue, valueFalse = attributes.valueFalse;
            if (valueToSet && !(0,index_all.isUndefined)(valueTrue)) {
                valueToSet = valueTrue;
            }
            if (!valueToSet && !(0,index_all.isUndefined)(valueFalse)) {
                valueToSet = valueFalse;
            }
        }
        var props = (_a = {}, _a[name] = valueToSet, _a);
        // This is required for the UndoManager to properly detect changes
        props.__p = opts.avoidStore ? null : undefined;
        if (this.changeProp) {
            component.set(props, opts);
        }
        else {
            component.addAttributes(props, opts);
        }
    };
    Trait.prototype.setValueFromInput = function (value, final, opts) {
        if (final === void 0) { final = true; }
        if (opts === void 0) { opts = {}; }
        var toSet = { value: value };
        this.set(toSet, Trait_assign(Trait_assign({}, opts), { avoidStore: 1 }));
        // Have to trigger the change
        if (final) {
            this.set('value', '', opts);
            this.set(toSet, opts);
        }
    };
    Trait.prototype.getInitValue = function () {
        var component = this.component;
        var name = this.getName();
        var value;
        if (component) {
            var attrs = component.get('attributes');
            value = this.changeProp ? component.get(name) : attrs[name];
        }
        return value || this.get('value') || this.get('default');
    };
    return Trait;
}(common/* Model */.Hn));
/* harmony default export */ const model_Trait = (Trait);

;// CONCATENATED MODULE: ./src/trait_manager/model/TraitFactory.ts


var TraitFactory = /** @class */ (function () {
    function TraitFactory(config) {
        if (config === void 0) { config = {}; }
        this.config = config;
    }
    /**
     * Build props object by their name
     */
    TraitFactory.prototype.build = function (prop, em) {
        return (0,index_all.isString)(prop) ? this.buildFromString(prop, em) : new model_Trait(prop, em);
    };
    TraitFactory.prototype.buildFromString = function (name, em) {
        var obj = {
            name: name,
            type: 'text',
        };
        switch (name) {
            case 'target':
                obj.type = 'select';
                obj.default = false;
                obj.options = this.config.optionsTarget;
                break;
        }
        return new model_Trait(obj, em);
    };
    return TraitFactory;
}());
/* harmony default export */ const model_TraitFactory = (TraitFactory);

;// CONCATENATED MODULE: ./src/trait_manager/model/Traits.ts
var Traits_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();





var Traits = /** @class */ (function (_super) {
    Traits_extends(Traits, _super);
    function Traits(coll, options) {
        var _this = _super.call(this, coll) || this;
        _this.categories = new ModuleCategories();
        _this.em = options.em;
        _this.on('add', _this.handleAdd);
        _this.on('reset', _this.handleReset);
        var tm = _this.module;
        var tmOpts = tm === null || tm === void 0 ? void 0 : tm.getConfig();
        _this.tf = new model_TraitFactory(tmOpts);
        return _this;
    }
    Object.defineProperty(Traits.prototype, "module", {
        get: function () {
            return this.em.Traits;
        },
        enumerable: false,
        configurable: true
    });
    Traits.prototype.getCategories = function () {
        return this.categories;
    };
    Traits.prototype.handleReset = function (coll, _a) {
        var _b = _a === void 0 ? {} : _a, _c = _b.previousModels, previousModels = _c === void 0 ? [] : _c;
        previousModels.forEach(function (model) { return model.trigger('remove'); });
    };
    Traits.prototype.handleAdd = function (model) {
        model.em = this.em;
        var target = this.target;
        if (target) {
            model.target = target;
        }
        this.initCategory(model);
    };
    Traits.prototype.setTarget = function (target) {
        this.target = target;
        this.models.forEach(function (trait) { return trait.setTarget(target); });
    };
    Traits.prototype.add = function (models, opt) {
        if (models == undefined) {
            return undefined;
        }
        var _a = this, target = _a.target, em = _a.em;
        if ((0,index_all.isArray)(models)) {
            var traits = [];
            for (var i = 0, len = models.length; i < len; i++) {
                var trait_1 = models[i];
                traits[i] = trait_1 instanceof model_Trait ? trait_1 : this.tf.build(trait_1, em);
                traits[i].setTarget(target);
            }
            return _super.prototype.add.call(this, traits, opt);
        }
        var trait = models instanceof model_Trait ? models : this.tf.build(models, em);
        trait.setTarget(target);
        return _super.prototype.add.call(this, trait, opt);
    };
    return Traits;
}(CollectionWithCategories));
/* harmony default export */ const model_Traits = (Traits);

;// CONCATENATED MODULE: ./src/dom_components/model/Component.ts
var Component_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var Component_assign = (undefined && undefined.__assign) || function () {
    Component_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return Component_assign.apply(this, arguments);
};
var Component_rest = (undefined && undefined.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
var Component_spreadArray = (undefined && undefined.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};








var escapeRegExp = function (str) {
    return str.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&');
};
var avoidInline = function (em) { return !!(em === null || em === void 0 ? void 0 : em.getConfig().avoidInlineStyle); };
var eventDrag = 'component:drag';
var keySymbols = '__symbols';
var keySymbol = '__symbol';
var keySymbolOvrd = '__symbol_ovrd';
var keyUpdate = 'component:update';
var keyUpdateInside = "".concat(keyUpdate, "-inside");
/**
 * The Component object represents a single node of our template structure, so when you update its properties the changes are
 * immediately reflected on the canvas and in the code to export (indeed, when you ask to export the code we just go through all
 * the tree of nodes).
 * An example on how to update properties:
 * ```js
 * component.set({
 *  tagName: 'span',
 *  attributes: { ... },
 *  removable: false,
 * });
 * component.get('tagName');
 * // -> 'span'
 * ```
 *
 * [Component]: component.html
 *
 * @property {String} [type=''] Component type, eg. `text`, `image`, `video`, etc.
 * @property {String} [tagName='div'] HTML tag of the component, eg. `span`. Default: `div`
 * @property {Object} [attributes={}] Key-value object of the component's attributes, eg. `{ title: 'Hello' }` Default: `{}`
 * @property {String} [name=''] Name of the component. Will be used, for example, in Layers and badges
 * @property {Boolean} [removable=true] When `true` the component is removable from the canvas, default: `true`
 * @property {Boolean|String|Function} [draggable=true] Indicates if it's possible to drag the component inside others.
 *  You can also specify a query string to indentify elements,
 *  eg. `'.some-class[title=Hello], [data-gjs-type=column]'` means you can drag the component only inside elements
 *  containing `some-class` class and `Hello` title, and `column` components. In the case of a function, target and destination components are passed as arguments, return a Boolean to indicate if the drag is possible. Default: `true`
 * @property {Boolean|String|Function} [droppable=true] Indicates if it's possible to drop other components inside. You can use
 * a query string as with `draggable`. In the case of a function, target and destination components are passed as arguments, return a Boolean to indicate if the drop is possible. Default: `true`
 * @property {Boolean} [badgable=true] Set to false if you don't want to see the badge (with the name) over the component. Default: `true`
 * @property {Boolean|Array<String>} [stylable=true] True if it's possible to style the component.
 * You can also indicate an array of CSS properties which is possible to style, eg. `['color', 'width']`, all other properties
 * will be hidden from the style manager. Default: `true`
 * @property {Array<String>} [stylable-require=[]] Indicate an array of style properties to show up which has been marked as `toRequire`. Default: `[]`
 * @property {Array<String>} [unstylable=[]] Indicate an array of style properties which should be hidden from the style manager. Default: `[]`
 * @property {Boolean} [highlightable=true] It can be highlighted with 'dotted' borders if true. Default: `true`
 * @property {Boolean} [copyable=true] True if it's possible to clone the component. Default: `true`
 * @property {Boolean} [resizable=false] Indicates if it's possible to resize the component. It's also possible to pass an object as [options for the Resizer](https://github.com/GrapesJS/grapesjs/blob/master/src/utils/Resizer.ts). Default: `false`
 * @property {Boolean} [editable=false] Allow to edit the content of the component (used on Text components). Default: `false`
 * @property {Boolean} [layerable=true] Set to `false` if you need to hide the component inside Layers. Default: `true`
 * @property {Boolean} [selectable=true] Allow component to be selected when clicked. Default: `true`
 * @property {Boolean} [hoverable=true] Shows a highlight outline when hovering on the element if `true`. Default: `true`
 * @property {Boolean} [locked] Disable the selection of the component and its children in the canvas. You can unlock a children by setting its locked property to `false`. Default: `undefined`
 * @property {Boolean} [void=false] This property is used by the HTML exporter as void elements don't have closing tags, eg. `<br/>`, `<hr/>`, etc. Default: `false`
 * @property {Object} [style={}] Component default style, eg. `{ width: '100px', height: '100px', 'background-color': 'red' }`
 * @property {String} [styles=''] Component related styles, eg. `.my-component-class { color: red }`
 * @property {String} [content=''] Content of the component (not escaped) which will be appended before children rendering. Default: `''`
 * @property {String} [icon=''] Component's icon, this string will be inserted before the name (in Layers and badge), eg. it can be an HTML string '<i class="fa fa-square-o"></i>'. Default: `''`
 * @property {String|Function} [script=''] Component's javascript. More about it [here](/modules/Components-js.html). Default: `''`
 * @property {String|Function} [script-export=''] You can specify javascript available only in export functions (eg. when you get the HTML).
 * If this property is defined it will overwrite the `script` one (in export functions). Default: `''`
 * @property {Array<Object|String>} [traits=''] Component's traits. More about it [here](/modules/Traits.html). Default: `['id', 'title']`
 * @property {Array<String>} [propagate=[]] Indicates an array of properties which will be inhereted by all NEW appended children.
 *  For example if you create a component likes this: `{ removable: false, draggable: false, propagate: ['removable', 'draggable'] }`
 *  and append some new component inside, the new added component will get the exact same properties indicated in the `propagate` array (and the `propagate` property itself). Default: `[]`
 * @property {Array<Object>} [toolbar=null] Set an array of items to show up inside the toolbar when the component is selected (move, clone, delete).
 * Eg. `toolbar: [ { attributes: {class: 'fa fa-arrows'}, command: 'tlb-move' }, ... ]`.
 * By default, when `toolbar` property is falsy the editor will add automatically commands `core:component-exit` (select parent component, added if there is one), `tlb-move` (added if `draggable`) , `tlb-clone` (added if `copyable`), `tlb-delete` (added if `removable`).
 * @property {Collection<Component>} [components=null] Children components. Default: `null`
 * @property {Object} [delegate=null] Delegate commands to other components. Available commands `remove` | `move` | `copy` | `select`. eg. `{ remove: (cmp) => cmp.closestType('other-type') }`
 *
 * @module docsjs.Component
 */
var Component = /** @class */ (function (_super) {
    Component_extends(Component, _super);
    function Component() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(Component.prototype, "defaults", {
        /**
         * @private
         * @ts-ignore */
        get: function () {
            var _a;
            return _a = {
                    tagName: 'div',
                    type: '',
                    name: '',
                    removable: true,
                    draggable: true,
                    droppable: true,
                    badgable: true,
                    stylable: true,
                    'stylable-require': '',
                    'style-signature': '',
                    unstylable: '',
                    highlightable: true,
                    copyable: true,
                    resizable: false,
                    editable: false,
                    layerable: true,
                    selectable: true,
                    hoverable: true,
                    void: false,
                    state: '',
                    status: '',
                    content: '',
                    icon: '',
                    style: '',
                    styles: '',
                    classes: '',
                    script: '',
                    'script-props': '',
                    'script-export': '',
                    attributes: {},
                    traits: ['id', 'title'],
                    propagate: '',
                    dmode: '',
                    toolbar: null,
                    delegate: null
                },
                _a[keySymbol] = 0,
                _a[keySymbols] = 0,
                _a[keySymbolOvrd] = 0,
                _a._undo = true,
                _a._undoexc = ['status', 'open'],
                _a;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Component.prototype, "classes", {
        get: function () {
            return this.get('classes');
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Component.prototype, "traits", {
        get: function () {
            return this.get('traits');
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Component.prototype, "content", {
        get: function () {
            var _a;
            return (_a = this.get('content')) !== null && _a !== void 0 ? _a : '';
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Component.prototype, "toolbar", {
        get: function () {
            return this.get('toolbar') || [];
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Component.prototype, "resizable", {
        get: function () {
            return this.get('resizable');
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Component.prototype, "delegate", {
        get: function () {
            return this.get('delegate');
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Component.prototype, "locked", {
        get: function () {
            return this.get('locked');
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Hook method, called once the model is created
     */
    Component.prototype.init = function () { };
    /**
     * Hook method, called when the model has been updated (eg. updated some model's property)
     * @param {String} property Property name, if triggered after some property update
     * @param {*} value Property value, if triggered after some property update
     * @param {*} previous Property previous value, if triggered after some property update
     */
    Component.prototype.updated = function (property, value, previous) { };
    /**
     * Hook method, called once the model has been removed
     */
    Component.prototype.removed = function () { };
    Component.prototype.initialize = function (props, opt) {
        var _this = this;
        if (props === void 0) { props = {}; }
        if (opt === void 0) { opt = {}; }
        (0,index_all.bindAll)(this, '__upSymbProps', '__upSymbCls', '__upSymbComps');
        var em = opt.em;
        // Propagate properties from parent if indicated
        var parent = this.parent();
        var parentAttr = parent === null || parent === void 0 ? void 0 : parent.attributes;
        var propagate = this.get('propagate');
        propagate && this.set('propagate', (0,index_all.isArray)(propagate) ? propagate : [propagate]);
        if (parentAttr && parentAttr.propagate && !propagate) {
            var newAttr_1 = {};
            var toPropagate = parentAttr.propagate;
            toPropagate.forEach(function (prop) { return (newAttr_1[prop] = parent.get(prop)); });
            newAttr_1.propagate = toPropagate;
            this.set(Component_assign(Component_assign({}, newAttr_1), props));
        }
        // Check void elements
        if (opt && opt.config && opt.config.voidElements.indexOf(this.get('tagName')) >= 0) {
            this.set('void', true);
        }
        opt.em = em;
        this.opt = opt;
        this.em = em;
        this.frame = opt.frame;
        this.config = opt.config || {};
        this.set('attributes', Component_assign(Component_assign({}, ((0,index_all.result)(this, 'defaults').attributes || {})), (this.get('attributes') || {})));
        this.ccid = Component.createId(this, opt);
        this.initClasses();
        this.initComponents();
        this.initTraits();
        this.initToolbar();
        this.initScriptProps();
        this.listenTo(this, 'change:script', this.scriptUpdated);
        this.listenTo(this, 'change:tagName', this.tagUpdated);
        this.listenTo(this, 'change:attributes', this.attrUpdated);
        this.listenTo(this, 'change:attributes:id', this._idUpdated);
        this.on('change:toolbar', this.__emitUpdateTlb);
        this.on('change', this.__onChange);
        this.on(keyUpdateInside, this.__propToParent);
        this.set('status', '');
        this.views = [];
        // Register global updates for collection properties
        ['classes', 'traits', 'components'].forEach(function (name) {
            var events = "add remove ".concat(name !== 'components' ? 'change' : '');
            _this.listenTo(_this.get(name), events.trim(), function () {
                var args = [];
                for (var _i = 0; _i < arguments.length; _i++) {
                    args[_i] = arguments[_i];
                }
                return _this.emitUpdate.apply(_this, Component_spreadArray([name], args, false));
            });
        });
        if (!opt.temporary) {
            // Add component styles
            var cssc = em && em.Css;
            var _a = this.attributes, styles = _a.styles, type = _a.type;
            if (styles && cssc) {
                cssc.addCollection(styles, { avoidUpdateStyle: true }, { group: "cmp:".concat(type) });
            }
            this.__postAdd();
            this.init();
            this.__isSymbolOrInst() && this.__initSymb();
            em && em.trigger('component:create', this);
        }
    };
    Component.prototype.__postAdd = function (opts) {
        if (opts === void 0) { opts = {}; }
        var em = this.em;
        var um = em === null || em === void 0 ? void 0 : em.UndoManager;
        var comps = this.components();
        if (um && !this.__hasUm) {
            um.add(comps);
            um.add(this.getSelectors());
            this.__hasUm = true;
        }
        opts.recursive && comps.map(function (c) { return c.__postAdd(opts); });
    };
    Component.prototype.__postRemove = function () {
        var em = this.em;
        var um = em === null || em === void 0 ? void 0 : em.get('UndoManager');
        if (um) {
            um.remove(this.components());
            um.remove(this.getSelectors());
            delete this.__hasUm;
        }
    };
    Component.prototype.__onChange = function (m, opts) {
        var _this = this;
        var changed = this.changedAttributes() || {};
        (0,index_all.keys)(changed).forEach(function (prop) { return _this.emitUpdate(prop); });
        ['status', 'open', 'toolbar', 'traits'].forEach(function (name) { return delete changed[name]; });
        // Propagate component prop changes
        if (!(0,mixins.isEmptyObj)(changed)) {
            this.__changesUp(opts);
            this.__propSelfToParent({ component: this, changed: changed, options: opts });
        }
    };
    Component.prototype.__onStyleChange = function (newStyles) {
        var _this = this;
        var em = this.em;
        if (!em)
            return;
        var event = 'component:styleUpdate';
        var styleKeys = (0,index_all.keys)(newStyles);
        var pros = { style: newStyles };
        em.trigger(event, this, pros);
        styleKeys.forEach(function (key) { return em.trigger("".concat(event, ":").concat(key), _this, pros); });
    };
    Component.prototype.__changesUp = function (opts) {
        var _a = this, em = _a.em, frame = _a.frame;
        [frame, em].forEach(function (md) { return md && md.changesUp(opts); });
    };
    Component.prototype.__propSelfToParent = function (props) {
        this.trigger(keyUpdate, props);
        this.__propToParent(props);
    };
    Component.prototype.__propToParent = function (props) {
        var parent = this.parent();
        parent && parent.trigger(keyUpdateInside, props);
    };
    Component.prototype.__emitUpdateTlb = function () {
        this.emitUpdate('toolbar');
    };
    /**
     * Check component's type
     * @param  {string}  type Component type
     * @return {Boolean}
     * @example
     * component.is('image')
     * // -> false
     */
    Component.prototype.is = function (type) {
        return !!(this.get('type') == type);
    };
    /**
     * Return all the propeties
     * @returns {Object}
     */
    Component.prototype.props = function () {
        return this.attributes;
    };
    /**
     * Get the index of the component in the parent collection.
     * @return {Number}
     */
    Component.prototype.index = function () {
        var collection = this.collection;
        return collection ? collection.indexOf(this) : 0;
    };
    /**
     * Change the drag mode of the component.
     * To get more about this feature read: https://github.com/GrapesJS/grapesjs/issues/1936
     * @param {String} value Drag mode, options: `'absolute'` | `'translate'` | `''`
     * @returns {this}
     */
    Component.prototype.setDragMode = function (value) {
        return this.set('dmode', value);
    };
    /**
     * Get the drag mode of the component.
     * @returns {String} Drag mode value, options: `'absolute'` | `'translate'` | `''`
     */
    Component.prototype.getDragMode = function () {
        return this.get('dmode') || '';
    };
    /**
     * Find inner components by query string.
     * **ATTENTION**: this method works only with already rendered component
     * @param  {String} query Query string
     * @return {Array} Array of components
     * @example
     * component.find('div > .class');
     * // -> [Component, Component, ...]
     */
    Component.prototype.find = function (query) {
        var _a;
        var result = [];
        var $els = (_a = this.view) === null || _a === void 0 ? void 0 : _a.$el.find(query);
        $els === null || $els === void 0 ? void 0 : $els.each(function (i) {
            var $el = $els.eq(i);
            var model = $el.data('model');
            model && result.push(model);
        });
        return result;
    };
    /**
     * Find all inner components by component type.
     * The advantage of this method over `find` is that you can use it
     * also before rendering the component
     * @param {String} type Component type
     * @returns {Array<Component>}
     * @example
     * const allImages = component.findType('image');
     * console.log(allImages[0]) // prints the first found component
     */
    Component.prototype.findType = function (type) {
        var result = [];
        var find = function (components) {
            return components.forEach(function (item) {
                item.is(type) && result.push(item);
                find(item.components());
            });
        };
        find(this.components());
        return result;
    };
    /**
     * Find the closest parent component by query string.
     * **ATTENTION**: this method works only with already rendered component
     * @param  {string} query Query string
     * @return {Component}
     * @example
     * component.closest('div.some-class');
     * // -> Component
     */
    Component.prototype.closest = function (query) {
        var _a;
        var result = (_a = this.view) === null || _a === void 0 ? void 0 : _a.$el.closest(query);
        return (result === null || result === void 0 ? void 0 : result.length) ? result.data('model') : undefined;
    };
    /**
     * Find the closest parent component by its type.
     * The advantage of this method over `closest` is that you can use it
     * also before rendering the component
     * @param {String} type Component type
     * @returns {Component} Found component, otherwise `undefined`
     * @example
     * const Section = component.closestType('section');
     * console.log(Section);
     */
    Component.prototype.closestType = function (type) {
        var parent = this.parent();
        while (parent && !parent.is(type)) {
            parent = parent.parent();
        }
        return parent;
    };
    /**
     * The method returns a Boolean value indicating whether the passed
     * component is a descendant of a given component
     * @param {Component} component Component to check
     * @returns {Boolean}
     */
    Component.prototype.contains = function (component) {
        var result = !1;
        if (!component)
            return result;
        var contains = function (components) {
            !result &&
                components.forEach(function (item) {
                    if (item === component)
                        result = !0;
                    !result && contains(item.components());
                });
        };
        contains(this.components());
        return result;
    };
    /**
     * Once the tag is updated I have to rerender the element
     * @private
     */
    Component.prototype.tagUpdated = function () {
        this.trigger('rerender');
    };
    /**
     * Replace a component with another one
     * @param {String|Component} el Component or HTML string
     * @param {Object} [opts={}] Options for the append action
     * @returns {Array<Component>} New replaced components
     * @example
     * const result = component.replaceWith('<div>Some new content</div>');
     * // result -> [Component]
     */
    Component.prototype.replaceWith = function (el, opts) {
        if (opts === void 0) { opts = {}; }
        var coll = this.collection;
        var at = coll.indexOf(this);
        coll.remove(this);
        var result = coll.add(el, Component_assign(Component_assign({}, opts), { at: at }));
        return (0,index_all.isArray)(result) ? result : [result];
    };
    /**
     * Emit changes for each updated attribute
     * @private
     */
    Component.prototype.attrUpdated = function (m, v, opts) {
        var _this = this;
        if (opts === void 0) { opts = {}; }
        var attrs = this.get('attributes');
        // Handle classes
        var classes = attrs.class;
        classes && this.setClass(classes);
        delete attrs.class;
        // Handle style
        var style = attrs.style;
        style && this.setStyle(style);
        delete attrs.style;
        var attrPrev = Component_assign({}, this.previous('attributes'));
        var diff = (0,mixins.shallowDiff)(attrPrev, this.get('attributes'));
        (0,index_all.keys)(diff).forEach(function (pr) { return _this.trigger("change:attributes:".concat(pr), _this, diff[pr], opts); });
    };
    /**
     * Update attributes of the component
     * @param {Object} attrs Key value attributes
     * @param {Object} options Options for the model update
     * @return {this}
     * @example
     * component.setAttributes({ id: 'test', 'data-key': 'value' });
     */
    Component.prototype.setAttributes = function (attrs, opts) {
        if (opts === void 0) { opts = {}; }
        this.set('attributes', Component_assign({}, attrs), opts);
        return this;
    };
    /**
     * Add attributes to the component
     * @param {Object} attrs Key value attributes
     * @param {Object} options Options for the model update
     * @return {this}
     * @example
     * component.addAttributes({ 'data-key': 'value' });
     */
    Component.prototype.addAttributes = function (attrs, opts) {
        if (opts === void 0) { opts = {}; }
        return this.setAttributes(Component_assign(Component_assign({}, this.getAttributes({ noClass: true })), attrs), opts);
    };
    /**
     * Remove attributes from the component
     * @param {String|Array<String>} attrs Array of attributes to remove
     * @param {Object} options Options for the model update
     * @return {this}
     * @example
     * component.removeAttributes('some-attr');
     * component.removeAttributes(['some-attr1', 'some-attr2']);
     */
    Component.prototype.removeAttributes = function (attrs, opts) {
        if (attrs === void 0) { attrs = []; }
        if (opts === void 0) { opts = {}; }
        var attrArr = Array.isArray(attrs) ? attrs : [attrs];
        var compAttr = this.getAttributes();
        attrArr.map(function (i) { return delete compAttr[i]; });
        return this.setAttributes(compAttr, opts);
    };
    /**
     * Get the style of the component
     * @return {Object}
     */
    Component.prototype.getStyle = function (options, optsAdd) {
        if (options === void 0) { options = {}; }
        if (optsAdd === void 0) { optsAdd = {}; }
        var em = this.em;
        var prop = (0,index_all.isString)(options) ? options : '';
        var opts = prop ? optsAdd : options;
        if (avoidInline(em) && !opts.inline) {
            var state = em.get('state');
            var cc = em.Css;
            var rule = cc.getIdRule(this.getId(), Component_assign({ state: state }, opts));
            this.rule = rule;
            if (rule) {
                return rule.getStyle(prop);
            }
        }
        return _super.prototype.getStyle.call(this, prop);
    };
    /**
     * Set the style on the component
     * @param {Object} prop Key value style object
     * @return {Object}
     * @example
     * component.setStyle({ color: 'red' });
     */
    Component.prototype.setStyle = function (prop, opts) {
        var _this = this;
        if (prop === void 0) { prop = {}; }
        if (opts === void 0) { opts = {}; }
        var _a = this, opt = _a.opt, em = _a.em;
        if (avoidInline(em) && !opt.temporary && !opts.inline) {
            var style = this.get('style') || {};
            prop = (0,index_all.isString)(prop) ? this.parseStyle(prop) : prop;
            prop = Component_assign(Component_assign({}, prop), style);
            var state = em.get('state');
            var cc = em.Css;
            var propOrig = this.getStyle(opts);
            this.rule = cc.setIdRule(this.getId(), prop, Component_assign({ state: state }, opts));
            var diff = (0,mixins.shallowDiff)(propOrig, prop);
            this.set('style', '', { silent: true });
            (0,index_all.keys)(diff).forEach(function (pr) { return _this.trigger("change:style:".concat(pr)); });
        }
        else {
            prop = _super.prototype.setStyle.apply(this, arguments);
        }
        if (!opt.temporary) {
            this.__onStyleChange(opts.addStyle || prop);
        }
        return prop;
    };
    /**
     * Return all component's attributes
     * @return {Object}
     */
    Component.prototype.getAttributes = function (opts) {
        if (opts === void 0) { opts = {}; }
        var em = this.em;
        var classes = [];
        var attributes = Component_assign({}, this.get('attributes'));
        var sm = em === null || em === void 0 ? void 0 : em.Selectors;
        var id = this.getId();
        // Add classes
        if (opts.noClass) {
            delete attributes.class;
        }
        else {
            this.classes.forEach(function (cls) { return classes.push((0,index_all.isString)(cls) ? cls : cls.getName()); });
            classes.length && (attributes.class = classes.join(' '));
        }
        // Add style
        if (!opts.noStyle) {
            var style = this.get('style');
            if ((0,mixins.isObject)(style) && !(0,mixins.isEmptyObj)(style)) {
                attributes.style = this.styleToString({ inline: 1 });
            }
        }
        // Check if we need an ID on the component
        if (!(0,index_all.has)(attributes, 'id')) {
            var addId = false;
            // If we don't rely on inline styling we have to check
            // for the ID selector
            if (avoidInline(em) || !(0,index_all.isEmpty)(this.getStyle())) {
                addId = !!(sm === null || sm === void 0 ? void 0 : sm.get(id, sm.Selector.TYPE_ID));
            }
            if (
            // Symbols should always have an id
            this.__getSymbol() ||
                this.__getSymbols() ||
                // Components with script should always have an id
                this.get('script-export') ||
                this.get('script')) {
                addId = true;
            }
            if (addId) {
                attributes.id = id;
            }
        }
        return attributes;
    };
    /**
     * Add classes
     * @param {Array<String>|String} classes Array or string of classes
     * @return {Array} Array of added selectors
     * @example
     * model.addClass('class1');
     * model.addClass('class1 class2');
     * model.addClass(['class1', 'class2']);
     * // -> [SelectorObject, ...]
     */
    Component.prototype.addClass = function (classes) {
        var added = this.em.Selectors.addClass(classes);
        return this.classes.add(added);
    };
    /**
     * Set classes (resets current collection)
     * @param {Array<String>|String} classes Array or string of classes
     * @return {Array} Array of added selectors
     * @example
     * model.setClass('class1');
     * model.setClass('class1 class2');
     * model.setClass(['class1', 'class2']);
     * // -> [SelectorObject, ...]
     */
    Component.prototype.setClass = function (classes) {
        this.classes.reset();
        return this.addClass(classes);
    };
    /**
     * Remove classes
     * @param {Array<String>|String} classes Array or string of classes
     * @return {Array} Array of removed selectors
     * @example
     * model.removeClass('class1');
     * model.removeClass('class1 class2');
     * model.removeClass(['class1', 'class2']);
     * // -> [SelectorObject, ...]
     */
    Component.prototype.removeClass = function (classes) {
        var removed = [];
        classes = (0,index_all.isArray)(classes) ? classes : [classes];
        var selectors = this.classes;
        var type = model_Selector.TYPE_CLASS;
        classes.forEach(function (classe) {
            var classes = classe.split(' ');
            classes.forEach(function (name) {
                var selector = selectors.where({ name: name, type: type })[0];
                selector && removed.push(selectors.remove(selector));
            });
        });
        return removed;
    };
    /**
     * Returns component's classes as an array of strings
     * @return {Array}
     */
    Component.prototype.getClasses = function () {
        var attr = this.getAttributes();
        var classStr = attr.class;
        return classStr ? classStr.split(' ') : [];
    };
    Component.prototype.__logSymbol = function (type, toUp, opts) {
        if (opts === void 0) { opts = {}; }
        var symbol = this.__getSymbol();
        var symbols = this.__getSymbols();
        if (!symbol && !symbols)
            return;
        this.em.log(type, { model: this, toUp: toUp, context: 'symbols', opts: opts });
    };
    Component.prototype.__initSymb = function () {
        if (this.__symbReady)
            return;
        this.on('change', this.__upSymbProps);
        this.__symbReady = true;
    };
    Component.prototype.__isSymbol = function () {
        return (0,index_all.isArray)(this.get(keySymbols));
    };
    Component.prototype.__isSymbolOrInst = function () {
        return !!(this.__isSymbol() || this.get(keySymbol));
    };
    Component.prototype.__isSymbolTop = function () {
        var parent = this.parent();
        var symb = this.__isSymbolOrInst();
        return symb && (!parent || (parent && !parent.__isSymbol() && !parent.__getSymbol()));
    };
    Component.prototype.__isSymbolNested = function () {
        if (!this.__isSymbolOrInst() || this.__isSymbolTop())
            return false;
        var symbTopSelf = (this.__isSymbol() ? this : this.__getSymbol()).__getSymbTop();
        var symbTop = this.__getSymbTop();
        var symbTopMain = symbTop.__isSymbol() ? symbTop : symbTop.__getSymbol();
        return symbTopMain !== symbTopSelf;
    };
    Component.prototype.__getAllById = function () {
        var em = this.em;
        return em ? em.Components.allById() : {};
    };
    Component.prototype.__getSymbol = function () {
        var symb = this.get(keySymbol);
        if (symb && (0,index_all.isString)(symb)) {
            var ref = this.__getAllById()[symb];
            if (ref) {
                symb = ref;
                this.set(keySymbol, ref);
            }
            else {
                symb = 0;
            }
        }
        return symb;
    };
    Component.prototype.__getSymbols = function () {
        var _this = this;
        var symbs = this.get(keySymbols);
        if (symbs && (0,index_all.isArray)(symbs)) {
            symbs.forEach(function (symb, idx) {
                if (symb && (0,index_all.isString)(symb)) {
                    symbs[idx] = _this.__getAllById()[symb];
                }
            });
            symbs = symbs.filter(function (symb) { return symb && !(0,index_all.isString)(symb); });
        }
        return symbs;
    };
    Component.prototype.__isSymbOvrd = function (prop) {
        if (prop === void 0) { prop = ''; }
        var ovrd = this.get(keySymbolOvrd);
        var prp = prop.split(':')[0];
        var props = prop !== prp ? [prop, prp] : [prop];
        return ovrd === true || ((0,index_all.isArray)(ovrd) && props.some(function (p) { return ovrd.indexOf(p) >= 0; }));
    };
    Component.prototype.__getSymbToUp = function (opts) {
        var _this = this;
        if (opts === void 0) { opts = {}; }
        var result = [];
        var changed = opts.changed;
        if (opts.fromInstance ||
            opts.noPropagate ||
            opts.fromUndo ||
            // Avoid updating others if the current component has override
            (changed && this.__isSymbOvrd(changed))) {
            return result;
        }
        var symbols = this.__getSymbols() || [];
        var symbol = this.__getSymbol();
        var all = symbol ? Component_spreadArray([symbol], (symbol.__getSymbols() || []), true) : symbols;
        result = all
            .filter(function (s) { return s !== _this; })
            // Avoid updating those with override
            .filter(function (s) { return !(changed && s.__isSymbOvrd(changed)); });
        return result;
    };
    Component.prototype.__getSymbTop = function (opts) {
        var result = this;
        var parent = this.parent(opts);
        while (parent && (parent.__isSymbol() || parent.__getSymbol())) {
            result = parent;
            parent = parent.parent(opts);
        }
        return result;
    };
    Component.prototype.__upSymbProps = function (m, opts) {
        var _this = this;
        if (opts === void 0) { opts = {}; }
        var changed = this.changedAttributes() || {};
        var attrs = changed.attributes || {};
        delete changed.status;
        delete changed.open;
        delete changed[keySymbols];
        delete changed[keySymbol];
        delete changed[keySymbolOvrd];
        delete changed.attributes;
        delete attrs.id;
        if (!(0,mixins.isEmptyObj)(attrs))
            changed.attributes = attrs;
        if (!(0,mixins.isEmptyObj)(changed)) {
            var toUp = this.__getSymbToUp(opts);
            // Avoid propagating overrides to other symbols
            (0,index_all.keys)(changed).map(function (prop) {
                if (_this.__isSymbOvrd(prop))
                    delete changed[prop];
            });
            this.__logSymbol('props', toUp, { opts: opts, changed: changed });
            toUp.forEach(function (child) {
                var propsChanged = Component_assign({}, changed);
                // Avoid updating those with override
                (0,index_all.keys)(propsChanged).map(function (prop) {
                    if (child.__isSymbOvrd(prop))
                        delete propsChanged[prop];
                });
                child.set(propsChanged, Component_assign({ fromInstance: _this }, opts));
            });
        }
    };
    Component.prototype.__upSymbCls = function (m, c, opts) {
        var _this = this;
        if (opts === void 0) { opts = {}; }
        var toUp = this.__getSymbToUp(opts);
        this.__logSymbol('classes', toUp, { opts: opts });
        toUp.forEach(function (child) {
            // @ts-ignore This will propagate the change up to __upSymbProps
            child.set('classes', _this.get('classes'), { fromInstance: _this });
        });
        this.__changesUp(opts);
    };
    Component.prototype.__upSymbComps = function (m, c, o) {
        var _this = this;
        var optUp = o || c || {};
        var fromInstance = optUp.fromInstance, fromUndo = optUp.fromUndo;
        var toUpOpts = { fromInstance: fromInstance, fromUndo: fromUndo };
        var isTemp = m.opt.temporary;
        // Reset
        if (!o) {
            var toUp = this.__getSymbToUp(Component_assign(Component_assign({}, toUpOpts), { changed: 'components:reset' }));
            // @ts-ignore
            var cmps_1 = m.models;
            this.__logSymbol('reset', toUp, { components: cmps_1 });
            toUp.forEach(function (symb) {
                var newMods = cmps_1.map(function (mod) { return mod.clone({ symbol: true }); });
                // @ts-ignore
                symb.components().reset(newMods, Component_assign({ fromInstance: _this }, c));
            });
            // Add
        }
        else if (o.add) {
            var addedInstances_1 = [];
            var isMainSymb_1 = !!this.__getSymbols();
            var toUp = this.__getSymbToUp(Component_assign(Component_assign({}, toUpOpts), { changed: 'components:add' }));
            if (toUp.length) {
                var addSymb = m.__getSymbol();
                addedInstances_1 = (addSymb ? addSymb.__getSymbols() : m.__getSymbols()) || [];
                addedInstances_1 = Component_spreadArray([], addedInstances_1, true);
                addedInstances_1.push(addSymb ? addSymb : m);
            }
            !isTemp &&
                this.__logSymbol('add', toUp, {
                    opts: o,
                    addedInstances: addedInstances_1.map(function (c) { return c.cid; }),
                    added: m.cid,
                });
            // Here, before appending a new symbol, I have to ensure there are no previously
            // created symbols (eg. used mainly when drag components around)
            toUp.forEach(function (symb) {
                var symbTop = symb.__getSymbTop();
                var symbPrev = addedInstances_1.filter(function (addedInst) {
                    var addedTop = addedInst.__getSymbTop({ prev: 1 });
                    return symbTop && addedTop && addedTop === symbTop;
                })[0];
                var toAppend = symbPrev || m.clone({ symbol: true, symbolInv: isMainSymb_1 });
                symb.append(toAppend, Component_assign({ fromInstance: _this }, o));
            });
            // Remove
        }
        else {
            // Remove instance reference from the symbol
            var symb = m.__getSymbol();
            symb &&
                !o.temporary &&
                symb.set(keySymbols, symb.__getSymbols().filter(function (i) { return i !== m; }));
            // Propagate remove only if the component is an inner symbol
            if (!m.__isSymbolTop()) {
                var changed_1 = 'components:remove';
                var index_1 = o.index;
                var parent_1 = m.parent();
                var opts_1 = Component_assign({ fromInstance: m }, o);
                var isSymbNested = m.__isSymbolNested();
                var toUpFn = function (symb) {
                    var symbPrnt = symb.parent();
                    symbPrnt && !symbPrnt.__isSymbOvrd(changed_1) && symb.remove(opts_1);
                };
                // Check if the parent allows the removing
                var toUp = !(parent_1 === null || parent_1 === void 0 ? void 0 : parent_1.__isSymbOvrd(changed_1)) ? m.__getSymbToUp(toUpOpts) : [];
                if (isSymbNested) {
                    toUp = parent_1 === null || parent_1 === void 0 ? void 0 : parent_1.__getSymbToUp(Component_assign(Component_assign({}, toUpOpts), { changed: changed_1 }));
                    toUpFn = function (symb) {
                        var toRemove = symb.components().at(index_1);
                        toRemove && toRemove.remove(Component_assign({ fromInstance: parent_1 }, opts_1));
                    };
                }
                !isTemp &&
                    this.__logSymbol('remove', toUp, {
                        opts: o,
                        removed: m.cid,
                        isSymbNested: isSymbNested,
                    });
                toUp.forEach(toUpFn);
            }
        }
        this.__changesUp(optUp);
    };
    Component.prototype.initClasses = function (m, c, opts) {
        if (opts === void 0) { opts = {}; }
        var event = 'change:classes';
        var _a = this.get('attributes') || {}, attrCls = _a.class, restAttr = Component_rest(_a, ["class"]);
        var toListen = [this, event, this.initClasses];
        var cls = this.get('classes') || attrCls || [];
        var clsArr = (0,index_all.isString)(cls) ? cls.split(' ') : cls;
        this.stopListening.apply(this, toListen);
        var classes = this.normalizeClasses(clsArr);
        var selectors = new model_Selectors([]);
        this.set('classes', selectors, opts);
        selectors.add(classes);
        selectors.on('add remove reset', this.__upSymbCls);
        // Clear attributes from classes
        attrCls && classes.length && this.set('attributes', restAttr);
        // @ts-ignore
        this.listenTo.apply(this, toListen);
        return this;
    };
    Component.prototype.initComponents = function () {
        var event = 'change:components';
        var toListen = [this, event, this.initComponents];
        this.stopListening.apply(this, toListen);
        // Have to add components after the init, otherwise the parent
        // is not visible
        var comps = new model_Components([], this.opt);
        comps.parent = this;
        var components = this.get('components');
        var addChild = !this.opt.avoidChildren;
        this.set('components', comps);
        addChild && components && comps.add((0,index_all.isFunction)(components) ? components(this) : components, this.opt);
        comps.on('add remove reset', this.__upSymbComps);
        // @ts-ignore
        this.listenTo.apply(this, toListen);
        return this;
    };
    Component.prototype.initTraits = function (changed) {
        var em = this.em;
        var event = 'change:traits';
        this.off(event, this.initTraits);
        this.__loadTraits();
        var attrs = Component_assign({}, this.get('attributes'));
        var traits = this.traits;
        traits.each(function (trait) {
            if (!trait.changeProp) {
                var name_1 = trait.getName();
                var value = trait.getInitValue();
                if (name_1 && value)
                    attrs[name_1] = value;
            }
        });
        traits.length && this.set('attributes', attrs);
        this.on(event, this.initTraits);
        changed && em && em.trigger('component:toggled');
        return this;
    };
    Component.prototype.initScriptProps = function () {
        if (this.opt.temporary)
            return;
        var prop = 'script-props';
        var toListen = ["change:".concat(prop), this.initScriptProps];
        this.off.apply(this, toListen);
        var prevProps = this.previous(prop) || [];
        var newProps = this.get(prop) || [];
        var prevPropsEv = prevProps.map(function (e) { return "change:".concat(e); }).join(' ');
        var newPropsEv = newProps.map(function (e) { return "change:".concat(e); }).join(' ');
        prevPropsEv && this.off(prevPropsEv, this.__scriptPropsChange);
        newPropsEv && this.on(newPropsEv, this.__scriptPropsChange);
        // @ts-ignore
        this.on.apply(this, toListen);
    };
    Component.prototype.__scriptPropsChange = function (m, v, opts) {
        if (opts === void 0) { opts = {}; }
        if (opts.avoidStore)
            return;
        this.trigger('rerender');
    };
    /**
     * Add new component children
     * @param  {Component|String} components Component to add
     * @param {Object} [opts={}] Options for the append action
     * @return {Array} Array of appended components
     * @example
     * someComponent.get('components').length // -> 0
     * const videoComponent = someComponent.append('<video></video><div></div>')[0];
     * // This will add 2 components (`video` and `div`) to your `someComponent`
     * someComponent.get('components').length // -> 2
     * // You can pass components directly
     * otherComponent.append(otherComponent2);
     * otherComponent.append([otherComponent3, otherComponent4]);
     * // append at specific index (eg. at the beginning)
     * someComponent.append(otherComponent, { at: 0 });
     */
    Component.prototype.append = function (components, opts) {
        if (opts === void 0) { opts = {}; }
        var compArr = (0,index_all.isArray)(components) ? Component_spreadArray([], components, true) : [components];
        var toAppend = compArr.map(function (comp) {
            if ((0,index_all.isString)(comp)) {
                return comp;
            }
            else {
                // I have to remove components from the old container before adding them to a new one
                comp.collection && comp.collection.remove(comp, { temporary: true });
                return comp;
            }
        });
        var result = this.components().add(toAppend, opts);
        return (0,index_all.isArray)(result) ? result : [result];
    };
    /**
     * Set new collection if `components` are provided, otherwise the
     * current collection is returned
     * @param  {Component|Component[]|String} [components] Component Definitions or HTML string
     * @param {Object} [opts={}] Options, same as in `Component.append()`
     * @returns {Collection|Array<[Component]>}
     * @example
     * // Set new collection
     * component.components('<span></span><div></div>');
     * // Get current collection
     * const collection = component.components();
     * console.log(collection.length);
     * // -> 2
     */
    Component.prototype.components = function (components, opts) {
        if (opts === void 0) { opts = {}; }
        var coll = this.get('components');
        if ((0,index_all.isUndefined)(components)) {
            return coll;
        }
        else {
            coll.reset(undefined, opts);
            return components ? this.append(components, opts) : [];
        }
    };
    /**
     * If exists, returns the child component at specific index.
     * @param {Number} index Index of the component to return
     * @returns {[Component]|null}
     * @example
     * // Return first child
     * component.getChildAt(0);
     * // Return second child
     * component.getChildAt(1);
     */
    Component.prototype.getChildAt = function (index) {
        return this.components().at(index || 0) || undefined;
    };
    /**
     * If exists, returns the last child component.
     * @returns {[Component]|null}
     * @example
     * const lastChild = component.getLastChild();
     */
    Component.prototype.getLastChild = function () {
        var children = this.components();
        return children.at(children.length - 1) || null;
    };
    /**
     * Remove all inner components
     * * @return {this}
     */
    Component.prototype.empty = function (opts) {
        if (opts === void 0) { opts = {}; }
        this.components().reset(undefined, opts);
        return this;
    };
    /**
     * Get the parent component, if exists
     * @return {Component|null}
     * @example
     * component.parent();
     * // -> Component
     */
    Component.prototype.parent = function (opts) {
        if (opts === void 0) { opts = {}; }
        var coll = this.collection || (opts.prev && this.prevColl);
        return coll ? coll.parent : undefined;
    };
    /**
     * Return all parents of the component.
     * @returns {Array<Component>}
     */
    Component.prototype.parents = function () {
        var parent = this.parent();
        return parent ? [parent].concat(parent.parents()) : [];
    };
    /**
     * Script updated
     * @private
     */
    Component.prototype.scriptUpdated = function () {
        this.set('scriptUpdated', 1);
    };
    /**
     * Init toolbar
     * @private
     */
    Component.prototype.initToolbar = function () {
        var em = this.em;
        var model = this;
        var ppfx = (em && em.getConfig().stylePrefix) || '';
        if (!model.get('toolbar') && em) {
            var tb = [];
            model.collection &&
                tb.push({
                    label: em.getIcon('arrowUp'),
                    command: function (ed) { return ed.runCommand('core:component-exit', { force: 1 }); },
                });
            model.get('draggable') &&
                tb.push({
                    attributes: { class: "".concat(ppfx, "no-touch-actions"), draggable: true },
                    label: em.getIcon('move'),
                    command: 'tlb-move',
                });
            model.get('copyable') &&
                tb.push({
                    label: em.getIcon('copy'),
                    command: 'tlb-clone',
                });
            model.get('removable') &&
                tb.push({
                    label: em.getIcon('delete'),
                    command: 'tlb-delete',
                });
            model.set('toolbar', tb);
        }
    };
    Component.prototype.__loadTraits = function (tr, opts) {
        if (opts === void 0) { opts = {}; }
        var traitsI = tr || this.traits;
        if (!(traitsI instanceof model_Traits)) {
            traitsI = ((0,index_all.isFunction)(traitsI) ? traitsI(this) : traitsI);
            var traits = new model_Traits([], this.opt);
            traits.setTarget(this);
            if (traitsI.length) {
                traitsI.forEach(function (tr) { return tr.attributes && delete tr.attributes.value; });
                traits.add(traitsI);
            }
            this.set({ traits: traits }, opts);
        }
        return this;
    };
    /**
     * Get traits.
     * @returns {Array<Trait>}
     * @example
     * const traits = component.getTraits();
     * console.log(traits);
     * // [Trait, Trait, Trait, ...]
     */
    Component.prototype.getTraits = function () {
        this.__loadTraits();
        return Component_spreadArray([], this.traits.models, true);
    };
    /**
     * Replace current collection of traits with a new one.
     * @param {Array<Object>} traits Array of trait definitions
     * @returns {Array<Trait>}
     * @example
     * const traits = component.setTraits([{ type: 'checkbox', name: 'disabled'}, ...]);
     * console.log(traits);
     * // [Trait, ...]
     */
    Component.prototype.setTraits = function (traits) {
        var tr = (0,index_all.isArray)(traits) ? traits : [traits];
        // @ts-ignore
        this.set({ traits: tr });
        return this.getTraits();
    };
    /**
     * Get the trait by id/name.
     * @param  {String} id The `id` or `name` of the trait
     * @return {Trait|null} Trait getModelToStyle
     * @example
     * const traitTitle = component.getTrait('title');
     * traitTitle && traitTitle.set('label', 'New label');
     */
    Component.prototype.getTrait = function (id) {
        return (this.getTraits().filter(function (trait) {
            return trait.get('id') === id || trait.get('name') === id;
        })[0] || null);
    };
    /**
     * Update a trait.
     * @param  {String} id The `id` or `name` of the trait
     * @param  {Object} props Object with the props to update
     * @return {this}
     * @example
     * component.updateTrait('title', {
     *  type: 'select',
     *  options: [ 'Option 1', 'Option 2' ],
     * });
     */
    Component.prototype.updateTrait = function (id, props) {
        var _a;
        var trait = this.getTrait(id);
        trait && trait.set(props);
        (_a = this.em) === null || _a === void 0 ? void 0 : _a.trigger('component:toggled');
        return this;
    };
    /**
     * Get the trait position index by id/name. Useful in case you want to
     * replace some trait, at runtime, with something else.
     * @param  {String} id The `id` or `name` of the trait
     * @return {Number} Index position of the current trait
     * @example
     * const traitTitle = component.getTraitIndex('title');
     * console.log(traitTitle); // 1
     */
    Component.prototype.getTraitIndex = function (id) {
        var trait = this.getTrait(id);
        return trait ? this.traits.indexOf(trait) : -1;
    };
    /**
     * Remove trait/s by id/s.
     * @param  {String|Array<String>} id The `id`/`name` of the trait (or an array)
     * @return {Array<Trait>} Array of removed traits
     * @example
     * component.removeTrait('title');
     * component.removeTrait(['title', 'id']);
     */
    Component.prototype.removeTrait = function (id) {
        var _this = this;
        var _a;
        var ids = (0,index_all.isArray)(id) ? id : [id];
        var toRemove = ids.map(function (id) { return _this.getTrait(id); });
        var traits = this.traits;
        var removed = toRemove.length ? traits.remove(toRemove) : [];
        (_a = this.em) === null || _a === void 0 ? void 0 : _a.trigger('component:toggled');
        return (0,index_all.isArray)(removed) ? removed : [removed];
    };
    /**
     * Add new trait/s.
     * @param  {String|Object|Array<String|Object>} trait Trait to add (or an array of traits)
     * @param  {Options} opts Options for the add
     * @return {Array<Trait>} Array of added traits
     * @example
     * component.addTrait('title', { at: 1 }); // Add title trait (`at` option is the position index)
     * component.addTrait({
     *  type: 'checkbox',
     *  name: 'disabled',
     * });
     * component.addTrait(['title', {...}, ...]);
     */
    Component.prototype.addTrait = function (trait, opts) {
        var _a;
        if (opts === void 0) { opts = {}; }
        this.__loadTraits();
        var added = this.traits.add(trait, opts);
        (_a = this.em) === null || _a === void 0 ? void 0 : _a.trigger('component:toggled');
        return (0,index_all.isArray)(added) ? added : [added];
    };
    /**
     * Normalize input classes from array to array of objects
     * @param {Array} arr
     * @return {Array}
     * @private
     */
    Component.prototype.normalizeClasses = function (arr) {
        var res = [];
        var em = this.em;
        var clm = em === null || em === void 0 ? void 0 : em.Selectors;
        if (!clm)
            return [];
        // @ts-ignore
        if (arr.models)
            return Component_spreadArray([], arr.models, true);
        arr.forEach(function (val) { return res.push(clm.add(val)); });
        return res;
    };
    /**
     * Override original clone method
     * @private
     */
    Component.prototype.clone = function (opt) {
        if (opt === void 0) { opt = {}; }
        var em = this.em;
        var attr = Component_assign({}, this.attributes);
        var opts = Component_assign({}, this.opt);
        var id = this.getId();
        var cssc = em === null || em === void 0 ? void 0 : em.Css;
        attr.attributes = Component_assign({}, attr.attributes);
        delete attr.attributes.id;
        // @ts-ignore
        attr.components = [];
        // @ts-ignore
        attr.classes = [];
        // @ts-ignore
        attr.traits = [];
        if (this.__isSymbolTop()) {
            opt.symbol = true;
        }
        this.get('components').each(function (md, i) {
            // @ts-ignore
            attr.components[i] = md.clone(Component_assign(Component_assign({}, opt), { _inner: 1 }));
        });
        this.get('traits').each(function (md, i) {
            // @ts-ignore
            attr.traits[i] = md.clone();
        });
        this.get('classes').each(function (md, i) {
            // @ts-ignore
            attr.classes[i] = md.get('name');
        });
        attr.status = '';
        // @ts-ignore
        opts.collection = null;
        // @ts-ignore
        var cloned = new this.constructor(attr, opts);
        // Clone component specific rules
        var newId = "#".concat(cloned.getId());
        var rulesToClone = cssc ? cssc.getRules("#".concat(id)) : [];
        rulesToClone.forEach(function (rule) {
            var newRule = rule.clone();
            // @ts-ignore
            newRule.set('selectors', [newId]);
            cssc.getAll().add(newRule);
        });
        // Symbols
        // If I clone an inner symbol, I have to reset it
        cloned.set(keySymbols, 0);
        var symbol = this.__getSymbol();
        var symbols = this.__getSymbols();
        if (!opt.symbol && (symbol || symbols)) {
            cloned.set(keySymbol, 0);
            cloned.set(keySymbols, 0);
        }
        else if (symbol) {
            // Contains already a reference to a symbol
            symbol.set(keySymbols, Component_spreadArray(Component_spreadArray([], symbol.__getSymbols(), true), [cloned], false));
            cloned.__initSymb();
        }
        else if (opt.symbol) {
            // Request to create a symbol
            if (this.__isSymbol()) {
                // Already a symbol, cloned should be an instance
                this.set(keySymbols, Component_spreadArray(Component_spreadArray([], symbols, true), [cloned], false));
                cloned.set(keySymbol, this);
                cloned.__initSymb();
            }
            else if (opt.symbolInv) {
                // Inverted, cloned is the instance, the origin is the main symbol
                this.set(keySymbols, [cloned]);
                cloned.set(keySymbol, this);
                [this, cloned].map(function (i) { return i.__initSymb(); });
            }
            else {
                // Cloned becomes the main symbol
                cloned.set(keySymbols, [this]);
                [this, cloned].map(function (i) { return i.__initSymb(); });
                this.set(keySymbol, cloned);
            }
        }
        var event = 'component:clone';
        em && em.trigger(event, cloned);
        this.trigger(event, cloned);
        return cloned;
    };
    /**
     * Get the name of the component.
     * @param {Object} [opts={}] Options
     * @param {Boolean} [opts.noCustom] Avoid custom name assigned to the component.
     * @returns {String}
     * */
    Component.prototype.getName = function (opts) {
        if (opts === void 0) { opts = {}; }
        var em = this.em;
        var _a = this.attributes, type = _a.type, tagName = _a.tagName, name = _a.name;
        var defName = type || tagName;
        var nameTag = !type ? tagName : '';
        var i18nPfx = 'domComponents.names.';
        var i18nName = name && (em === null || em === void 0 ? void 0 : em.t("".concat(i18nPfx).concat(name)));
        var i18nNameTag = nameTag && (em === null || em === void 0 ? void 0 : em.t("".concat(i18nPfx).concat(nameTag)));
        var i18nDefName = em && (em.t("".concat(i18nPfx).concat(type)) || em.t("".concat(i18nPfx).concat(tagName)));
        var customName = this.get('custom-name');
        return ((!opts.noCustom ? customName : '') || // Used in Layers (when the user changes the name)
            i18nName || // Use local component `name` key (eg. `domComponents.names.myComponentName`)
            name || // Use component `name` key
            i18nNameTag || // Use local component `tagName` key (eg. `domComponents.names.div`)
            (0,mixins.capitalize)(nameTag) || // Use component `tagName` key
            i18nDefName || // Use local component `type` key (eg. `domComponents.names.image`)
            (0,mixins.capitalize)(defName) // Use component `type` key
        );
    };
    /**
     * Get the icon string
     * @return {String}
     */
    Component.prototype.getIcon = function () {
        var icon = this.get('icon');
        return icon ? icon + ' ' : '';
    };
    /**
     * Return HTML string of the component
     * @param {Object} [opts={}] Options
     * @param {String} [opts.tag] Custom tagName
     * @param {Object|Function} [opts.attributes=null] You can pass an object of custom attributes to replace with the current ones or you can even pass a function to generate attributes dynamically.
     * @param {Boolean} [opts.withProps] Include component properties as `data-gjs-*` attributes. This allows you to have re-importable HTML.
     * @param {Boolean} [opts.altQuoteAttr] In case the attribute value contains a `"` char, instead of escaping it (`attr="value &quot;"`), the attribute will be quoted using single quotes (`attr='value "'`).
     * @return {String} HTML string
     * @example
     * // Simple HTML return
     * component.set({ tagName: 'span' });
     * component.setAttributes({ title: 'Hello' });
     * component.toHTML();
     * // -> <span title="Hello"></span>
     *
     * // Custom attributes
     * component.toHTML({ attributes: { 'data-test': 'Hello' } });
     * // -> <span data-test="Hello"></span>
     *
     * // Custom dynamic attributes
     * component.toHTML({
     *  attributes(component, attributes) {
     *    if (component.get('tagName') == 'span') {
     *      attributes.title = 'Custom attribute';
     *    }
     *    return attributes;
     *  },
     * });
     * // -> <span title="Custom attribute"></span>
     */
    Component.prototype.toHTML = function (opts) {
        if (opts === void 0) { opts = {}; }
        var model = this;
        var attrs = [];
        var customTag = opts.tag;
        var tag = customTag || model.get('tagName');
        var sTag = model.get('void');
        var customAttr = opts.attributes;
        var attributes = this.getAttrToHTML();
        delete opts.tag;
        // Get custom attributes if requested
        if (customAttr) {
            if ((0,index_all.isFunction)(customAttr)) {
                attributes = customAttr(model, attributes) || {};
            }
            else if ((0,mixins.isObject)(customAttr)) {
                attributes = customAttr;
            }
        }
        if (opts.withProps) {
            var props = this.toJSON();
            (0,index_all.forEach)(props, function (value, key) {
                var skipProps = ['classes', 'attributes', 'components'];
                if (key[0] !== '_' && skipProps.indexOf(key) < 0) {
                    attributes["data-gjs-".concat(key)] =
                        (0,index_all.isArray)(value) || (0,mixins.isObject)(value) ? JSON.stringify(value) : (0,index_all.isBoolean)(value) ? "".concat(value) : value;
                }
            });
        }
        for (var attr in attributes) {
            var val = attributes[attr];
            if (!(0,index_all.isUndefined)(val) && val !== null) {
                if ((0,index_all.isBoolean)(val)) {
                    val && attrs.push(attr);
                }
                else {
                    var valueRes = '';
                    if (opts.altQuoteAttr && (0,index_all.isString)(val) && val.indexOf('"') >= 0) {
                        valueRes = "'".concat(val.replace(/'/g, '&apos;'), "'");
                    }
                    else {
                        var value = (0,index_all.isString)(val) ? val.replace(/"/g, '&quot;') : val;
                        valueRes = "\"".concat(value, "\"");
                    }
                    attrs.push("".concat(attr, "=").concat(valueRes));
                }
            }
        }
        var attrString = attrs.length ? " ".concat(attrs.join(' ')) : '';
        var inner = model.getInnerHTML(opts);
        var code = "<".concat(tag).concat(attrString).concat(sTag ? '/' : '', ">").concat(inner);
        !sTag && (code += "</".concat(tag, ">"));
        return code;
    };
    /**
     * Get inner HTML of the component
     * @param {Object} [opts={}] Same options of `toHTML`
     * @returns {String} HTML string
     */
    Component.prototype.getInnerHTML = function (opts) {
        return this.__innerHTML(opts);
    };
    Component.prototype.__innerHTML = function (opts) {
        if (opts === void 0) { opts = {}; }
        var cmps = this.components();
        return !cmps.length ? this.content : cmps.map(function (c) { return c.toHTML(opts); }).join('');
    };
    /**
     * Returns object of attributes for HTML
     * @return {Object}
     * @private
     */
    Component.prototype.getAttrToHTML = function () {
        var attrs = this.getAttributes();
        if (avoidInline(this.em)) {
            delete attrs.style;
        }
        return attrs;
    };
    /**
     * Return a shallow copy of the model's attributes for JSON
     * stringification.
     * @return {Object}
     * @private
     */
    Component.prototype.toJSON = function (opts) {
        if (opts === void 0) { opts = {}; }
        var obj = backbone.Model.prototype.toJSON.call(this, opts);
        obj.attributes = this.getAttributes();
        delete obj.attributes.class;
        delete obj.toolbar;
        delete obj.traits;
        delete obj.status;
        delete obj.open; // used in Layers
        delete obj._undoexc;
        delete obj.delegate;
        if (!opts.fromUndo) {
            var symbol = obj[keySymbol];
            var symbols = obj[keySymbols];
            if (symbols && (0,index_all.isArray)(symbols)) {
                obj[keySymbols] = symbols.filter(function (i) { return i; }).map(function (i) { return (i.getId ? i.getId() : i); });
            }
            if (symbol && !(0,index_all.isString)(symbol)) {
                obj[keySymbol] = symbol.getId();
            }
        }
        if (this.em.getConfig().avoidDefaults) {
            this.getChangedProps(obj);
        }
        return obj;
    };
    /**
     * Return an object containing only changed props
     */
    Component.prototype.getChangedProps = function (res) {
        var obj = res || backbone.Model.prototype.toJSON.apply(this);
        var defaults = (0,index_all.result)(this, 'defaults');
        (0,index_all.forEach)(defaults, function (value, key) {
            if (['type'].indexOf(key) === -1 && obj[key] === value) {
                delete obj[key];
            }
        });
        if ((0,index_all.isEmpty)(obj.type)) {
            delete obj.type;
        }
        (0,index_all.forEach)(['attributes', 'style'], function (prop) {
            if ((0,index_all.isEmpty)(defaults[prop]) && (0,index_all.isEmpty)(obj[prop])) {
                delete obj[prop];
            }
        });
        (0,index_all.forEach)(['classes', 'components'], function (prop) {
            if (!obj[prop] || ((0,index_all.isEmpty)(defaults[prop]) && !obj[prop].length)) {
                delete obj[prop];
            }
        });
        return obj;
    };
    /**
     * Return the component id
     * @return {String}
     */
    Component.prototype.getId = function () {
        var attrs = this.get('attributes') || {};
        return attrs.id || this.ccid || this.cid;
    };
    /**
     * Set new id on the component
     * @param {String} id
     * @return {this}
     */
    Component.prototype.setId = function (id, opts) {
        var attrs = Component_assign({}, this.get('attributes'));
        attrs.id = id;
        this.set('attributes', attrs, opts);
        return this;
    };
    /**
     * Get the DOM element of the component.
     * This works only if the component is already rendered
     * @param {Frame} frame Specific frame from which taking the element
     * @return {HTMLElement}
     */
    Component.prototype.getEl = function (frame) {
        var view = this.getView(frame);
        return view && view.el;
    };
    /**
     * Get the View of the component.
     * This works only if the component is already rendered
     * @param {Frame} frame Get View of a specific frame
     * @return {ComponentView}
     */
    Component.prototype.getView = function (frame) {
        var _a = this, view = _a.view, views = _a.views, em = _a.em;
        var frm = frame || (em === null || em === void 0 ? void 0 : em.getCurrentFrameModel());
        if (frm) {
            view = views.filter(function (view) { return view.frameView === frm.view; })[0];
        }
        return view;
    };
    Component.prototype.getCurrentView = function () {
        var frameView = this.em.getCurrentFrame();
        var frame = frameView === null || frameView === void 0 ? void 0 : frameView.model;
        return this.getView(frame);
    };
    Component.prototype.__getScriptProps = function () {
        var modelProps = this.props();
        var scrProps = this.get('script-props') || [];
        return scrProps.reduce(function (acc, prop) {
            acc[prop] = modelProps[prop];
            return acc;
        }, {});
    };
    /**
     * Return script in string format, cleans 'function() {..' from scripts
     * if it's a function
     * @param {string|Function} script
     * @return {string}
     * @private
     */
    Component.prototype.getScriptString = function (script) {
        var _this = this;
        var scr = script || this.get('script') || '';
        if (!scr) {
            return scr;
        }
        if (this.get('script-props')) {
            scr = scr.toString().trim();
        }
        else {
            // Deprecated
            // Need to convert script functions to strings
            if ((0,index_all.isFunction)(scr)) {
                var scrStr = scr.toString().trim();
                scrStr = scrStr.slice(scrStr.indexOf('{') + 1, scrStr.lastIndexOf('}'));
                scr = scrStr.trim();
            }
            var config = this.em.getConfig();
            var tagVarStart = escapeRegExp(config.tagVarStart || '{[ ');
            var tagVarEnd = escapeRegExp(config.tagVarEnd || ' ]}');
            var reg = new RegExp("".concat(tagVarStart, "([\\w\\d-]*)").concat(tagVarEnd), 'g');
            scr = scr.replace(reg, function (match, v) {
                // If at least one match is found I have to track this change for a
                // better optimization inside JS generator
                _this.scriptUpdated();
                var result = _this.attributes[v] || '';
                return (0,index_all.isArray)(result) || typeof result == 'object' ? JSON.stringify(result) : result;
            });
        }
        return scr;
    };
    Component.prototype.emitUpdate = function (property) {
        var _a;
        var args = [];
        for (var _i = 1; _i < arguments.length; _i++) {
            args[_i - 1] = arguments[_i];
        }
        var em = this.em;
        var event = keyUpdate + (property ? ":".concat(property) : '');
        var item = property && this.get(property);
        // @ts-ignore
        property && this.updated.apply(this, Component_spreadArray([property, item, property && this.previous(property)], args, false));
        this.trigger.apply(this, Component_spreadArray([event], args, false));
        em && em.trigger.apply(em, Component_spreadArray([event, this], args, false));
        ['components', 'classes'].indexOf(property) >= 0 &&
            this.__propSelfToParent({
                component: this,
                changed: (_a = {}, _a[property] = item, _a),
                options: args[2] || args[1] || {},
            });
    };
    /**
     * Execute callback function on itself and all inner components
     * @param  {Function} clb Callback function, the model is passed as an argument
     * @return {this}
     * @example
     * component.onAll(component => {
     *  // do something with component
     * })
     */
    Component.prototype.onAll = function (clb) {
        if ((0,index_all.isFunction)(clb)) {
            clb(this);
            this.components().forEach(function (model) { return model.onAll(clb); });
        }
        return this;
    };
    /**
     * Execute a callback function on all inner child components.
     * @param  {Function} clb Callback function, the child component is passed as an argument
     * @example
     * component.forEachChild(child => {
     *  console.log(child)
     * })
     */
    Component.prototype.forEachChild = function (clb) {
        if ((0,index_all.isFunction)(clb)) {
            this.components().forEach(function (child) {
                clb(child);
                child.forEachChild(clb);
            });
        }
    };
    /**
     * Remove the component
     * @return {this}
     */
    Component.prototype.remove = function (opts) {
        var _this = this;
        if (opts === void 0) { opts = {}; }
        var em = this.em;
        var coll = this.collection;
        var remove = function () {
            coll && coll.remove(_this, Component_assign(Component_assign({}, opts), { action: 'remove-component' }));
            // Component without parent
            if (!coll) {
                _this.components('', opts);
                _this.components().removeChildren(_this, undefined, opts);
            }
        };
        var rmOpts = Component_assign({}, opts);
        [this, em].map(function (i) { return i.trigger('component:remove:before', _this, remove, rmOpts); });
        !rmOpts.abort && remove();
        return this;
    };
    /**
     * Move the component to another destination component
     * @param {Component} component Destination component (so the current one will be appended as a child)
     * @param {Object} opts Options for the append action
     * @returns {this}
     * @example
     * // Move the selected component on top of the wrapper
     * const dest = editor.getWrapper();
     * editor.getSelected().move(dest, { at: 0 });
     */
    Component.prototype.move = function (component, opts) {
        if (opts === void 0) { opts = {}; }
        if (component) {
            var at = opts.at;
            var index = this.index();
            var sameParent = component === this.parent();
            var sameIndex = index === at || index === at - 1;
            if (!sameParent || !sameIndex) {
                if (sameParent && at && at > index) {
                    opts.at = at - 1;
                }
                this.remove({ temporary: 1 });
                component.append(this, opts);
                this.emitUpdate();
            }
        }
        return this;
    };
    /**
     * Check if the component is an instance of some component type.
     * @param {String} type Component type
     * @returns {Boolean}
     * @example
     * // Add a new component type by extending an existing one
     * editor.Components.addType('text-ext', { extend: 'text' });
     * // Append a new component somewhere
     * const newTextExt = editor.getSelected().append({ type: 'text-ext' })[0];
     * newTextExt.isInstanceOf('text-ext'); // true
     * newTextExt.isInstanceOf('text'); // true
     */
    Component.prototype.isInstanceOf = function (type) {
        var _a, _b;
        var cmp = (_b = (_a = this.em) === null || _a === void 0 ? void 0 : _a.Components.getType(type)) === null || _b === void 0 ? void 0 : _b.model;
        if (!cmp)
            return false;
        return this instanceof cmp;
    };
    /**
     * Check if the component is a child of some other component (or component type)
     * @param {[Component]|String} component Component parent to check. In case a string is passed,
     *  the check will be performed on the component type.
     * @returns {Boolean}
     * @example
     * const newTextComponent = editor.getSelected().append({
     *  type: 'text',
     *  components: 'My text <b>here</b>',
     * })[0];
     * const innerComponent = newTextComponent.find('b')[0];
     * innerComponent.isChildOf(newTextComponent); // true
     * innerComponent.isChildOf('text'); // true
     */
    Component.prototype.isChildOf = function (component) {
        var byType = (0,index_all.isString)(component);
        var parent = this.parent();
        while (parent) {
            if (byType) {
                if (parent.isInstanceOf(component)) {
                    return true;
                }
            }
            else {
                if (parent === component) {
                    return true;
                }
            }
            parent = parent.parent();
        }
        return false;
    };
    /**
     * Reset id of the component and any of its style rule
     * @param {Object} [opts={}] Options
     * @return {this}
     * @private
     */
    Component.prototype.resetId = function (opts) {
        if (opts === void 0) { opts = {}; }
        var em = this.em;
        var oldId = this.getId();
        if (!oldId)
            return this;
        var newId = Component.createId(this);
        this.setId(newId);
        var rule = em === null || em === void 0 ? void 0 : em.Css.getIdRule(oldId);
        var selector = rule === null || rule === void 0 ? void 0 : rule.get('selectors').at(0);
        selector === null || selector === void 0 ? void 0 : selector.set('name', newId);
        return this;
    };
    Component.prototype._getStyleRule = function (_a) {
        var _b = _a === void 0 ? {} : _a, id = _b.id;
        var em = this.em;
        var idS = id || this.getId();
        return em === null || em === void 0 ? void 0 : em.Css.getIdRule(idS);
    };
    Component.prototype._getStyleSelector = function (opts) {
        var rule = this._getStyleRule(opts);
        return rule === null || rule === void 0 ? void 0 : rule.get('selectors').at(0);
    };
    Component.prototype._idUpdated = function (m, v, opts) {
        if (opts === void 0) { opts = {}; }
        if (opts.idUpdate)
            return;
        var ccid = this.ccid;
        var id = (this.get('attributes') || {}).id;
        var idPrev = (this.previous('attributes') || {}).id || ccid;
        var list = Component.getList(this);
        // If the ID already exists I need to rollback to the old one
        if (list[id] || (!id && idPrev)) {
            return this.setId(idPrev, { idUpdate: true });
        }
        // Remove the old ID reference and add the new one
        delete list[idPrev];
        list[id] = this;
        this.ccid = id;
        // Update the style selector name
        var selector = this._getStyleSelector({ id: idPrev });
        selector && selector.set({ name: id, label: id });
    };
    Component.getDefaults = function () {
        return (0,index_all.result)(this.prototype, 'defaults');
    };
    Component.isComponent = function (el) {
        return { tagName: (0,mixins.toLowerCase)(el.tagName) };
    };
    Component.ensureInList = function (model) {
        var list = Component.getList(model);
        var id = model.getId();
        var current = list[id];
        if (!current) {
            // Insert in list
            list[id] = model;
        }
        else if (current !== model) {
            // Create new ID
            var nextId = Component.getIncrementId(id, list);
            model.setId(nextId);
            list[nextId] = model;
        }
        model.components().forEach(function (i) { return Component.ensureInList(i); });
    };
    Component.createId = function (model, opts) {
        if (opts === void 0) { opts = {}; }
        var list = Component.getList(model);
        var _a = opts.idMap, idMap = _a === void 0 ? {} : _a;
        var id = model.get('attributes').id;
        var nextId;
        if (id) {
            nextId = Component.getIncrementId(id, list, opts);
            model.setId(nextId);
            if (id !== nextId)
                idMap[id] = nextId;
        }
        else {
            nextId = Component.getNewId(list);
        }
        list[nextId] = model;
        return nextId;
    };
    Component.getNewId = function (list) {
        var count = Object.keys(list).length;
        // Testing 1000000 components with `+ 2` returns 0 collisions
        var ilen = count.toString().length + 2;
        var uid = (Math.random() + 1.1).toString(36).slice(-ilen);
        var newId = "i".concat(uid);
        while (list[newId]) {
            newId = Component.getNewId(list);
        }
        return newId;
    };
    Component.getIncrementId = function (id, list, opts) {
        if (opts === void 0) { opts = {}; }
        var _a = opts.keepIds, keepIds = _a === void 0 ? [] : _a;
        var counter = 1;
        var newId = id;
        if (keepIds.indexOf(id) < 0) {
            while (list[newId]) {
                counter++;
                newId = "".concat(id, "-").concat(counter);
            }
        }
        return newId;
    };
    Component.getList = function (model) {
        var _a = model.opt, opt = _a === void 0 ? {} : _a;
        // @ts-ignore
        var domc = opt.domc, em = opt.em;
        var dm = domc || (em === null || em === void 0 ? void 0 : em.Components);
        return dm ? dm.componentsById : {};
    };
    Component.checkId = function (components, styles, list, opts) {
        if (styles === void 0) { styles = []; }
        if (list === void 0) { list = {}; }
        if (opts === void 0) { opts = {}; }
        var comps = (0,index_all.isArray)(components) ? components : [components];
        var _a = opts.keepIds, keepIds = _a === void 0 ? [] : _a, _b = opts.idMap, idMap = _b === void 0 ? {} : _b;
        comps.forEach(function (comp) {
            comp.attributes;
            var _a = comp.attributes, attributes = _a === void 0 ? {} : _a, components = comp.components;
            var id = attributes.id;
            // Check if we have collisions with current components
            if (id && list[id] && keepIds.indexOf(id) < 0) {
                var newId_1 = Component.getIncrementId(id, list);
                idMap[id] = newId_1;
                attributes.id = newId_1;
                // Update passed styles
                (0,index_all.isArray)(styles) &&
                    styles.forEach(function (style) {
                        var selectors = style.selectors;
                        selectors.forEach(function (sel, idx) {
                            if (sel === "#".concat(id))
                                selectors[idx] = "#".concat(newId_1);
                        });
                    });
            }
            components && Component.checkId(components, styles, list, opts);
        });
    };
    return Component;
}(model_StyleableModel));
/* harmony default export */ const model_Component = (Component);

;// CONCATENATED MODULE: ./src/dom_components/model/ComponentTextNode.ts
var ComponentTextNode_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var ComponentTextNode_assign = (undefined && undefined.__assign) || function () {
    ComponentTextNode_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return ComponentTextNode_assign.apply(this, arguments);
};


var ComponentTextNode = /** @class */ (function (_super) {
    ComponentTextNode_extends(ComponentTextNode, _super);
    function ComponentTextNode() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(ComponentTextNode.prototype, "defaults", {
        get: function () {
            return ComponentTextNode_assign(ComponentTextNode_assign({}, _super.prototype.defaults), { tagName: '', droppable: false, layerable: false, selectable: false, editable: true });
        },
        enumerable: false,
        configurable: true
    });
    ComponentTextNode.prototype.toHTML = function () {
        var content = this.content;
        var parent = this.parent();
        return (parent === null || parent === void 0 ? void 0 : parent.is('script')) ? content : this.__escapeContent(content);
    };
    ComponentTextNode.prototype.__escapeContent = function (content) {
        return (0,mixins.escapeNodeContent)(content);
    };
    ComponentTextNode.isComponent = function (el) {
        var _a;
        if (el.nodeType === 3) {
            return {
                type: 'textnode',
                content: (_a = el.textContent) !== null && _a !== void 0 ? _a : '',
            };
        }
    };
    return ComponentTextNode;
}(model_Component));
/* harmony default export */ const model_ComponentTextNode = (ComponentTextNode);

;// CONCATENATED MODULE: ./src/dom_components/model/ComponentComment.ts
var ComponentComment_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var ComponentComment_assign = (undefined && undefined.__assign) || function () {
    ComponentComment_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return ComponentComment_assign.apply(this, arguments);
};

var ComponentComment = /** @class */ (function (_super) {
    ComponentComment_extends(ComponentComment, _super);
    function ComponentComment() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(ComponentComment.prototype, "defaults", {
        get: function () {
            // @ts-ignore
            return ComponentComment_assign({}, _super.prototype.defaults);
        },
        enumerable: false,
        configurable: true
    });
    ComponentComment.prototype.toHTML = function () {
        return "<!--".concat(this.content, "-->");
    };
    ComponentComment.isComponent = function (el) {
        var _a;
        if (el.nodeType == 8) {
            return {
                type: 'comment',
                content: (_a = el.textContent) !== null && _a !== void 0 ? _a : '',
            };
        }
    };
    return ComponentComment;
}(model_ComponentTextNode));
/* harmony default export */ const model_ComponentComment = (ComponentComment);

;// CONCATENATED MODULE: ./src/dom_components/model/ComponentFrame.ts
var ComponentFrame_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var ComponentFrame_assign = (undefined && undefined.__assign) || function () {
    ComponentFrame_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return ComponentFrame_assign.apply(this, arguments);
};


var type = 'iframe';
var ComponentFrame = /** @class */ (function (_super) {
    ComponentFrame_extends(ComponentFrame, _super);
    function ComponentFrame() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(ComponentFrame.prototype, "defaults", {
        get: function () {
            return ComponentFrame_assign(ComponentFrame_assign({}, _super.prototype.defaults), { type: type, tagName: type, droppable: false, resizable: true, traits: ['id', 'title', 'src'], attributes: { frameborder: '0' } });
        },
        enumerable: false,
        configurable: true
    });
    ComponentFrame.isComponent = function (el) {
        return (0,mixins.toLowerCase)(el.tagName) === type;
    };
    return ComponentFrame;
}(model_Component));
/* harmony default export */ const model_ComponentFrame = (ComponentFrame);
// ComponentFrame.isComponent = el => toLowerCase(el.tagName) === type;

;// CONCATENATED MODULE: ./src/dom_components/model/ComponentImage.ts
var ComponentImage_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var ComponentImage_assign = (undefined && undefined.__assign) || function () {
    ComponentImage_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return ComponentImage_assign.apply(this, arguments);
};



var svgAttrs = 'xmlns="http://www.w3.org/2000/svg" width="100" viewBox="0 0 24 24" style="fill: rgba(0,0,0,0.15); transform: scale(0.75)"';
var ComponentImage = /** @class */ (function (_super) {
    ComponentImage_extends(ComponentImage, _super);
    function ComponentImage() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(ComponentImage.prototype, "defaults", {
        get: function () {
            return ComponentImage_assign(ComponentImage_assign({}, _super.prototype.defaults), { type: 'image', tagName: 'img', void: true, droppable: 0, editable: 1, highlightable: 0, resizable: { ratioDefault: 1 }, traits: ['alt'], src: "<svg ".concat(svgAttrs, ">\n        <path d=\"M8.5 13.5l2.5 3 3.5-4.5 4.5 6H5m16 1V5a2 2 0 0 0-2-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2z\"></path>\n      </svg>"), 
                // Fallback image in case the src can't be loaded
                // If you use SVG, xmlns="http://www.w3.org/2000/svg" is required
                fallback: "<svg ".concat(svgAttrs, ">\n        <path d=\"M2.28 3L1 4.27l2 2V19c0 1.1.9 2 2 2h12.73l2 2L21 21.72 2.28 3m2.55 0L21 19.17V5a2 2 0 0 0-2-2H4.83M8.5 13.5l2.5 3 1-1.25L14.73 18H5l3.5-4.5z\"></path>\n      </svg>"), 
                // File to load asynchronously once the model is rendered
                file: '' });
        },
        enumerable: false,
        configurable: true
    });
    ComponentImage.prototype.initialize = function (props, opts) {
        _super.prototype.initialize.call(this, props, opts);
        var src = this.get('attributes').src;
        if (src && (0,mixins.buildBase64UrlFromSvg)((0,index_all.result)(this, 'defaults').src) !== src) {
            this.set('src', src, { silent: true });
        }
    };
    ComponentImage.prototype.initToolbar = function () {
        _super.prototype.initToolbar.call(this);
        var em = this.em;
        if (em) {
            var cmd = em.Commands;
            var cmdName = 'image-editor';
            // Add Image Editor button only if the default command exists
            if (cmd.has(cmdName)) {
                var hasButtonBool = false;
                var tb = this.get('toolbar');
                for (var i = 0; i < tb.length; i++) {
                    if (tb[i].command === 'image-editor') {
                        hasButtonBool = true;
                        break;
                    }
                }
                if (!hasButtonBool) {
                    tb.push({
                        attributes: { class: 'fa fa-pencil' },
                        command: cmdName,
                    });
                    this.set('toolbar', tb);
                }
            }
        }
    };
    /**
     * Returns object of attributes for HTML
     * @return {Object}
     * @private
     */
    ComponentImage.prototype.getAttrToHTML = function () {
        var attr = _super.prototype.getAttrToHTML.call(this);
        var src = this.getSrcResult();
        if (src)
            attr.src = src;
        return attr;
    };
    ComponentImage.prototype.getSrcResult = function (opt) {
        if (opt === void 0) { opt = {}; }
        var src = this.get(opt.fallback ? 'fallback' : 'src') || '';
        var result = src;
        if (src && src.substr(0, 4) === '<svg') {
            result = (0,mixins.buildBase64UrlFromSvg)(src);
        }
        return result;
    };
    ComponentImage.prototype.isDefaultSrc = function () {
        var src = this.get('src');
        var srcDef = (0,index_all.result)(this, 'defaults').src;
        return src === srcDef || src === (0,mixins.buildBase64UrlFromSvg)(srcDef);
    };
    /**
     * Return a shallow copy of the model's attributes for JSON
     * stringification.
     * @return {Object}
     * @private
     */
    ComponentImage.prototype.toJSON = function (opts) {
        var obj = _super.prototype.toJSON.call(this, opts);
        var attributes = obj.attributes;
        if (attributes && obj.src === attributes.src) {
            delete obj.src;
        }
        return obj;
    };
    /**
     * Parse uri
     * @param  {string} uri
     * @return {object}
     * @private
     */
    ComponentImage.prototype.parseUri = function (uri) {
        var result = {};
        var getQueryObject = function (search) {
            if (search === void 0) { search = ''; }
            var query = {};
            var qrs = search.substring(1).split('&');
            for (var i = 0; i < qrs.length; i++) {
                var pair = qrs[i].split('=');
                var name_1 = decodeURIComponent(pair[0]);
                if (name_1)
                    query[name_1] = decodeURIComponent(pair[1] || '');
            }
            return query;
        };
        if ((0,mixins.hasWin)()) {
            result = document.createElement('a');
            result.href = uri;
        }
        else if (typeof URL !== 'undefined') {
            try {
                result = new URL(uri);
            }
            catch (e) { }
        }
        return {
            hostname: result.hostname || '',
            pathname: result.pathname || '',
            protocol: result.protocol || '',
            search: result.search || '',
            hash: result.hash || '',
            port: result.port || '',
            query: getQueryObject(result.search),
        };
    };
    ComponentImage.isComponent = function (el) {
        return (0,mixins.toLowerCase)(el.tagName) === 'img';
    };
    return ComponentImage;
}(model_Component));
/* harmony default export */ const model_ComponentImage = (ComponentImage);

;// CONCATENATED MODULE: ./src/dom_components/model/ComponentText.ts
var ComponentText_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var ComponentText_assign = (undefined && undefined.__assign) || function () {
    ComponentText_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return ComponentText_assign.apply(this, arguments);
};


var ComponentText = /** @class */ (function (_super) {
    ComponentText_extends(ComponentText, _super);
    function ComponentText() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(ComponentText.prototype, "defaults", {
        get: function () {
            return ComponentText_assign(ComponentText_assign({}, _super.prototype.defaults), { type: 'text', droppable: false, editable: true });
        },
        enumerable: false,
        configurable: true
    });
    ComponentText.prototype.initialize = function (props, opts) {
        _super.prototype.initialize.call(this, props, opts);
        this.__checkInnerChilds();
    };
    ComponentText.prototype.__checkInnerChilds = function () {
        var disableTextInnerChilds = this.em.Components.config.disableTextInnerChilds;
        if (disableTextInnerChilds) {
            var disableChild_1 = function (child) {
                if (!child.isInstanceOf('textnode')) {
                    child.set({
                        locked: true,
                        layerable: false,
                    });
                }
            };
            if ((0,index_all.isFunction)(disableTextInnerChilds)) {
                this.forEachChild(function (child) {
                    disableTextInnerChilds(child) && disableChild_1(child);
                });
            }
            else {
                this.forEachChild(disableChild_1);
            }
        }
    };
    return ComponentText;
}(model_Component));
/* harmony default export */ const model_ComponentText = (ComponentText);

;// CONCATENATED MODULE: ./src/dom_components/model/ComponentLabel.ts
var ComponentLabel_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var ComponentLabel_assign = (undefined && undefined.__assign) || function () {
    ComponentLabel_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return ComponentLabel_assign.apply(this, arguments);
};


var ComponentLabel_type = 'label';
var ComponentLabel = /** @class */ (function (_super) {
    ComponentLabel_extends(ComponentLabel, _super);
    function ComponentLabel() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(ComponentLabel.prototype, "defaults", {
        get: function () {
            return ComponentLabel_assign(ComponentLabel_assign({}, _super.prototype.defaults), { type: ComponentLabel_type, tagName: ComponentLabel_type, traits: ['id', 'title', 'for'] });
        },
        enumerable: false,
        configurable: true
    });
    ComponentLabel.isComponent = function (el) {
        return (0,mixins.toLowerCase)(el.tagName) === ComponentLabel_type;
    };
    return ComponentLabel;
}(model_ComponentText));
/* harmony default export */ const model_ComponentLabel = (ComponentLabel);

;// CONCATENATED MODULE: ./src/dom_components/model/ComponentLink.ts
var ComponentLink_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var ComponentLink_assign = (undefined && undefined.__assign) || function () {
    ComponentLink_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return ComponentLink_assign.apply(this, arguments);
};



var ComponentLink_type = 'link';
var ComponentLink = /** @class */ (function (_super) {
    ComponentLink_extends(ComponentLink, _super);
    function ComponentLink() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(ComponentLink.prototype, "defaults", {
        get: function () {
            return ComponentLink_assign(ComponentLink_assign({}, _super.prototype.defaults), { type: ComponentLink_type, tagName: 'a', traits: ['title', 'href', 'target'] });
        },
        enumerable: false,
        configurable: true
    });
    ComponentLink.isComponent = function (el, opts) {
        if (opts === void 0) { opts = {}; }
        var result;
        if ((0,mixins.toLowerCase)(el.tagName) === 'a') {
            var textTags_1 = opts.textTags || [];
            result = { type: ComponentLink_type, editable: false };
            // The link is editable only if, at least, one of its
            // children is a text node (not empty one)
            var children = el.childNodes;
            var len = children.length;
            if (!len)
                delete result.editable;
            (0,index_all.forEach)(children, function (child) {
                var tagName = child.tagName;
                if ((child.nodeType == 3 && child.textContent.trim() !== '') ||
                    (tagName && textTags_1.indexOf((0,mixins.toLowerCase)(tagName)) >= 0)) {
                    delete result.editable;
                }
            });
        }
        return result;
    };
    return ComponentLink;
}(model_ComponentText));
/* harmony default export */ const model_ComponentLink = (ComponentLink);

;// CONCATENATED MODULE: ./src/dom_components/model/ComponentMap.ts
var ComponentMap_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var ComponentMap_assign = (undefined && undefined.__assign) || function () {
    ComponentMap_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return ComponentMap_assign.apply(this, arguments);
};


var ComponentMap = /** @class */ (function (_super) {
    ComponentMap_extends(ComponentMap, _super);
    function ComponentMap() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(ComponentMap.prototype, "defaults", {
        /** @ts-ignore */
        get: function () {
            // @ts-ignore
            var defs = _super.prototype.defaults;
            return ComponentMap_assign(ComponentMap_assign({}, defs), { type: 'map', src: '', void: false, mapUrl: 'https://maps.google.com/maps', tagName: 'iframe', mapType: 'q', address: '', zoom: '1', attributes: { frameborder: 0 }, 
                // @ts-ignore
                toolbar: defs.toolbar, traits: [
                    {
                        label: 'Address',
                        name: 'address',
                        placeholder: 'eg. London, UK',
                        changeProp: true,
                    },
                    {
                        type: 'select',
                        label: 'Map type',
                        name: 'mapType',
                        changeProp: true,
                        options: [
                            { id: 'q', label: 'Roadmap' },
                            { id: 'w', label: 'Satellite' },
                        ],
                    },
                    {
                        label: 'Zoom',
                        name: 'zoom',
                        type: 'range',
                        min: 1,
                        max: 20,
                        changeProp: true,
                    },
                ] });
        },
        enumerable: false,
        configurable: true
    });
    ComponentMap.prototype.initialize = function (props, opts) {
        if (this.get('src'))
            this.parseFromSrc();
        else
            this.updateSrc();
        _super.prototype.initialize.call(this, props, opts);
        this.listenTo(this, 'change:address change:zoom change:mapType', this.updateSrc);
    };
    ComponentMap.prototype.updateSrc = function () {
        this.set('src', this.getMapUrl());
    };
    /**
     * Returns url of the map
     * @return {string}
     * @private
     */
    ComponentMap.prototype.getMapUrl = function () {
        var addr = this.get('address');
        var zoom = this.get('zoom');
        var type = this.get('mapType');
        addr = addr ? '&q=' + addr : '';
        zoom = zoom ? '&z=' + zoom : '';
        type = type ? '&t=' + type : '';
        var result = this.get('mapUrl') + '?' + addr + zoom + type;
        result += '&output=embed';
        return result;
    };
    /**
     * Set attributes by src string
     * @private
     */
    ComponentMap.prototype.parseFromSrc = function () {
        var uri = this.parseUri(this.get('src'));
        var qr = uri.query;
        if (qr.q)
            this.set('address', qr.q);
        if (qr.z)
            this.set('zoom', qr.z);
        if (qr.t)
            this.set('mapType', qr.t);
    };
    ComponentMap.isComponent = function (el) {
        if ((0,mixins.toLowerCase)(el.tagName) == 'iframe' && /maps\.google\.com/.test(el.src)) {
            return { type: 'map', src: el.src };
        }
    };
    return ComponentMap;
}(model_ComponentImage));
/* harmony default export */ const model_ComponentMap = (ComponentMap);

;// CONCATENATED MODULE: ./src/dom_components/model/ComponentScript.ts
var ComponentScript_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var ComponentScript_assign = (undefined && undefined.__assign) || function () {
    ComponentScript_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return ComponentScript_assign.apply(this, arguments);
};


var ComponentScript_type = 'script';
var ComponentScript = /** @class */ (function (_super) {
    ComponentScript_extends(ComponentScript, _super);
    function ComponentScript() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(ComponentScript.prototype, "defaults", {
        get: function () {
            return ComponentScript_assign(ComponentScript_assign({}, _super.prototype.defaults), { type: ComponentScript_type, tagName: ComponentScript_type, droppable: false, draggable: false, layerable: false, highlightable: false });
        },
        enumerable: false,
        configurable: true
    });
    ComponentScript.isComponent = function (el) {
        return (0,mixins.toLowerCase)(el.tagName) === ComponentScript_type;
    };
    return ComponentScript;
}(model_Component));
/* harmony default export */ const model_ComponentScript = (ComponentScript);

;// CONCATENATED MODULE: ./src/dom_components/model/ComponentSvg.ts
var ComponentSvg_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var ComponentSvg_assign = (undefined && undefined.__assign) || function () {
    ComponentSvg_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return ComponentSvg_assign.apply(this, arguments);
};


var ComponentSvg_type = 'svg';
var ComponentSvg = /** @class */ (function (_super) {
    ComponentSvg_extends(ComponentSvg, _super);
    function ComponentSvg() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(ComponentSvg.prototype, "defaults", {
        get: function () {
            return ComponentSvg_assign(ComponentSvg_assign({}, _super.prototype.defaults), { type: ComponentSvg_type, tagName: ComponentSvg_type, highlightable: false, resizable: { ratioDefault: true } });
        },
        enumerable: false,
        configurable: true
    });
    ComponentSvg.prototype.getName = function () {
        var name = this.get('tagName');
        var customName = this.get('custom-name');
        name = name.charAt(0).toUpperCase() + name.slice(1);
        return customName || name;
    };
    ComponentSvg.isComponent = function (el) {
        return (0,mixins.toLowerCase)(el.tagName) === ComponentSvg_type;
    };
    return ComponentSvg;
}(model_Component));
/* harmony default export */ const model_ComponentSvg = (ComponentSvg);

;// CONCATENATED MODULE: ./src/dom_components/model/ComponentSvgIn.ts
var ComponentSvgIn_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var ComponentSvgIn_assign = (undefined && undefined.__assign) || function () {
    ComponentSvgIn_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return ComponentSvgIn_assign.apply(this, arguments);
};

/**
 * Component for inner SVG elements
 */
var ComponentSvgIn = /** @class */ (function (_super) {
    ComponentSvgIn_extends(ComponentSvgIn, _super);
    function ComponentSvgIn() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(ComponentSvgIn.prototype, "defaults", {
        get: function () {
            return ComponentSvgIn_assign(ComponentSvgIn_assign({}, _super.prototype.defaults), { selectable: false, hoverable: false, layerable: false });
        },
        enumerable: false,
        configurable: true
    });
    ComponentSvgIn.isComponent = function (el, opts) {
        if (opts === void 0) { opts = {}; }
        return !!opts.inSvg;
    };
    return ComponentSvgIn;
}(model_ComponentSvg));
/* harmony default export */ const model_ComponentSvgIn = (ComponentSvgIn);

;// CONCATENATED MODULE: ./src/dom_components/model/ComponentTable.ts
var ComponentTable_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var ComponentTable_assign = (undefined && undefined.__assign) || function () {
    ComponentTable_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return ComponentTable_assign.apply(this, arguments);
};


var ComponentTable_type = 'table';
var ComponentTable = /** @class */ (function (_super) {
    ComponentTable_extends(ComponentTable, _super);
    function ComponentTable() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(ComponentTable.prototype, "defaults", {
        get: function () {
            return ComponentTable_assign(ComponentTable_assign({}, _super.prototype.defaults), { type: ComponentTable_type, tagName: ComponentTable_type, droppable: ['tbody', 'thead', 'tfoot'] });
        },
        enumerable: false,
        configurable: true
    });
    ComponentTable.prototype.initialize = function (props, opts) {
        _super.prototype.initialize.call(this, props, opts);
        var components = this.get('components');
        !components.length && components.add({ type: 'tbody' });
    };
    ComponentTable.isComponent = function (el) {
        return (0,mixins.toLowerCase)(el.tagName) === ComponentTable_type;
    };
    return ComponentTable;
}(model_Component));
/* harmony default export */ const model_ComponentTable = (ComponentTable);

;// CONCATENATED MODULE: ./src/dom_components/model/ComponentTableBody.ts
var ComponentTableBody_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var ComponentTableBody_assign = (undefined && undefined.__assign) || function () {
    ComponentTableBody_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return ComponentTableBody_assign.apply(this, arguments);
};


var ComponentTableBody_type = 'tbody';
var ComponentTableBody = /** @class */ (function (_super) {
    ComponentTableBody_extends(ComponentTableBody, _super);
    function ComponentTableBody() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(ComponentTableBody.prototype, "defaults", {
        get: function () {
            return ComponentTableBody_assign(ComponentTableBody_assign({}, _super.prototype.defaults), { type: ComponentTableBody_type, tagName: ComponentTableBody_type, draggable: ['table'], droppable: ['tr'], columns: 1, rows: 1 });
        },
        enumerable: false,
        configurable: true
    });
    ComponentTableBody.prototype.initialize = function (props, opts) {
        _super.prototype.initialize.call(this, props, opts);
        var components = this.get('components');
        var columns = this.get('columns');
        var rows = this.get('rows');
        // Init components if empty
        if (!components.length) {
            var rowsToAdd = [];
            while (rows--) {
                var columnsToAdd = [];
                var clm = columns;
                while (clm--) {
                    columnsToAdd.push({
                        type: 'cell',
                        classes: ['cell'],
                    });
                }
                rowsToAdd.push({
                    type: 'row',
                    classes: ['row'],
                    components: columnsToAdd,
                });
            }
            components.add(rowsToAdd);
        }
    };
    ComponentTableBody.isComponent = function (el) {
        return (0,mixins.toLowerCase)(el.tagName) === ComponentTableBody_type;
    };
    return ComponentTableBody;
}(model_Component));
/* harmony default export */ const model_ComponentTableBody = (ComponentTableBody);

;// CONCATENATED MODULE: ./src/dom_components/model/ComponentTableCell.ts
var ComponentTableCell_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var ComponentTableCell_assign = (undefined && undefined.__assign) || function () {
    ComponentTableCell_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return ComponentTableCell_assign.apply(this, arguments);
};


var ComponentTableCell = /** @class */ (function (_super) {
    ComponentTableCell_extends(ComponentTableCell, _super);
    function ComponentTableCell() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(ComponentTableCell.prototype, "defaults", {
        get: function () {
            return ComponentTableCell_assign(ComponentTableCell_assign({}, _super.prototype.defaults), { type: 'cell', tagName: 'td', draggable: ['tr'] });
        },
        enumerable: false,
        configurable: true
    });
    ComponentTableCell.isComponent = function (el) {
        return ['td', 'th'].indexOf((0,mixins.toLowerCase)(el.tagName)) >= 0;
    };
    return ComponentTableCell;
}(model_Component));
/* harmony default export */ const model_ComponentTableCell = (ComponentTableCell);

;// CONCATENATED MODULE: ./src/dom_components/model/ComponentTableFoot.ts
var ComponentTableFoot_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var ComponentTableFoot_assign = (undefined && undefined.__assign) || function () {
    ComponentTableFoot_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return ComponentTableFoot_assign.apply(this, arguments);
};


var ComponentTableFoot_type = 'tfoot';
var ComponentTableFoot = /** @class */ (function (_super) {
    ComponentTableFoot_extends(ComponentTableFoot, _super);
    function ComponentTableFoot() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(ComponentTableFoot.prototype, "defaults", {
        get: function () {
            return ComponentTableFoot_assign(ComponentTableFoot_assign({}, _super.prototype.defaults), { type: ComponentTableFoot_type, tagName: ComponentTableFoot_type });
        },
        enumerable: false,
        configurable: true
    });
    ComponentTableFoot.isComponent = function (el) {
        return (0,mixins.toLowerCase)(el.tagName) === ComponentTableFoot_type;
    };
    return ComponentTableFoot;
}(model_ComponentTableBody));
/* harmony default export */ const model_ComponentTableFoot = (ComponentTableFoot);

;// CONCATENATED MODULE: ./src/dom_components/model/ComponentTableHead.ts
var ComponentTableHead_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var ComponentTableHead_assign = (undefined && undefined.__assign) || function () {
    ComponentTableHead_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return ComponentTableHead_assign.apply(this, arguments);
};


var ComponentTableHead_type = 'thead';
var ComponentTableHead = /** @class */ (function (_super) {
    ComponentTableHead_extends(ComponentTableHead, _super);
    function ComponentTableHead() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(ComponentTableHead.prototype, "defaults", {
        get: function () {
            return ComponentTableHead_assign(ComponentTableHead_assign({}, _super.prototype.defaults), { type: ComponentTableHead_type, tagName: ComponentTableHead_type });
        },
        enumerable: false,
        configurable: true
    });
    ComponentTableHead.isComponent = function (el) {
        return (0,mixins.toLowerCase)(el.tagName) === ComponentTableHead_type;
    };
    return ComponentTableHead;
}(model_ComponentTableBody));
/* harmony default export */ const model_ComponentTableHead = (ComponentTableHead);

;// CONCATENATED MODULE: ./src/dom_components/model/ComponentTableRow.ts
var ComponentTableRow_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var ComponentTableRow_assign = (undefined && undefined.__assign) || function () {
    ComponentTableRow_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return ComponentTableRow_assign.apply(this, arguments);
};


var tagName = 'tr';
var ComponentTableRow = /** @class */ (function (_super) {
    ComponentTableRow_extends(ComponentTableRow, _super);
    function ComponentTableRow() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(ComponentTableRow.prototype, "defaults", {
        get: function () {
            return ComponentTableRow_assign(ComponentTableRow_assign({}, _super.prototype.defaults), { tagName: tagName, draggable: ['thead', 'tbody', 'tfoot'], droppable: ['th', 'td'] });
        },
        enumerable: false,
        configurable: true
    });
    ComponentTableRow.isComponent = function (el) {
        return (0,mixins.toLowerCase)(el.tagName) === tagName;
    };
    return ComponentTableRow;
}(model_Component));
/* harmony default export */ const model_ComponentTableRow = (ComponentTableRow);

;// CONCATENATED MODULE: ./src/dom_components/model/ComponentVideo.ts
var ComponentVideo_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var ComponentVideo_assign = (undefined && undefined.__assign) || function () {
    ComponentVideo_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return ComponentVideo_assign.apply(this, arguments);
};


var ComponentVideo_type = 'video';
var yt = 'yt';
var vi = 'vi';
var ytnc = 'ytnc';
var defProvider = 'so';
var hasParam = function (value) { return value && value !== '0'; };
var ComponentVideo = /** @class */ (function (_super) {
    ComponentVideo_extends(ComponentVideo, _super);
    function ComponentVideo() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(ComponentVideo.prototype, "defaults", {
        get: function () {
            return ComponentVideo_assign(ComponentVideo_assign({}, _super.prototype.defaults), { type: ComponentVideo_type, tagName: ComponentVideo_type, videoId: '', void: false, provider: defProvider, ytUrl: 'https://www.youtube.com/embed/', ytncUrl: 'https://www.youtube-nocookie.com/embed/', viUrl: 'https://player.vimeo.com/video/', loop: false, poster: '', muted: 0, autoplay: false, controls: true, color: '', list: '', src: '', rel: 1, modestbranding: 0, sources: [], attributes: { allowfullscreen: 'allowfullscreen' } });
        },
        enumerable: false,
        configurable: true
    });
    ComponentVideo.prototype.initialize = function (props, opts) {
        this.em = opts.em;
        if (this.get('src'))
            this.parseFromSrc();
        this.updatePropsFromAttr();
        this.updateTraits();
        this.on('change:provider', this.updateTraits);
        this.on('change:videoId change:provider', this.updateSrc);
        _super.prototype.initialize.call(this, props, opts);
    };
    ComponentVideo.prototype.updatePropsFromAttr = function () {
        if (this.get('provider') === defProvider) {
            var _a = this.get('attributes'), controls = _a.controls, autoplay = _a.autoplay, loop = _a.loop;
            var toUp = {};
            if ((0,mixins.isDef)(controls))
                toUp.controls = !!controls;
            if ((0,mixins.isDef)(autoplay))
                toUp.autoplay = !!autoplay;
            if ((0,mixins.isDef)(loop))
                toUp.loop = !!loop;
            if (!(0,mixins.isEmptyObj)(toUp)) {
                this.set(toUp);
            }
        }
    };
    /**
     * Update traits by provider
     * @private
     */
    ComponentVideo.prototype.updateTraits = function () {
        var em = this.em;
        var prov = this.get('provider');
        var tagName = 'iframe';
        var traits;
        switch (prov) {
            case yt:
            case ytnc:
                traits = this.getYoutubeTraits();
                break;
            case vi:
                traits = this.getVimeoTraits();
                break;
            default:
                tagName = 'video';
                traits = this.getSourceTraits();
        }
        this.set({ tagName: tagName }, { silent: true }); // avoid break in view
        // @ts-ignore
        this.set({ traits: traits });
        em.get('ready') && em.trigger('component:toggled');
    };
    /**
     * Set attributes by src string
     */
    ComponentVideo.prototype.parseFromSrc = function () {
        var prov = this.get('provider');
        var uri = this.parseUri(this.get('src'));
        var qr = uri.query;
        switch (prov) {
            case yt:
            case ytnc:
            case vi:
                this.set('videoId', uri.pathname.split('/').pop());
                qr.list && this.set('list', qr.list);
                hasParam(qr.autoplay) && this.set('autoplay', true);
                hasParam(qr.loop) && this.set('loop', true);
                parseInt(qr.controls) === 0 && this.set('controls', false);
                hasParam(qr.color) && this.set('color', qr.color);
                qr.rel === '0' && this.set('rel', 0);
                qr.modestbranding === '1' && this.set('modestbranding', 1);
                break;
            default:
        }
    };
    /**
     * Update src on change of video ID
     * @private
     */
    ComponentVideo.prototype.updateSrc = function () {
        var prov = this.get('provider');
        var src = '';
        switch (prov) {
            case yt:
                src = this.getYoutubeSrc();
                break;
            case ytnc:
                src = this.getYoutubeNoCookieSrc();
                break;
            case vi:
                src = this.getVimeoSrc();
                break;
        }
        this.set({ src: src });
    };
    /**
     * Returns object of attributes for HTML
     * @return {Object}
     * @private
     */
    ComponentVideo.prototype.getAttrToHTML = function () {
        var attr = _super.prototype.getAttrToHTML.call(this);
        var prov = this.get('provider');
        switch (prov) {
            case yt:
            case ytnc:
            case vi:
                break;
            default:
                attr.loop = !!this.get('loop');
                attr.autoplay = !!this.get('autoplay');
                attr.controls = !!this.get('controls');
        }
        return attr;
    };
    // Listen provider change and switch traits, in TraitView listen traits change
    /**
     * Return the provider trait
     * @return {Object}
     * @private
     */
    ComponentVideo.prototype.getProviderTrait = function () {
        return {
            type: 'select',
            label: 'Provider',
            name: 'provider',
            changeProp: true,
            options: [
                { value: 'so', name: 'HTML5 Source' },
                { value: yt, name: 'Youtube' },
                { value: ytnc, name: 'Youtube (no cookie)' },
                { value: vi, name: 'Vimeo' },
            ],
        };
    };
    /**
     * Return traits for the source provider
     * @return {Array<Object>}
     * @private
     */
    ComponentVideo.prototype.getSourceTraits = function () {
        return [
            this.getProviderTrait(),
            {
                label: 'Source',
                name: 'src',
                placeholder: 'eg. ./media/video.mp4',
                changeProp: true,
            },
            {
                label: 'Poster',
                name: 'poster',
                placeholder: 'eg. ./media/image.jpg',
            },
            this.getAutoplayTrait(),
            this.getLoopTrait(),
            this.getControlsTrait(),
        ];
    };
    /**
     * Return traits for the source provider
     * @return {Array<Object>}
     * @private
     */
    ComponentVideo.prototype.getYoutubeTraits = function () {
        return [
            this.getProviderTrait(),
            {
                label: 'Video ID',
                name: 'videoId',
                placeholder: 'eg. jNQXAC9IVRw',
                changeProp: true,
            },
            this.getAutoplayTrait(),
            this.getLoopTrait(),
            this.getControlsTrait(),
            {
                type: 'checkbox',
                label: 'Related',
                name: 'rel',
                changeProp: true,
            },
            {
                type: 'checkbox',
                label: 'Modest',
                name: 'modestbranding',
                changeProp: true,
            },
        ];
    };
    /**
     * Return traits for the source provider
     * @return {Array<Object>}
     * @private
     */
    ComponentVideo.prototype.getVimeoTraits = function () {
        return [
            this.getProviderTrait(),
            {
                label: 'Video ID',
                name: 'videoId',
                placeholder: 'eg. 123456789',
                changeProp: true,
            },
            {
                label: 'Color',
                name: 'color',
                placeholder: 'eg. FF0000',
                changeProp: true,
            },
            this.getAutoplayTrait(),
            this.getLoopTrait(),
        ];
    };
    /**
     * Return object trait
     * @return {Object}
     * @private
     */
    ComponentVideo.prototype.getAutoplayTrait = function () {
        return {
            type: 'checkbox',
            label: 'Autoplay',
            name: 'autoplay',
            changeProp: true,
        };
    };
    /**
     * Return object trait
     * @return {Object}
     * @private
     */
    ComponentVideo.prototype.getLoopTrait = function () {
        return {
            type: 'checkbox',
            label: 'Loop',
            name: 'loop',
            changeProp: true,
        };
    };
    /**
     * Return object trait
     * @return {Object}
     * @private
     */
    ComponentVideo.prototype.getControlsTrait = function () {
        return {
            type: 'checkbox',
            label: 'Controls',
            name: 'controls',
            changeProp: true,
        };
    };
    /**
     * Returns url to youtube video
     * @return {string}
     * @private
     */
    ComponentVideo.prototype.getYoutubeSrc = function () {
        var id = this.get('videoId');
        var url = this.get('ytUrl');
        var list = this.get('list');
        url += id + (id.indexOf('?') < 0 ? '?' : '');
        url += list ? "&list=".concat(list) : '';
        url += this.get('autoplay') ? '&autoplay=1&mute=1' : '';
        url += !this.get('controls') ? '&controls=0&showinfo=0' : '';
        // Loop works only with playlist enabled
        // https://stackoverflow.com/questions/25779966/youtube-iframe-loop-doesnt-work
        url += this.get('loop') ? "&loop=1&playlist=".concat(id) : '';
        url += this.get('rel') ? '' : '&rel=0';
        url += this.get('modestbranding') ? '&modestbranding=1' : '';
        return url;
    };
    /**
     * Returns url to youtube no cookie video
     * @return {string}
     * @private
     */
    ComponentVideo.prototype.getYoutubeNoCookieSrc = function () {
        var url = this.getYoutubeSrc();
        url = url.replace(this.get('ytUrl'), this.get('ytncUrl'));
        return url;
    };
    /**
     * Returns url to vimeo video
     * @return {string}
     * @private
     */
    ComponentVideo.prototype.getVimeoSrc = function () {
        var url = this.get('viUrl');
        url += this.get('videoId') + '?';
        url += this.get('autoplay') ? '&autoplay=1&muted=1' : '';
        url += this.get('loop') ? '&loop=1' : '';
        url += !this.get('controls') ? '&title=0&portrait=0&badge=0' : '';
        url += this.get('color') ? '&color=' + this.get('color') : '';
        return url;
    };
    ComponentVideo.isComponent = function (el) {
        var tagName = el.tagName, src = el.src;
        var isYtProv = /youtube\.com\/embed/.test(src);
        var isYtncProv = /youtube-nocookie\.com\/embed/.test(src);
        var isViProv = /player\.vimeo\.com\/video/.test(src);
        var isExtProv = isYtProv || isYtncProv || isViProv;
        if ((0,mixins.toLowerCase)(tagName) == ComponentVideo_type || ((0,mixins.toLowerCase)(tagName) == 'iframe' && isExtProv)) {
            var result = { type: 'video' };
            if (src)
                result.src = src;
            if (isExtProv) {
                if (isYtProv)
                    result.provider = yt;
                else if (isYtncProv)
                    result.provider = ytnc;
                else if (isViProv)
                    result.provider = vi;
            }
            return result;
        }
    };
    return ComponentVideo;
}(model_ComponentImage));
/* harmony default export */ const model_ComponentVideo = (ComponentVideo);

;// CONCATENATED MODULE: ./src/dom_components/model/ComponentWrapper.ts
var ComponentWrapper_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var ComponentWrapper_assign = (undefined && undefined.__assign) || function () {
    ComponentWrapper_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return ComponentWrapper_assign.apply(this, arguments);
};

var ComponentWrapper = /** @class */ (function (_super) {
    ComponentWrapper_extends(ComponentWrapper, _super);
    function ComponentWrapper() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(ComponentWrapper.prototype, "defaults", {
        get: function () {
            return ComponentWrapper_assign(ComponentWrapper_assign({}, _super.prototype.defaults), { tagName: 'body', removable: false, copyable: false, draggable: false, components: [], traits: [], stylable: [
                    'background',
                    'background-color',
                    'background-image',
                    'background-repeat',
                    'background-attachment',
                    'background-position',
                    'background-size',
                ] });
        },
        enumerable: false,
        configurable: true
    });
    ComponentWrapper.prototype.__postAdd = function () {
        var _a;
        var um = (_a = this.em) === null || _a === void 0 ? void 0 : _a.UndoManager;
        !this.__hasUm && (um === null || um === void 0 ? void 0 : um.add(this));
        return _super.prototype.__postAdd.call(this);
    };
    ComponentWrapper.prototype.__postRemove = function () {
        var _a;
        var um = (_a = this.em) === null || _a === void 0 ? void 0 : _a.UndoManager;
        um === null || um === void 0 ? void 0 : um.remove(this);
        return _super.prototype.__postRemove.call(this);
    };
    ComponentWrapper.isComponent = function () {
        return false;
    };
    return ComponentWrapper;
}(model_Component));
/* harmony default export */ const model_ComponentWrapper = (ComponentWrapper);

;// CONCATENATED MODULE: ./src/dom_components/view/ComponentsView.ts
var ComponentsView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();




var ComponentsView = /** @class */ (function (_super) {
    ComponentsView_extends(ComponentsView, _super);
    function ComponentsView() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.compView = view_ComponentView;
        return _this;
    }
    ComponentsView.prototype.initialize = function (o) {
        this.opts = o || {};
        this.config = o.config || {};
        // @ts-ignore
        this.em = this.config.em;
        var coll = this.collection;
        this.listenTo(coll, 'add', this.addTo);
        this.listenTo(coll, 'reset', this.resetChildren);
        this.listenTo(coll, 'remove', this.removeChildren);
    };
    ComponentsView.prototype.removeChildren = function (removed, coll, opts) {
        var _this = this;
        if (opts === void 0) { opts = {}; }
        removed.views.forEach(function (view) {
            if (!view)
                return;
            var childrenView = view.childrenView, scriptContainer = view.scriptContainer;
            childrenView && childrenView.stopListening();
            (0,dom/* removeEl */.L_)(scriptContainer);
            view.remove.apply(view);
        });
        var inner = removed.components();
        inner.forEach(function (it) { return _this.removeChildren(it, coll, opts); });
    };
    /**
     * Add to collection
     * @param {Model} model
     * @param {Collection} coll
     * @param {Object} opts
     * @private
     * */
    ComponentsView.prototype.addTo = function (model, coll, opts) {
        if (coll === void 0) { coll = {}; }
        if (opts === void 0) { opts = {}; }
        var em = this.em;
        var i = this.collection.indexOf(model);
        this.addToCollection(model, null, i);
        if (em && !opts.temporary) {
            var triggerAdd_1 = function (model) {
                em.trigger('component:add', model);
                model.components().forEach(function (comp) { return triggerAdd_1(comp); });
            };
            triggerAdd_1(model);
        }
    };
    /**
     * Add new object to collection
     * @param  {Object}  Model
     * @param  {Object}   Fragment collection
     * @param  {Integer}  Index of append
     *
     * @return   {Object}   Object rendered
     * @private
     * */
    ComponentsView.prototype.addToCollection = function (model, fragmentEl, index) {
        // if (!this.compView) this.compView = require('./ComponentView').default;
        var _a = this, config = _a.config, opts = _a.opts, em = _a.em;
        var fragment = fragmentEl || null;
        var frameView = config.frameView;
        var sameFrameView = (frameView === null || frameView === void 0 ? void 0 : frameView.model) && model.getView(frameView.model);
        var dt = opts.componentTypes || (em === null || em === void 0 ? void 0 : em.Components.getTypes());
        var type = model.get('type') || 'default';
        var viewObject = this.compView;
        for (var it_1 = 0; it_1 < dt.length; it_1++) {
            if (dt[it_1].id == type) {
                viewObject = dt[it_1].view;
                break;
            }
        }
        var view = sameFrameView ||
            new viewObject({
                model: model,
                // @ts-ignore
                config: config,
                componentTypes: dt,
            });
        var rendered;
        try {
            // Avoid breaking on DOM rendering (eg. invalid attribute name)
            rendered = view.render().el;
        }
        catch (error) {
            rendered = document.createTextNode('');
            em.logError(error);
        }
        if (fragment) {
            fragment.appendChild(rendered);
        }
        else {
            var parent_1 = this.parentEl;
            var children = parent_1.childNodes;
            if (!(0,index_all.isUndefined)(index)) {
                var lastIndex = children.length == index;
                // If the added model is the last of collection
                // need to change the logic of append
                if (lastIndex) {
                    index--;
                }
                // In case the added is new in the collection index will be -1
                if (lastIndex || !children.length) {
                    parent_1.appendChild(rendered);
                }
                else {
                    parent_1.insertBefore(rendered, children[index]);
                }
            }
            else {
                parent_1.appendChild(rendered);
            }
        }
        if (!model.opt.temporary) {
            em === null || em === void 0 ? void 0 : em.trigger('component:mount', model);
        }
        return rendered;
    };
    ComponentsView.prototype.resetChildren = function (models, _a) {
        var _this = this;
        var _b = _a === void 0 ? {} : _a, _c = _b.previousModels, previousModels = _c === void 0 ? [] : _c;
        this.parentEl.innerHTML = '';
        previousModels.forEach(function (md) { return _this.removeChildren(md, _this.collection); });
        models.each(function (model) { return _this.addToCollection(model); });
    };
    ComponentsView.prototype.render = function (parent) {
        var _this = this;
        var el = this.el;
        var frag = document.createDocumentFragment();
        this.parentEl = parent || this.el;
        this.collection.each(function (model) { return _this.addToCollection(model, frag); });
        el.innerHTML = '';
        el.appendChild(frag);
        return this;
    };
    return ComponentsView;
}(common/* View */.G7));
/* harmony default export */ const view_ComponentsView = (ComponentsView);

;// CONCATENATED MODULE: ./src/dom_components/view/ComponentView.ts
var ComponentView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var ComponentView_assign = (undefined && undefined.__assign) || function () {
    ComponentView_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return ComponentView_assign.apply(this, arguments);
};









var ComponentView = /** @class */ (function (_super) {
    ComponentView_extends(ComponentView, _super);
    function ComponentView() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    /** @ts-ignore */
    ComponentView.prototype.className = function () {
        return this.getClasses();
    };
    /** @ts-ignore */
    ComponentView.prototype.tagName = function () {
        return this.model.get('tagName');
    };
    ComponentView.prototype.preinitialize = function (opt) {
        if (opt === void 0) { opt = {}; }
        this.opts = opt;
    };
    ComponentView.prototype.initialize = function (opt) {
        if (opt === void 0) { opt = {}; }
        var model = this.model;
        var config = opt.config || {};
        var em = config.em;
        var modelOpt = model.opt || {};
        var _a = this, $el = _a.$el, el = _a.el;
        this.opts = opt;
        this.modelOpt = modelOpt;
        this.config = config;
        this.em = em;
        this.pfx = config.stylePrefix || '';
        this.ppfx = config.pStylePrefix || '';
        this.attr = model.get('attributes');
        this.classe = this.attr.class || [];
        this.listenTo(model, 'change:style', this.updateStyle);
        this.listenTo(model, 'change:attributes', this.renderAttributes);
        this.listenTo(model, 'change:highlightable', this.updateHighlight);
        this.listenTo(model, 'change:status change:locked', this.updateStatus);
        this.listenTo(model, 'change:script rerender', this.reset);
        this.listenTo(model, 'change:content', this.updateContent);
        this.listenTo(model, 'change', this.handleChange);
        this.listenTo(model, 'active', this.onActive);
        this.listenTo(model, 'disable', this.onDisable);
        $el.data('model', model);
        (0,mixins.setViewEl)(el, this);
        model.view = this;
        this.frameView && model.views.push(this);
        this.initClasses();
        this.initComponents({ avoidRender: true });
        this.events = ComponentView_assign(ComponentView_assign({}, this.constructor.getEvents()), { dragstart: 'handleDragStart' });
        this.delegateEvents();
        !modelOpt.temporary && this.init(this._clbObj());
    };
    Object.defineProperty(ComponentView.prototype, "__cmpStyleOpts", {
        get: function () {
            return { state: '', mediaText: '' };
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ComponentView.prototype, "frameView", {
        get: function () {
            return this.opts.config.frameView;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ComponentView.prototype, "createDoc", {
        get: function () {
            var _a, _b;
            var doc = ((_a = this.frameView) === null || _a === void 0 ? void 0 : _a.getDoc()) || document;
            return ((_b = this.opts.config) === null || _b === void 0 ? void 0 : _b.useFrameDoc) ? doc : document;
        },
        enumerable: false,
        configurable: true
    });
    ComponentView.prototype.__isDraggable = function () {
        var _a = this, model = _a.model, config = _a.config;
        var draggable = model.attributes.draggable;
        return config.draggableComponents && draggable;
    };
    ComponentView.prototype._clbObj = function () {
        var _a = this, em = _a.em, model = _a.model, el = _a.el;
        return {
            editor: em === null || em === void 0 ? void 0 : em.getEditor(),
            model: model,
            el: el,
        };
    };
    /**
     * Initialize callback
     */
    ComponentView.prototype.init = function (opts) { };
    /**
     * Remove callback
     */
    ComponentView.prototype.removed = function (opts) { };
    /**
     * On render callback
     */
    ComponentView.prototype.onRender = function (opts) { };
    /**
     * Callback executed when the `active` event is triggered on component
     */
    ComponentView.prototype.onActive = function (ev) { };
    /**
     * Callback executed when the `disable` event is triggered on component
     */
    ComponentView.prototype.onDisable = function (opts) { };
    ComponentView.prototype.remove = function () {
        var _a;
        _super.prototype.remove.call(this);
        var _b = this, model = _b.model, $el = _b.$el;
        var views = model.views;
        var frame = this.frameView || {};
        model.components().forEach(function (comp) {
            var view = comp.getView(frame.model);
            view === null || view === void 0 ? void 0 : view.remove();
        });
        (_a = this.childrenView) === null || _a === void 0 ? void 0 : _a.remove();
        views.splice(views.indexOf(this), 1);
        this.removed(this._clbObj());
        $el.data({ model: '', collection: '', view: '' });
        // delete model.view; // Sorter relies on this property
        return this;
    };
    ComponentView.prototype.handleDragStart = function (event) {
        if (!this.__isDraggable())
            return false;
        event.stopPropagation();
        event.preventDefault();
        this.em.Commands.run('tlb-move', {
            target: this.model,
            event: event,
        });
    };
    ComponentView.prototype.initClasses = function () {
        var model = this.model;
        var classes = model.classes;
        var event = 'change:classes';
        if (classes instanceof model_Selectors) {
            this.stopListening(model, event, this.initClasses);
            this.listenTo(model, event, this.initClasses);
            this.listenTo(classes, 'add remove change reset', this.updateClasses);
            classes.length && this.importClasses();
        }
    };
    ComponentView.prototype.initComponents = function (opts) {
        if (opts === void 0) { opts = {}; }
        var _a = this, model = _a.model, $el = _a.$el, childrenView = _a.childrenView;
        var event = 'change:components';
        var comps = model.get('components');
        var toListen = [model, event, this.initComponents];
        if (comps instanceof model_Components) {
            $el.data('collection', comps);
            childrenView && childrenView.remove();
            this.stopListening.apply(this, toListen);
            !opts.avoidRender && this.renderChildren();
            // @ts-ignore
            this.listenTo.apply(this, toListen);
        }
    };
    /**
     * Handle any property change
     * @private
     */
    ComponentView.prototype.handleChange = function () {
        var model = this.model;
        var chgArr = (0,index_all.keys)(model.changed);
        if (chgArr.length === 1 && chgArr[0] === 'status')
            return;
        model.emitUpdate();
        for (var prop in model.changed) {
            model.emitUpdate(prop);
        }
    };
    /**
     * Import, if possible, classes inside main container
     * @private
     * */
    ComponentView.prototype.importClasses = function () {
        var _a = this, em = _a.em, model = _a.model;
        var sm = em.Selectors;
        sm && model.classes.forEach(function (s) { return sm.add(s.getName()); });
    };
    /**
     * Update item on status change
     * @param  {Event} e
     * @private
     * */
    ComponentView.prototype.updateStatus = function (opts) {
        if (opts === void 0) { opts = {}; }
        var _a = this, em = _a.em, el = _a.el, ppfx = _a.ppfx, model = _a.model;
        var canvas = em === null || em === void 0 ? void 0 : em.Canvas;
        var extHl = canvas === null || canvas === void 0 ? void 0 : canvas.config.extHl;
        var status = model.get('status');
        var selectedCls = "".concat(ppfx, "selected");
        var selectedParentCls = "".concat(selectedCls, "-parent");
        var freezedCls = "".concat(ppfx, "freezed");
        var hoveredCls = "".concat(ppfx, "hovered");
        var noPointerCls = "".concat(ppfx, "no-pointer");
        var pointerInitCls = "".concat(ppfx, "pointer-init");
        var toRemove = [selectedCls, selectedParentCls, freezedCls, hoveredCls, noPointerCls];
        var selCls = extHl && !opts.noExtHl ? '' : selectedCls;
        this.$el.removeClass(toRemove.join(' '));
        var actualCls = el.getAttribute('class') || '';
        var cls = [actualCls];
        var noCustomSpotSelect = !(canvas === null || canvas === void 0 ? void 0 : canvas.hasCustomSpot(CanvasSpot/* CanvasSpotBuiltInTypes */.q.Select));
        var noCustomSpotTarget = !(canvas === null || canvas === void 0 ? void 0 : canvas.hasCustomSpot(CanvasSpot/* CanvasSpotBuiltInTypes */.q.Target));
        switch (status) {
            case 'selected':
                noCustomSpotSelect && cls.push(selCls);
                break;
            case 'selected-parent':
                noCustomSpotTarget && cls.push(selectedParentCls);
                break;
            case 'freezed':
                cls.push(freezedCls);
                break;
            case 'freezed-selected':
                cls.push(freezedCls);
                noCustomSpotSelect && cls.push(selCls);
                break;
            case 'hovered':
                !opts.avoidHover && cls.push(hoveredCls);
                break;
        }
        if ((0,index_all.isBoolean)(model.locked)) {
            cls.push(model.locked ? noPointerCls : pointerInitCls);
        }
        var clsStr = cls.filter(Boolean).join(' ');
        clsStr && el.setAttribute('class', clsStr);
    };
    /**
     * Update highlight attribute
     * @private
     * */
    ComponentView.prototype.updateHighlight = function () {
        var model = this.model;
        var isTextable = model.get('textable');
        var hl = model.get('highlightable') && (isTextable || !model.isChildOf('text'));
        this.setAttribute('data-gjs-highlightable', hl ? true : '');
    };
    /**
     * Update style attribute
     * @private
     * */
    ComponentView.prototype.updateStyle = function (m, v, opts) {
        if (opts === void 0) { opts = {}; }
        var _a = this, model = _a.model, em = _a.em;
        if (avoidInline(em) && !opts.inline) {
            var styleOpts = this.__cmpStyleOpts;
            var style = model.getStyle(styleOpts);
            !(0,index_all.isEmpty)(style) && model.setStyle(style, styleOpts);
        }
        else {
            this.setAttribute('style', model.styleToString(opts));
        }
    };
    /**
     * Update classe attribute
     * @private
     * */
    ComponentView.prototype.updateClasses = function () {
        var str = this.model.classes.pluck('name').join(' ');
        this.setAttribute('class', str);
        // Regenerate status class
        this.updateStatus();
        this.onAttrUpdate();
    };
    /**
     * Update single attribute
     * @param {[type]} name  [description]
     * @param {[type]} value [description]
     */
    ComponentView.prototype.setAttribute = function (name, value) {
        var el = this.$el;
        value ? el.attr(name, value) : el.removeAttr(name);
    };
    /**
     * Get classes from attributes.
     * This method is called before initialize
     *
     * @return  {Array}|null
     * @private
     * */
    ComponentView.prototype.getClasses = function () {
        return this.model.getClasses().join(' ');
    };
    /**
     * Update attributes
     * @private
     * */
    ComponentView.prototype.updateAttributes = function () {
        var attrs = [];
        var _a = this, model = _a.model, $el = _a.$el, el = _a.el;
        var _b = model.attributes, textable = _b.textable, type = _b.type;
        var defaultAttr = ComponentView_assign(ComponentView_assign({ id: model.getId(), 'data-gjs-type': type || 'default' }, (this.__isDraggable() && { draggable: true })), (textable && { contenteditable: 'false' }));
        // Remove all current attributes
        (0,index_all.each)(el.attributes, function (attr) { return attrs.push(attr.nodeName); });
        attrs.forEach(function (attr) { return $el.removeAttr(attr); });
        this.updateStyle();
        this.updateHighlight();
        var attr = ComponentView_assign(ComponentView_assign({}, defaultAttr), model.getAttributes());
        // Remove all `false` attributes
        (0,index_all.keys)(attr).forEach(function (key) { return attr[key] === false && delete attr[key]; });
        $el.attr(attr);
    };
    /**
     * Update component content
     * @private
     * */
    ComponentView.prototype.updateContent = function () {
        var content = this.model.content;
        var hasComps = this.model.components().length;
        this.getChildrenContainer().innerHTML = hasComps ? '' : content;
    };
    /**
     * Prevent default helper
     * @param  {Event} e
     * @private
     */
    ComponentView.prototype.prevDef = function (e) {
        e.preventDefault();
    };
    /**
     * Render component's script
     * @private
     */
    ComponentView.prototype.updateScript = function () {
        var _a = this, model = _a.model, em = _a.em;
        if (!model.get('script'))
            return;
        em === null || em === void 0 ? void 0 : em.Canvas.getCanvasView().updateScript(this);
    };
    /**
     * Return children container
     * Differently from a simple component where children container is the
     * component itself
     * <my-comp>
     *  <!--
     *    <child></child> ...
     *   -->
     * </my-comp>
     * You could have the children container more deeper
     * <my-comp>
     *  <div></div>
     *  <div></div>
     *  <div>
     *    <div>
     *      <!--
     *        <child></child> ...
     *      -->
     *    </div>
     *  </div>
     * </my-comp>
     * @return HTMLElement
     * @private
     */
    ComponentView.prototype.getChildrenContainer = function () {
        var container = this.el;
        if (typeof this.getChildrenSelector == 'function') {
            container = this.el.querySelector(this.getChildrenSelector());
        }
        else if (typeof this.getTemplate == 'function') {
            // Need to find deepest first child
        }
        return container;
    };
    /**
     * This returns rect informations not affected by the canvas zoom.
     * The method `getBoundingClientRect` doesn't work here and we
     * have to take in account offsetParent
     */
    ComponentView.prototype.getOffsetRect = function () {
        var rect = { top: 0, left: 0, bottom: 0, right: 0 };
        var target = this.el;
        var gtop = 0;
        var gleft = 0;
        var assignRect = function (el) {
            var offsetParent = el.offsetParent;
            if (offsetParent) {
                gtop += offsetParent.offsetTop;
                gleft += offsetParent.offsetLeft;
                assignRect(offsetParent);
            }
            else {
                rect.top = target.offsetTop + gtop;
                rect.left = target.offsetLeft + gleft;
                rect.bottom = rect.top + target.offsetHeight;
                rect.right = rect.left + target.offsetWidth;
            }
        };
        assignRect(target);
        return rect;
    };
    ComponentView.prototype.isInViewport = function () {
        var _a = this, el = _a.el, em = _a.em, frameView = _a.frameView;
        var canvasView = em.Canvas.getCanvasView();
        var elRect = canvasView.getElBoxRect(el, { local: true });
        var frameEl = frameView.el;
        var frameH = frameEl.clientHeight;
        var frameW = frameEl.clientWidth;
        var elTop = elRect.y;
        var elRight = elRect.x;
        var elBottom = elTop + elRect.height;
        var elLeft = elRight + elRect.width;
        var isTopInside = elTop >= 0 && elTop < frameH;
        var isBottomInside = elBottom > 0 && elBottom < frameH;
        var isLeftInside = elLeft >= 0 && elLeft < frameW;
        var isRightInside = elRight > 0 && elRight <= frameW;
        var partiallyIn = (isTopInside || isBottomInside) && (isLeftInside || isRightInside);
        return partiallyIn;
    };
    ComponentView.prototype.scrollIntoView = function (opts) {
        var _a;
        if (opts === void 0) { opts = {}; }
        var isInViewport = this.isInViewport();
        if (!isInViewport || opts.force) {
            var el = this.el;
            // PATCH: scrollIntoView won't work with multiple requests from iframes
            if (opts.behavior !== 'smooth') {
                var rect = this.getOffsetRect();
                (_a = el.ownerDocument.defaultView) === null || _a === void 0 ? void 0 : _a.scrollTo(0, rect.top);
            }
            else {
                el.scrollIntoView(ComponentView_assign({ behavior: 'smooth', block: 'nearest' }, opts));
            }
        }
    };
    /**
     * Recreate the element of the view
     */
    ComponentView.prototype.reset = function () {
        var el = this.el;
        // @ts-ignore
        this.el = '';
        this._ensureElement();
        this._setData();
        (0,dom/* replaceWith */.dL)(el, this.el);
        this.render();
    };
    ComponentView.prototype._setData = function () {
        var model = this.model;
        var collection = model.components();
        var view = this;
        this.$el.data({ model: model, collection: collection, view: view });
    };
    ComponentView.prototype._createElement = function (tagName) {
        return this.createDoc.createElement(tagName);
    };
    /**
     * Render children components
     * @private
     */
    ComponentView.prototype.renderChildren = function () {
        this.updateContent();
        var container = this.getChildrenContainer();
        var view = this.childrenView ||
            new view_ComponentsView({
                // @ts-ignore
                collection: this.model.get('components'),
                config: this.config,
                componentTypes: this.opts.componentTypes,
            });
        view.render(container);
        this.childrenView = view;
        var childNodes = Array.prototype.slice.call(view.el.childNodes);
        for (var i = 0, len = childNodes.length; i < len; i++) {
            container.appendChild(childNodes.shift());
        }
    };
    ComponentView.prototype.renderAttributes = function () {
        this.updateAttributes();
        this.updateClasses();
    };
    ComponentView.prototype.onAttrUpdate = function () { };
    ComponentView.prototype.render = function () {
        this.renderAttributes();
        if (this.modelOpt.temporary)
            return this;
        this.renderChildren();
        this.updateScript();
        (0,mixins.setViewEl)(this.el, this);
        this.postRender();
        return this;
    };
    ComponentView.prototype.postRender = function () {
        if (!this.modelOpt.temporary) {
            this.onRender(this._clbObj());
        }
    };
    ComponentView.getEvents = function () {
        return (0,index_all.result)(this.prototype, 'events');
    };
    return ComponentView;
}(common/* View */.G7));
/* harmony default export */ const view_ComponentView = (ComponentView);

;// CONCATENATED MODULE: ./src/dom_components/view/ComponentTextNodeView.ts
var ComponentTextNodeView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();

var ComponentTextNodeView = /** @class */ (function (_super) {
    ComponentTextNodeView_extends(ComponentTextNodeView, _super);
    function ComponentTextNodeView() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    // Clear methods used on Nodes with attributes
    ComponentTextNodeView.prototype._setAttributes = function () { };
    ComponentTextNodeView.prototype.renderAttributes = function () { };
    ComponentTextNodeView.prototype.updateStatus = function () { };
    ComponentTextNodeView.prototype.updateClasses = function () { };
    ComponentTextNodeView.prototype.setAttribute = function () { };
    ComponentTextNodeView.prototype.updateAttributes = function () { };
    ComponentTextNodeView.prototype.initClasses = function () { };
    ComponentTextNodeView.prototype.initComponents = function () { };
    ComponentTextNodeView.prototype.delegateEvents = function () {
        return this;
    };
    ComponentTextNodeView.prototype._createElement = function () {
        return document.createTextNode('');
    };
    ComponentTextNodeView.prototype.render = function () {
        var _a = this, model = _a.model, el = _a.el;
        if (model.opt.temporary)
            return this;
        el.textContent = model.content;
        return this;
    };
    return ComponentTextNodeView;
}(view_ComponentView));
/* harmony default export */ const view_ComponentTextNodeView = (ComponentTextNodeView);

;// CONCATENATED MODULE: ./src/dom_components/view/ComponentCommentView.ts
var ComponentCommentView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();

var ComponentCommentView = /** @class */ (function (_super) {
    ComponentCommentView_extends(ComponentCommentView, _super);
    function ComponentCommentView() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    ComponentCommentView.prototype._createElement = function () {
        return document.createComment(this.model.content);
    };
    return ComponentCommentView;
}(view_ComponentTextNodeView));
/* harmony default export */ const view_ComponentCommentView = (ComponentCommentView);

;// CONCATENATED MODULE: ./src/dom_components/view/ComponentFrameView.ts
var ComponentFrameView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();


var ComponentFrameView = /** @class */ (function (_super) {
    ComponentFrameView_extends(ComponentFrameView, _super);
    function ComponentFrameView() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    ComponentFrameView.prototype.tagName = function () {
        return 'div';
    };
    ComponentFrameView.prototype.initialize = function (props) {
        _super.prototype.initialize.call(this, props);
        this.listenTo(this.model, 'change:attributes:src', this.updateSrc);
    };
    ComponentFrameView.prototype.updateSrc = function () {
        var frame = (0,dom/* find */.sE)(this.el, 'iframe')[0];
        frame && (0,dom/* attrUp */.FW)(frame, { src: this.__getSrc() });
    };
    ComponentFrameView.prototype.render = function () {
        _super.prototype.render.call(this);
        var frame = (0,dom/* createEl */.ut)('iframe', {
            class: "".concat(this.ppfx, "no-pointer"),
            style: 'width: 100%; height: 100%; border: none',
            src: this.__getSrc(),
        });
        this.el.appendChild(frame);
        return this;
    };
    ComponentFrameView.prototype.__getSrc = function () {
        return this.model.getAttributes().src || '';
    };
    return ComponentFrameView;
}(view_ComponentView));
/* harmony default export */ const view_ComponentFrameView = (ComponentFrameView);

;// CONCATENATED MODULE: ./src/dom_components/view/ComponentImageView.ts
var ComponentImageView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();


var ComponentImageView = /** @class */ (function (_super) {
    ComponentImageView_extends(ComponentImageView, _super);
    function ComponentImageView() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    ComponentImageView.prototype.tagName = function () {
        return 'img';
    };
    ComponentImageView.prototype.events = function () {
        return {
            dblclick: 'onActive',
            click: 'initResize',
            error: 'onError',
            load: 'onLoad',
            dragstart: 'noDrag',
        };
    };
    ComponentImageView.prototype.initialize = function (props) {
        _super.prototype.initialize.call(this, props);
        this.listenTo(this.model, 'change:src', this.updateSrc);
        this.classEmpty = "".concat(this.ppfx, "plh-image");
        this.fetchFile();
    };
    /**
     * Fetch file if exists
     */
    ComponentImageView.prototype.fetchFile = function () {
        if (this.modelOpt.temporary)
            return;
        var _a = this, model = _a.model, em = _a.em;
        var file = model.get('file');
        if (file && em) {
            var fu = em.Assets.FileUploader();
            fu === null || fu === void 0 ? void 0 : fu.uploadFile({
                // @ts-ignore
                dataTransfer: { files: [file] },
            }, function (res) {
                var obj = res && res.data && res.data[0];
                var src = obj && ((0,index_all.isString)(obj) ? obj : obj.src);
                src && model.set({ src: src });
            });
            model.set('file', '');
        }
    };
    /**
     * Update src attribute
     * @private
     * */
    ComponentImageView.prototype.updateSrc = function () {
        var model = this.model;
        model.addAttributes({ src: model.getSrcResult() });
        this.updateClasses();
    };
    ComponentImageView.prototype.updateClasses = function () {
        _super.prototype.updateClasses.call(this);
        var _a = this, el = _a.el, classEmpty = _a.classEmpty, model = _a.model;
        var srcExists = model.getSrcResult() && !model.isDefaultSrc();
        var method = srcExists ? 'remove' : 'add';
        el.classList[method](classEmpty);
    };
    /**
     * Open dialog for image changing
     * @param  {Object}  e  Event
     * @private
     * */
    ComponentImageView.prototype.onActive = function (ev) {
        ev === null || ev === void 0 ? void 0 : ev.stopPropagation();
        var _a = this, em = _a.em, model = _a.model;
        var am = em === null || em === void 0 ? void 0 : em.Assets;
        if (am && model.get('editable')) {
            am.open({
                select: function (asset, complete) {
                    model.set({ src: asset.getSrc() });
                    complete && am.close();
                },
                target: model,
                types: ['image'],
                accept: 'image/*',
            });
        }
    };
    ComponentImageView.prototype.onError = function () {
        var fallback = this.model.getSrcResult({ fallback: true });
        if (fallback) {
            this.el.src = fallback;
        }
    };
    ComponentImageView.prototype.onLoad = function () {
        // Used to update component tools box (eg. toolbar, resizer) once the image is loaded
        this.em.Canvas.refresh({ all: true });
    };
    ComponentImageView.prototype.noDrag = function (ev) {
        ev.preventDefault();
        return false;
    };
    ComponentImageView.prototype.render = function () {
        this.renderAttributes();
        if (this.modelOpt.temporary)
            return this;
        this.updateSrc();
        var _a = this, $el = _a.$el, model = _a.model;
        var cls = $el.attr('class') || '';
        !model.get('src') && $el.attr('class', "".concat(cls, " ").concat(this.classEmpty).trim());
        this.postRender();
        return this;
    };
    return ComponentImageView;
}(view_ComponentView));
/* harmony default export */ const view_ComponentImageView = (ComponentImageView);

;// CONCATENATED MODULE: ./src/dom_components/view/ComponentTextView.ts
var ComponentTextView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var ComponentTextView_assign = (undefined && undefined.__assign) || function () {
    ComponentTextView_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return ComponentTextView_assign.apply(this, arguments);
};
var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (undefined && undefined.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};





var ComponentTextView = /** @class */ (function (_super) {
    ComponentTextView_extends(ComponentTextView, _super);
    function ComponentTextView() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    ComponentTextView.prototype.events = function () {
        return {
            dblclick: 'onActive',
            input: 'onInput',
        };
    };
    ComponentTextView.prototype.initialize = function (props) {
        _super.prototype.initialize.call(this, props);
        (0,index_all.bindAll)(this, 'disableEditing', 'onDisable');
        var model = this.model;
        var em = this.em;
        this.listenTo(model, 'focus', this.onActive);
        this.listenTo(model, 'change:content', this.updateContentText);
        this.listenTo(model, 'sync:content', this.syncContent);
        this.rte = em === null || em === void 0 ? void 0 : em.RichTextEditor;
    };
    ComponentTextView.prototype.updateContentText = function (m, v, opts) {
        if (opts === void 0) { opts = {}; }
        !opts.fromDisable && this.disableEditing();
    };
    ComponentTextView.prototype.canActivate = function () {
        var _a = this, model = _a.model, rteEnabled = _a.rteEnabled, em = _a.em;
        var modelInEdit = em === null || em === void 0 ? void 0 : em.getEditing();
        var sameInEdit = modelInEdit === model;
        var result = true;
        var isInnerText = false;
        var delegate;
        if (rteEnabled || !model.get('editable') || sameInEdit || (isInnerText = model.isChildOf('text'))) {
            result = false;
            // If the current is inner text, select the closest text
            if (isInnerText && !model.get('textable')) {
                var parent_1 = model.parent();
                while (parent_1 && !parent_1.isInstanceOf('text')) {
                    parent_1 = parent_1.parent();
                }
                if (parent_1 && parent_1.get('editable')) {
                    delegate = parent_1;
                }
                else {
                    result = true;
                }
            }
        }
        return { result: result, delegate: delegate };
    };
    /**
     * Enable element content editing
     * @private
     * */
    ComponentTextView.prototype.onActive = function (ev) {
        var _a, _b;
        return __awaiter(this, void 0, void 0, function () {
            var _c, rte, em, _d, result, delegate, _e, _f, err_1;
            return __generator(this, function (_g) {
                switch (_g.label) {
                    case 0:
                        _c = this, rte = _c.rte, em = _c.em;
                        _d = this.canActivate(), result = _d.result, delegate = _d.delegate;
                        // We place this before stopPropagation in case of nested
                        // text components will not block the editing (#1394)
                        if (!result) {
                            if (delegate) {
                                (_a = ev === null || ev === void 0 ? void 0 : ev.stopPropagation) === null || _a === void 0 ? void 0 : _a.call(ev);
                                em.setSelected(delegate);
                                delegate.trigger('active', ev);
                            }
                            return [2 /*return*/];
                        }
                        (_b = ev === null || ev === void 0 ? void 0 : ev.stopPropagation) === null || _b === void 0 ? void 0 : _b.call(ev);
                        _e = this;
                        return [4 /*yield*/, this.getContent()];
                    case 1:
                        _e.lastContent = _g.sent();
                        if (!rte) return [3 /*break*/, 5];
                        _g.label = 2;
                    case 2:
                        _g.trys.push([2, 4, , 5]);
                        _f = this;
                        return [4 /*yield*/, rte.enable(this, this.activeRte, { event: ev })];
                    case 3:
                        _f.activeRte = _g.sent();
                        return [3 /*break*/, 5];
                    case 4:
                        err_1 = _g.sent();
                        em.logError(err_1);
                        return [3 /*break*/, 5];
                    case 5:
                        this.toggleEvents(true);
                        return [2 /*return*/];
                }
            });
        });
    };
    ComponentTextView.prototype.onDisable = function (opts) {
        this.disableEditing(opts);
    };
    /**
     * Disable element content editing
     * @private
     * */
    ComponentTextView.prototype.disableEditing = function (opts) {
        if (opts === void 0) { opts = {}; }
        return __awaiter(this, void 0, void 0, function () {
            var _a, model, rte, activeRte, em, editable, err_2, _b;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        _a = this, model = _a.model, rte = _a.rte, activeRte = _a.activeRte, em = _a.em;
                        editable = model && model.get('editable');
                        if (!rte) return [3 /*break*/, 8];
                        _c.label = 1;
                    case 1:
                        _c.trys.push([1, 3, , 4]);
                        return [4 /*yield*/, rte.disable(this, activeRte, opts)];
                    case 2:
                        _c.sent();
                        return [3 /*break*/, 4];
                    case 3:
                        err_2 = _c.sent();
                        em.logError(err_2);
                        return [3 /*break*/, 4];
                    case 4:
                        _b = editable;
                        if (!_b) return [3 /*break*/, 6];
                        return [4 /*yield*/, this.getContent()];
                    case 5:
                        _b = (_c.sent()) !== this.lastContent;
                        _c.label = 6;
                    case 6:
                        if (!_b) return [3 /*break*/, 8];
                        return [4 /*yield*/, this.syncContent(opts)];
                    case 7:
                        _c.sent();
                        this.lastContent = '';
                        _c.label = 8;
                    case 8:
                        this.toggleEvents();
                        return [2 /*return*/];
                }
            });
        });
    };
    /**
     * get content from RTE
     * @return string
     */
    ComponentTextView.prototype.getContent = function () {
        return __awaiter(this, void 0, void 0, function () {
            var _a, rte, activeRte, result;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        _a = this, rte = _a.rte, activeRte = _a.activeRte;
                        result = '';
                        if (!rte) return [3 /*break*/, 2];
                        return [4 /*yield*/, rte.getContent(this, activeRte)];
                    case 1:
                        result = _b.sent();
                        _b.label = 2;
                    case 2: return [2 /*return*/, result];
                }
            });
        });
    };
    /**
     * Merge content from the DOM to the model
     */
    ComponentTextView.prototype.syncContent = function (opts) {
        if (opts === void 0) { opts = {}; }
        return __awaiter(this, void 0, void 0, function () {
            var _a, model, rte, rteEnabled, content, comps, contentOpt;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        _a = this, model = _a.model, rte = _a.rte, rteEnabled = _a.rteEnabled;
                        if (!rteEnabled && !opts.force)
                            return [2 /*return*/];
                        return [4 /*yield*/, this.getContent()];
                    case 1:
                        content = _b.sent();
                        comps = model.components();
                        contentOpt = ComponentTextView_assign({ fromDisable: 1 }, opts);
                        model.set('content', '', contentOpt);
                        // If there is a custom RTE the content is just added staticly
                        // inside 'content'
                        if ((rte === null || rte === void 0 ? void 0 : rte.customRte) && !rte.customRte.parseContent) {
                            comps.length &&
                                comps.reset(undefined, ComponentTextView_assign(ComponentTextView_assign({}, opts), { 
                                    // @ts-ignore
                                    keepIds: getComponentIds(comps) }));
                            model.set('content', content, contentOpt);
                        }
                        else {
                            comps.resetFromString(content, opts);
                        }
                        return [2 /*return*/];
                }
            });
        });
    };
    ComponentTextView.prototype.insertComponent = function (content, opts) {
        var _a;
        if (opts === void 0) { opts = {}; }
        var _b = this, model = _b.model, el = _b.el;
        var doc = el.ownerDocument;
        var selection = doc.getSelection();
        if (selection === null || selection === void 0 ? void 0 : selection.rangeCount) {
            var range = selection.getRangeAt(0);
            var textNode_1 = range.startContainer;
            var offset_1 = range.startOffset;
            var textModel_1 = (0,mixins.getComponentModel)(textNode_1);
            var newCmps_1 = [];
            if (textModel_1 && ((_a = textModel_1.is) === null || _a === void 0 ? void 0 : _a.call(textModel_1, 'textnode'))) {
                var cmps = textModel_1.collection;
                cmps.forEach(function (cmp) {
                    if (cmp === textModel_1) {
                        var type = 'textnode';
                        var cnt = opts.useDomContent ? textNode_1.textContent || '' : cmp.content;
                        newCmps_1.push({ type: type, content: cnt.slice(0, offset_1) });
                        newCmps_1.push(content);
                        newCmps_1.push({ type: type, content: cnt.slice(offset_1) });
                    }
                    else {
                        newCmps_1.push(cmp);
                    }
                });
                var result = newCmps_1.filter(Boolean);
                var index = result.indexOf(content);
                cmps.reset(result, opts);
                return cmps.at(index);
            }
        }
        return model.append(content, opts);
    };
    /**
     * Callback on input event
     * @param  {Event} e
     */
    ComponentTextView.prototype.onInput = function () {
        var em = this.em;
        var evPfx = 'component';
        var ev = ["".concat(evPfx, ":update"), "".concat(evPfx, ":input")].join(' ');
        // Update toolbars
        em && em.trigger(ev, this.model);
    };
    /**
     * Isolate disable propagation method
     * @param {Event}
     * @private
     * */
    ComponentTextView.prototype.disablePropagation = function (e) {
        e.stopPropagation();
    };
    /**
     * Enable/Disable events
     * @param {Boolean} enable
     */
    ComponentTextView.prototype.toggleEvents = function (enable) {
        var _a = this, em = _a.em, model = _a.model, $el = _a.$el;
        var mixins = { on: dom.on, off: dom/* off */.S1 };
        var method = enable ? 'on' : 'off';
        em.setEditing(enable ? this : false);
        this.rteEnabled = !!enable;
        // The ownerDocument is from the frame
        var elDocs = [this.el.ownerDocument, document];
        mixins.off(elDocs, 'mousedown', this.onDisable);
        mixins[method](elDocs, 'mousedown', this.onDisable);
        em[method]('toolbar:run:before', this.onDisable);
        if (model) {
            model[method]('removed', this.onDisable);
            model.trigger("rte:".concat(enable ? 'enable' : 'disable'));
        }
        // @ts-ignore Avoid closing edit mode on component click
        $el === null || $el === void 0 ? void 0 : $el.off('mousedown', this.disablePropagation);
        // @ts-ignore
        $el && $el[method]('mousedown', this.disablePropagation);
        // Fixes #2210 but use this also as a replacement
        // of this fix: bd7b804f3b46eb45b4398304b2345ce870f232d2
        if (this.config.draggableComponents) {
            var el = this.el;
            while (el) {
                el.draggable = enable ? !1 : !0;
                // Note: el.parentNode is sometimes null here
                el = el.parentNode;
                if (el && el.tagName == 'BODY') {
                    // @ts-ignore
                    el = 0;
                }
            }
        }
    };
    return ComponentTextView;
}(view_ComponentView));
/* harmony default export */ const view_ComponentTextView = (ComponentTextView);

;// CONCATENATED MODULE: ./src/dom_components/view/ComponentLinkView.ts
var ComponentLinkView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();

var ComponentLinkView = /** @class */ (function (_super) {
    ComponentLinkView_extends(ComponentLinkView, _super);
    function ComponentLinkView() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    ComponentLinkView.prototype.render = function () {
        _super.prototype.render.call(this);
        // I need capturing instead of bubbling as bubbled clicks from other
        // children will execute the link event
        this.el.addEventListener('click', this.prevDef, true);
        return this;
    };
    return ComponentLinkView;
}(view_ComponentTextView));
/* harmony default export */ const view_ComponentLinkView = (ComponentLinkView);

;// CONCATENATED MODULE: ./src/dom_components/view/ComponentLabelView.ts
var ComponentLabelView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();

var ComponentLabelView = /** @class */ (function (_super) {
    ComponentLabelView_extends(ComponentLabelView, _super);
    function ComponentLabelView() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    return ComponentLabelView;
}(view_ComponentLinkView));
/* harmony default export */ const view_ComponentLabelView = (ComponentLabelView);

;// CONCATENATED MODULE: ./src/dom_components/view/ComponentMapView.ts
var ComponentMapView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();

var ComponentMapView = /** @class */ (function (_super) {
    ComponentMapView_extends(ComponentMapView, _super);
    function ComponentMapView() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    ComponentMapView.prototype.tagName = function () {
        return 'div';
    };
    ComponentMapView.prototype.events = function () {
        return {};
    };
    ComponentMapView.prototype.initialize = function (props) {
        _super.prototype.initialize.call(this, props);
        this.classEmpty = this.ppfx + 'plh-map';
    };
    /**
     * Update the map on the canvas
     * @private
     */
    ComponentMapView.prototype.updateSrc = function () {
        this.getIframe().src = this.model.get('src');
    };
    ComponentMapView.prototype.getIframe = function () {
        if (!this.iframe) {
            var ifrm = document.createElement('iframe');
            ifrm.src = this.model.get('src');
            ifrm.frameBorder = '0';
            ifrm.style.height = '100%';
            ifrm.style.width = '100%';
            ifrm.className = this.ppfx + 'no-pointer';
            this.iframe = ifrm;
        }
        return this.iframe;
    };
    ComponentMapView.prototype.render = function () {
        _super.prototype.render.call(this);
        this.updateClasses();
        this.el.appendChild(this.getIframe());
        return this;
    };
    return ComponentMapView;
}(view_ComponentImageView));
/* harmony default export */ const view_ComponentMapView = (ComponentMapView);

;// CONCATENATED MODULE: ./src/dom_components/view/ComponentScriptView.ts
var ComponentScriptView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();

var ComponentScriptView = /** @class */ (function (_super) {
    ComponentScriptView_extends(ComponentScriptView, _super);
    function ComponentScriptView() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    ComponentScriptView.prototype.tagName = function () {
        return 'script';
    };
    ComponentScriptView.prototype.events = function () {
        return {};
    };
    return ComponentScriptView;
}(view_ComponentView));
/* harmony default export */ const view_ComponentScriptView = (ComponentScriptView);

;// CONCATENATED MODULE: ./src/dom_components/view/ComponentSvgView.ts
var ComponentSvgView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();

var ComponentSvgView = /** @class */ (function (_super) {
    ComponentSvgView_extends(ComponentSvgView, _super);
    function ComponentSvgView() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    ComponentSvgView.prototype._createElement = function (tagName) {
        return document.createElementNS('http://www.w3.org/2000/svg', tagName);
    };
    return ComponentSvgView;
}(view_ComponentView));
/* harmony default export */ const view_ComponentSvgView = (ComponentSvgView);

;// CONCATENATED MODULE: ./src/dom_components/view/ComponentTableBodyView.ts
var ComponentTableBodyView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();

var ComponentTableBodyView = /** @class */ (function (_super) {
    ComponentTableBodyView_extends(ComponentTableBodyView, _super);
    function ComponentTableBodyView() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    return ComponentTableBodyView;
}(view_ComponentView));
/* harmony default export */ const view_ComponentTableBodyView = (ComponentTableBodyView);

;// CONCATENATED MODULE: ./src/dom_components/view/ComponentTableCellView.ts
var ComponentTableCellView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();

var ComponentTableCellView = /** @class */ (function (_super) {
    ComponentTableCellView_extends(ComponentTableCellView, _super);
    function ComponentTableCellView() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    return ComponentTableCellView;
}(view_ComponentView));
/* harmony default export */ const view_ComponentTableCellView = (ComponentTableCellView);

;// CONCATENATED MODULE: ./src/dom_components/view/ComponentTableFootView.ts
var ComponentTableFootView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();

var ComponentTableFootView = /** @class */ (function (_super) {
    ComponentTableFootView_extends(ComponentTableFootView, _super);
    function ComponentTableFootView() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    return ComponentTableFootView;
}(view_ComponentView));
/* harmony default export */ const view_ComponentTableFootView = (ComponentTableFootView);

;// CONCATENATED MODULE: ./src/dom_components/view/ComponentTableHeadView.ts
var ComponentTableHeadView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();

var ComponentTableHeadView = /** @class */ (function (_super) {
    ComponentTableHeadView_extends(ComponentTableHeadView, _super);
    function ComponentTableHeadView() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    return ComponentTableHeadView;
}(view_ComponentView));
/* harmony default export */ const view_ComponentTableHeadView = (ComponentTableHeadView);

;// CONCATENATED MODULE: ./src/dom_components/view/ComponentTableRowView.ts
var ComponentTableRowView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();

var ComponentTableRowView = /** @class */ (function (_super) {
    ComponentTableRowView_extends(ComponentTableRowView, _super);
    function ComponentTableRowView() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    return ComponentTableRowView;
}(view_ComponentView));
/* harmony default export */ const view_ComponentTableRowView = (ComponentTableRowView);

;// CONCATENATED MODULE: ./src/dom_components/view/ComponentTableView.ts
var ComponentTableView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();

var ComponentTableView = /** @class */ (function (_super) {
    ComponentTableView_extends(ComponentTableView, _super);
    function ComponentTableView() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    ComponentTableView.prototype.events = function () {
        return {};
    };
    return ComponentTableView;
}(view_ComponentView));
/* harmony default export */ const view_ComponentTableView = (ComponentTableView);

;// CONCATENATED MODULE: ./src/dom_components/view/ComponentVideoView.ts
var ComponentVideoView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();


var ComponentVideoView = /** @class */ (function (_super) {
    ComponentVideoView_extends(ComponentVideoView, _super);
    function ComponentVideoView() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    ComponentVideoView.prototype.tagName = function () {
        return 'div';
    };
    // @ts-ignore
    ComponentVideoView.prototype.events = function () {
        return {};
    };
    ComponentVideoView.prototype.initialize = function () {
        // @ts-ignore
        view_ComponentView.prototype.initialize.apply(this, arguments);
        var model = this.model;
        var props = ['loop', 'autoplay', 'controls', 'color', 'rel', 'modestbranding', 'poster'];
        var events = props.map(function (p) { return "change:".concat(p); }).join(' ');
        this.listenTo(model, 'change:provider', this.updateProvider);
        this.listenTo(model, 'change:src', this.updateSrc);
        this.listenTo(model, events, this.updateVideo);
    };
    /**
     * Rerender on update of the provider
     * @private
     */
    ComponentVideoView.prototype.updateProvider = function () {
        var prov = this.model.get('provider');
        this.el.innerHTML = '';
        this.el.appendChild(this.renderByProvider(prov));
    };
    /**
     * Update the source of the video
     * @private
     */
    ComponentVideoView.prototype.updateSrc = function () {
        var _a = this, model = _a.model, videoEl = _a.videoEl;
        if (!videoEl)
            return;
        var prov = model.get('provider');
        var src = model.get('src');
        switch (prov) {
            case 'yt':
                src = model.getYoutubeSrc();
                break;
            case 'ytnc':
                src = model.getYoutubeNoCookieSrc();
                break;
            case 'vi':
                src = model.getVimeoSrc();
                break;
        }
        videoEl.src = src;
    };
    /**
     * Update video parameters
     * @private
     */
    ComponentVideoView.prototype.updateVideo = function () {
        var _a = this, model = _a.model, videoEl = _a.videoEl;
        var prov = model.get('provider');
        switch (prov) {
            case 'yt':
            case 'ytnc':
            case 'vi':
                model.trigger('change:videoId');
                break;
            default: {
                if (videoEl) {
                    var el = videoEl;
                    el.loop = model.get('loop');
                    el.autoplay = model.get('autoplay');
                    el.controls = model.get('controls');
                    el.poster = model.get('poster');
                }
            }
        }
    };
    ComponentVideoView.prototype.renderByProvider = function (prov) {
        var videoEl;
        switch (prov) {
            case 'yt':
                videoEl = this.renderYoutube();
                break;
            case 'ytnc':
                videoEl = this.renderYoutubeNoCookie();
                break;
            case 'vi':
                videoEl = this.renderVimeo();
                break;
            default:
                videoEl = this.renderSource();
        }
        this.videoEl = videoEl;
        return videoEl;
    };
    ComponentVideoView.prototype.renderSource = function () {
        var el = document.createElement('video');
        el.src = this.model.get('src');
        this.initVideoEl(el);
        return el;
    };
    ComponentVideoView.prototype.renderYoutube = function () {
        var el = document.createElement('iframe');
        el.src = this.model.getYoutubeSrc();
        el.frameBorder = '0';
        el.setAttribute('allowfullscreen', 'true');
        this.initVideoEl(el);
        return el;
    };
    ComponentVideoView.prototype.renderYoutubeNoCookie = function () {
        var el = document.createElement('iframe');
        el.src = this.model.getYoutubeNoCookieSrc();
        el.frameBorder = '0';
        el.setAttribute('allowfullscreen', 'true');
        this.initVideoEl(el);
        return el;
    };
    ComponentVideoView.prototype.renderVimeo = function () {
        var el = document.createElement('iframe');
        el.src = this.model.getVimeoSrc();
        el.frameBorder = '0';
        el.setAttribute('allowfullscreen', 'true');
        this.initVideoEl(el);
        return el;
    };
    ComponentVideoView.prototype.initVideoEl = function (el) {
        el.className = this.ppfx + 'no-pointer';
        el.style.height = '100%';
        el.style.width = '100%';
    };
    ComponentVideoView.prototype.render = function () {
        view_ComponentView.prototype.render.apply(this);
        this.updateClasses();
        var prov = this.model.get('provider');
        this.el.appendChild(this.renderByProvider(prov));
        this.updateVideo();
        return this;
    };
    return ComponentVideoView;
}(view_ComponentImageView));
/* harmony default export */ const view_ComponentVideoView = (ComponentVideoView);

;// CONCATENATED MODULE: ./src/dom_components/view/ComponentWrapperView.ts
var ComponentWrapperView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();

var ComponentWrapperView = /** @class */ (function (_super) {
    ComponentWrapperView_extends(ComponentWrapperView, _super);
    function ComponentWrapperView() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    ComponentWrapperView.prototype.tagName = function () {
        return 'div';
    };
    return ComponentWrapperView;
}(view_ComponentView));
/* harmony default export */ const view_ComponentWrapperView = (ComponentWrapperView);

;// CONCATENATED MODULE: ./src/dom_components/index.ts
var dom_components_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var dom_components_assign = (undefined && undefined.__assign) || function () {
    dom_components_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return dom_components_assign.apply(this, arguments);
};
var dom_components_rest = (undefined && undefined.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
/**
 * With this module is possible to manage components inside the canvas. You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](https://github.com/GrapesJS/grapesjs/blob/master/src/dom_components/config/config.ts)
 * ```js
 * const editor = grapesjs.init({
 *  domComponents: {
 *    // options
 *  }
 * })
 * ```
 *
 * Once the editor is instantiated you can use its API and listen to its events. Before using these methods, you should get the module from the instance.
 *
 * ```js
 * // Listen to events
 * editor.on('component:create', () => { ... });
 *
 * // Use the API
 * const cmp = editor.Components;
 * cmp.addType(...);
 * ```
 *
 * ## Available Events
 * * `component:create` - Component is created (only the model, is not yet mounted in the canvas), called after the init() method
 * * `component:mount` - Component is mounted to an element and rendered in canvas
 * * `component:add` - Triggered when a new component is added to the editor, the model is passed as an argument to the callback
 * * `component:remove` - Triggered when a component is removed, the model is passed as an argument to the callback
 * * `component:remove:before` - Triggered before the remove of the component, the model, remove function (if aborted via options, with this function you can complete the remove) and options (use options.abort = true to prevent remove), are passed as arguments to the callback
 * * `component:clone` - Triggered when a component is cloned, the new model is passed as an argument to the callback
 * * `component:update` - Triggered when a component is updated (moved, styled, etc.), the model is passed as an argument to the callback
 * * `component:update:{propertyName}` - Listen any property change, the model is passed as an argument to the callback
 * * `component:styleUpdate` - Triggered when the style of the component is updated, the model is passed as an argument to the callback
 * * `component:styleUpdate:{propertyName}` - Listen for a specific style property change, the model is passed as an argument to the callback
 * * `component:selected` - New component selected, the selected model is passed as an argument to the callback
 * * `component:deselected` - Component deselected, the deselected model is passed as an argument to the callback
 * * `component:toggled` - Component selection changed, toggled model is passed as an argument to the callback
 * * `component:type:add` - New component type added, the new type is passed as an argument to the callback
 * * `component:type:update` - Component type updated, the updated type is passed as an argument to the callback
 * * `component:drag:start` - Component drag started. Passed an object, to the callback, containing the `target` (component to drag), `parent` (parent of the component) and `index` (component index in the parent)
 * * `component:drag` - During component drag. Passed the same object as in `component:drag:start` event, but in this case, `parent` and `index` are updated by the current pointer
 * * `component:drag:end` - Component drag ended. Passed the same object as in `component:drag:start` event, but in this case, `parent` and `index` are updated by the final pointer
 * * `component:resize` - During component resize.
 *
 * ## Methods
 * * [getWrapper](#getwrapper)
 * * [getComponents](#getcomponents)
 * * [addComponent](#addcomponent)
 * * [clear](#clear)
 * * [addType](#addtype)
 * * [getType](#gettype)
 * * [getTypes](#gettypes)
 *
 * * [Component]: component.html
 *
 * @module Components
 */













































/** @private */
var CanMoveReason;
(function (CanMoveReason) {
    /**
     * Invalid source. This is a default value and should be ignored in case the `result` is true
     */
    CanMoveReason[CanMoveReason["InvalidSource"] = 0] = "InvalidSource";
    /**
     * Source doesn't accept target as destination.
     */
    CanMoveReason[CanMoveReason["SourceReject"] = 1] = "SourceReject";
    /**
     * Target doesn't accept source.
     */
    CanMoveReason[CanMoveReason["TargetReject"] = 2] = "TargetReject";
})(CanMoveReason || (CanMoveReason = {}));
var ComponentManager = /** @class */ (function (_super) {
    dom_components_extends(ComponentManager, _super);
    /**
     * Initialize module. Called on a new instance of the editor with configurations passed
     * inside 'domComponents' field
     * @param {Object} config Configurations
     * @private
     */
    function ComponentManager(em) {
        var _this = _super.call(this, em, 'DomComponents', new model_Components(undefined, { em: em })) || this;
        _this.componentTypes = [
            {
                id: 'cell',
                model: model_ComponentTableCell,
                view: view_ComponentTableCellView,
            },
            {
                id: 'row',
                model: model_ComponentTableRow,
                view: view_ComponentTableRowView,
            },
            {
                id: 'table',
                model: model_ComponentTable,
                view: view_ComponentTableView,
            },
            {
                id: 'thead',
                model: model_ComponentTableHead,
                view: view_ComponentTableHeadView,
            },
            {
                id: 'tbody',
                model: model_ComponentTableBody,
                view: view_ComponentTableBodyView,
            },
            {
                id: 'tfoot',
                model: model_ComponentTableFoot,
                view: view_ComponentTableFootView,
            },
            {
                id: 'map',
                model: model_ComponentMap,
                view: view_ComponentMapView,
            },
            {
                id: 'link',
                model: model_ComponentLink,
                view: view_ComponentLinkView,
            },
            {
                id: 'label',
                model: model_ComponentLabel,
                view: view_ComponentLabelView,
            },
            {
                id: 'video',
                model: model_ComponentVideo,
                view: view_ComponentVideoView,
            },
            {
                id: 'image',
                model: model_ComponentImage,
                view: view_ComponentImageView,
            },
            {
                id: 'script',
                model: model_ComponentScript,
                view: view_ComponentScriptView,
            },
            {
                id: 'svg-in',
                model: model_ComponentSvgIn,
                view: view_ComponentSvgView,
            },
            {
                id: 'svg',
                model: model_ComponentSvg,
                view: view_ComponentSvgView,
            },
            {
                id: 'iframe',
                model: model_ComponentFrame,
                view: view_ComponentFrameView,
            },
            {
                id: 'comment',
                model: model_ComponentComment,
                view: view_ComponentCommentView,
            },
            {
                id: 'textnode',
                model: model_ComponentTextNode,
                view: view_ComponentTextNodeView,
            },
            {
                id: 'text',
                model: model_ComponentText,
                view: view_ComponentTextView,
            },
            {
                id: 'wrapper',
                model: model_ComponentWrapper,
                view: view_ComponentWrapperView,
            },
            {
                id: 'default',
                model: model_Component,
                view: view_ComponentView,
            },
        ];
        _this.componentsById = {};
        _this.Component = model_Component;
        _this.Components = model_Components;
        _this.ComponentView = view_ComponentView;
        _this.ComponentsView = view_ComponentsView;
        /**
         * Name of the module
         * @type {String}
         * @private
         */
        //name = "DomComponents";
        _this.storageKey = 'components';
        if (em) {
            //@ts-ignore
            _this.config.components = em.config.components || _this.config.components;
        }
        for (var name in dom_components_config_config) {
            //@ts-ignore
            if (!(name in _this.config))
                _this.config[name] = dom_components_config_config[name];
        }
        var ppfx = _this.config.pStylePrefix;
        if (ppfx)
            _this.config.stylePrefix = ppfx + _this.config.stylePrefix;
        // Load dependencies
        if (em) {
            em.get('Parser').compTypes = _this.componentTypes;
            em.on('change:componentHovered', _this.componentHovered, _this);
            var selected_1 = em.get('selected');
            em.listenTo(selected_1, 'add', function (sel, c, opts) { return _this.selectAdd(selected_1.getComponent(sel), opts); });
            em.listenTo(selected_1, 'remove', function (sel, c, opts) { return _this.selectRemove(selected_1.getComponent(sel), opts); });
        }
        return _this;
    }
    ComponentManager.prototype.load = function (data) {
        var _this = this;
        return this.loadProjectData(data, {
            onResult: function (result) {
                var wrapper = _this.getWrapper();
                if (!wrapper) {
                    _this.em.Pages.add({}, { select: true });
                    wrapper = _this.getWrapper();
                }
                if ((0,index_all.isArray)(result)) {
                    result.length && wrapper.components(result);
                }
                else {
                    var _a = result.components, components = _a === void 0 ? [] : _a, rest = dom_components_rest(result, ["components"]);
                    wrapper.set(rest);
                    //@ts-ignore
                    wrapper.components(components);
                }
            },
        });
    };
    ComponentManager.prototype.store = function () {
        return {};
    };
    /**
     * Returns the main wrapper.
     * @return {Object}
     * @private
     */
    ComponentManager.prototype.getComponent = function () {
        var sel = this.em.Pages.getSelected();
        var frame = sel === null || sel === void 0 ? void 0 : sel.getMainFrame();
        return frame === null || frame === void 0 ? void 0 : frame.getComponent();
    };
    /**
     * Returns root component inside the canvas. Something like `<body>` inside HTML page
     * The wrapper doesn't differ from the original Component Model
     * @return {[Component]} Root Component
     * @example
     * // Change background of the wrapper and set some attribute
     * var wrapper = cmp.getWrapper();
     * wrapper.set('style', {'background-color': 'red'});
     * wrapper.set('attributes', {'title': 'Hello!'});
     */
    ComponentManager.prototype.getWrapper = function () {
        return this.getComponent();
    };
    /**
     * Returns wrapper's children collection. Once you have the collection you can
     * add other Components(Models) inside. Each component can have several nested
     * components inside and you can nest them as more as you wish.
     * @return {Components} Collection of components
     * @example
     * // Let's add some component
     * var wrapperChildren = cmp.getComponents();
     * var comp1 = wrapperChildren.add({
     *   style: { 'background-color': 'red'}
     * });
     * var comp2 = wrapperChildren.add({
     *   tagName: 'span',
     *   attributes: { title: 'Hello!'}
     * });
     * // Now let's add an other one inside first component
     * // First we have to get the collection inside. Each
     * // component has 'components' property
     * var comp1Children = comp1.get('components');
     * // Procede as before. You could also add multiple objects
     * comp1Children.add([
     *   { style: { 'background-color': 'blue'}},
     *   { style: { height: '100px', width: '100px'}}
     * ]);
     * // Remove comp2
     * wrapperChildren.remove(comp2);
     */
    ComponentManager.prototype.getComponents = function () {
        var wrp = this.getWrapper();
        return wrp === null || wrp === void 0 ? void 0 : wrp.components();
    };
    /**
     * Add new components to the wrapper's children. It's the same
     * as 'cmp.getComponents().add(...)'
     * @param {Object|[Component]|Array<Object>} component Component/s to add
     * @param {string} [component.tagName='div'] Tag name
     * @param {string} [component.type=''] Type of the component. Available: ''(default), 'text', 'image'
     * @param {boolean} [component.removable=true] If component is removable
     * @param {boolean} [component.draggable=true] If is possible to move the component around the structure
     * @param {boolean} [component.droppable=true] If is possible to drop inside other components
     * @param {boolean} [component.badgable=true] If the badge is visible when the component is selected
     * @param {boolean} [component.stylable=true] If is possible to style component
     * @param {boolean} [component.copyable=true] If is possible to copy&paste the component
     * @param {string} [component.content=''] String inside component
     * @param {Object} [component.style={}] Style object
     * @param {Object} [component.attributes={}] Attribute object
     * @param {Object} opt the options object to be used by the [Components.add]{@link getComponents} method
     * @return {[Component]|Array<[Component]>} Component/s added
     * @example
     * // Example of a new component with some extra property
     * var comp1 = cmp.addComponent({
     *   tagName: 'div',
     *   removable: true, // Can't remove it
     *   draggable: true, // Can't move it
     *   copyable: true, // Disable copy/past
     *   content: 'Content text', // Text inside component
     *   style: { color: 'red'},
     *   attributes: { title: 'here' }
     * });
     */
    ComponentManager.prototype.addComponent = function (component, opt) {
        if (opt === void 0) { opt = {}; }
        return this.getComponents().add(component, opt);
    };
    /**
     * Render and returns wrapper element with all components inside.
     * Once the wrapper is rendered, and it's what happens when you init the editor,
     * the all new components will be added automatically and property changes are all
     * updated immediately
     * @return {HTMLElement}
     * @private
     */
    ComponentManager.prototype.render = function () {
        var _a;
        return (_a = this.componentView) === null || _a === void 0 ? void 0 : _a.render().el;
    };
    /**
     * Remove all components
     * @return {this}
     */
    ComponentManager.prototype.clear = function (opts) {
        if (opts === void 0) { opts = {}; }
        var components = this.getComponents();
        //@ts-ignore
        components === null || components === void 0 ? void 0 : components.filter(Boolean).forEach(function (i) { return i.remove(opts); });
        return this;
    };
    /**
     * Set components
     * @param {Object|string} components HTML string or components model
     * @param {Object} opt the options object to be used by the {@link addComponent} method
     * @return {this}
     * @private
     */
    ComponentManager.prototype.setComponents = function (components, opt) {
        if (opt === void 0) { opt = {}; }
        this.clear(opt).addComponent(components, opt);
    };
    /**
     * Add new component type.
     * Read more about this in [Define New Component](https://grapesjs.com/docs/modules/Components.html#define-new-component)
     * @param {string} type Component ID
     * @param {Object} methods Component methods
     * @return {this}
     */
    ComponentManager.prototype.addType = function (type, methods) {
        var em = this.em;
        var _a = methods.model, model = _a === void 0 ? {} : _a, _b = methods.view, view = _b === void 0 ? {} : _b, isComponent = methods.isComponent, extend = methods.extend, extendView = methods.extendView, _c = methods.extendFn, extendFn = _c === void 0 ? [] : _c, _d = methods.extendFnView, extendFnView = _d === void 0 ? [] : _d;
        var compType = this.getType(type);
        var extendType = this.getType(extend);
        var extendViewType = this.getType(extendView);
        var typeToExtend = extendType ? extendType : compType ? compType : this.getType('default');
        var modelToExt = typeToExtend.model;
        var viewToExt = extendViewType ? extendViewType.view : typeToExtend.view;
        // Function for extending source object methods
        var getExtendedObj = function (fns, target, srcToExt) {
            return fns.reduce(function (res, next) {
                var fn = target[next];
                var parentFn = srcToExt.prototype[next];
                if (fn && parentFn) {
                    res[next] = function () {
                        var args = [];
                        for (var _i = 0; _i < arguments.length; _i++) {
                            args[_i] = arguments[_i];
                        }
                        parentFn.bind(this).apply(void 0, args);
                        fn.bind(this).apply(void 0, args);
                    };
                }
                return res;
            }, {});
        };
        // If the model/view is a simple object I need to extend it
        if (typeof model === 'object') {
            var modelDefaults_1 = { defaults: model.defaults };
            delete model.defaults;
            methods.model = modelToExt.extend(dom_components_assign(dom_components_assign({}, model), getExtendedObj(extendFn, model, modelToExt)), {
                isComponent: compType && !extendType && !isComponent ? modelToExt.isComponent : isComponent || (function () { return 0; }),
            });
            // Reassign the defaults getter to the model
            Object.defineProperty(methods.model.prototype, 'defaults', {
                get: function () { return (dom_components_assign(dom_components_assign({}, ((0,index_all.result)(modelToExt.prototype, 'defaults') || {})), ((0,index_all.result)(modelDefaults_1, 'defaults') || {}))); },
            });
        }
        if (typeof view === 'object') {
            methods.view = viewToExt.extend(dom_components_assign(dom_components_assign({}, view), getExtendedObj(extendFnView, view, viewToExt)));
        }
        if (compType) {
            compType.model = methods.model;
            compType.view = methods.view;
        }
        else {
            // @ts-ignore
            methods.id = type;
            this.componentTypes.unshift(methods);
        }
        var event = "component:type:".concat(compType ? 'update' : 'add');
        em === null || em === void 0 ? void 0 : em.trigger(event, compType || methods);
        return this;
    };
    ComponentManager.prototype.getType = function (type) {
        var df = this.componentTypes;
        for (var it = 0; it < df.length; it++) {
            var dfId = df[it].id;
            if (dfId == type) {
                return df[it];
            }
        }
        return;
    };
    /**
     * Remove component type
     * @param {string} type Component ID
     * @returns {Object|undefined} Removed component type, undefined otherwise
     */
    ComponentManager.prototype.removeType = function (id) {
        var df = this.componentTypes;
        var type = this.getType(id);
        if (!type)
            return;
        var index = df.indexOf(type);
        df.splice(index, 1);
        return type;
    };
    /**
     * Return the array of all types
     * @return {Array}
     */
    ComponentManager.prototype.getTypes = function () {
        return this.componentTypes;
    };
    ComponentManager.prototype.selectAdd = function (component, opts) {
        var _this = this;
        if (opts === void 0) { opts = {}; }
        if (component) {
            component.set({
                status: 'selected',
            });
            ['component:selected', 'component:toggled'].forEach(function (event) { return _this.em.trigger(event, component, opts); });
        }
    };
    ComponentManager.prototype.selectRemove = function (component, opts) {
        var _this = this;
        if (opts === void 0) { opts = {}; }
        if (component) {
            var em = this.em;
            component.set({
                status: '',
                state: '',
            });
            ['component:deselected', 'component:toggled'].forEach(function (event) { return _this.em.trigger(event, component, opts); });
        }
    };
    /**
     * Triggered when the component is hovered
     * @private
     */
    ComponentManager.prototype.componentHovered = function () {
        var em = this.em;
        var model = em.get('componentHovered');
        var previous = em.previous('componentHovered');
        var state = 'hovered';
        // Deselect the previous component
        previous &&
            previous.get('status') == state &&
            previous.set({
                status: '',
                state: '',
            });
        model && (0,index_all.isEmpty)(model.get('status')) && model.set('status', state);
    };
    ComponentManager.prototype.getShallowWrapper = function () {
        var _a = this, shallow = _a.shallow, em = _a.em;
        if (!shallow && em) {
            var shallowEm = em.shallow;
            if (!shallowEm)
                return;
            var domc = shallowEm.Components;
            domc.componentTypes = this.componentTypes;
            shallow = domc.getWrapper();
            if (shallow) {
                var events = [keyUpdate, keyUpdateInside].join(' ');
                shallow.on(events, (0,index_all.debounce)(function () { return shallow === null || shallow === void 0 ? void 0 : shallow.components(''); }, 100));
            }
            this.shallow = shallow;
        }
        return shallow;
    };
    /**
     * Check if the object is a [Component].
     * @param {Object} obj
     * @returns {Boolean}
     * @example
     * cmp.isComponent(editor.getSelected()); // true
     * cmp.isComponent({}); // false
     */
    ComponentManager.prototype.isComponent = function (obj) {
        return (0,mixins.isComponent)(obj);
    };
    /**
     * Check if a component can be moved inside another one.
     * @param {[Component]} target The target component is the one that is supposed to receive the source one.
     * @param {[Component]|String} source The source can be another component, a component definition or an HTML string.
     * @param {Number} [index] Index position, if not specified, the check will be performed against appending the source to the target.
     * @returns {Object} Object containing the `result` (Boolean), `source`, `target` (as Components), and a `reason` (Number) with these meanings:
     * * `0` - Invalid source. This is a default value and should be ignored in case the `result` is true.
     * * `1` - Source doesn't accept target as destination.
     * * `2` - Target doesn't accept source.
     * @example
     * const rootComponent = editor.getWrapper();
     * const someComponent = editor.getSelected();
     *
     * // Check with two components
     * editor.Components.canMove(rootComponent, someComponent);
     *
     * // Check with component definition
     * editor.Components.canMove(rootComponent, { tagName: 'a', draggable: false });
     *
     * // Check with HTML string
     * editor.Components.canMove(rootComponent, '<form>...</form>');
     */
    ComponentManager.prototype.canMove = function (target, source, index) {
        var result = {
            result: false,
            reason: CanMoveReason.InvalidSource,
            target: target,
            source: null,
        };
        if (!source || !target)
            return result;
        var srcModel = (0,mixins.isComponent)(source) ? source : null;
        if (!srcModel) {
            var wrapper = this.getShallowWrapper();
            srcModel = (wrapper === null || wrapper === void 0 ? void 0 : wrapper.append(source)[0]) || null;
        }
        result.source = srcModel;
        if (!srcModel)
            return result;
        // Check if the source is draggable in the target
        var draggable = srcModel.get('draggable');
        if ((0,index_all.isFunction)(draggable)) {
            draggable = !!draggable(srcModel, target, index);
        }
        else {
            var el = target.getEl();
            draggable = (0,index_all.isArray)(draggable) ? draggable.join(',') : draggable;
            draggable = (0,index_all.isString)(draggable) ? el === null || el === void 0 ? void 0 : el.matches(draggable) : draggable;
        }
        if (!draggable)
            return dom_components_assign(dom_components_assign({}, result), { reason: CanMoveReason.SourceReject });
        // Check if the target accepts the source
        var droppable = target.get('droppable');
        if ((0,index_all.isFunction)(droppable)) {
            droppable = !!droppable(srcModel, target, index);
        }
        else {
            if (droppable === false && target.isInstanceOf('text') && srcModel.get('textable')) {
                droppable = true;
            }
            else {
                var el = srcModel.getEl();
                droppable = (0,index_all.isArray)(droppable) ? droppable.join(',') : droppable;
                droppable = (0,index_all.isString)(droppable) ? el === null || el === void 0 ? void 0 : el.matches(droppable) : droppable;
            }
        }
        // Ensure the target is not inside the source
        var isTargetInside = [target].concat(target.parents()).indexOf(srcModel) > -1;
        if (!droppable || isTargetInside)
            return dom_components_assign(dom_components_assign({}, result), { reason: CanMoveReason.TargetReject });
        return dom_components_assign(dom_components_assign({}, result), { result: true });
    };
    ComponentManager.prototype.allById = function () {
        return this.componentsById;
    };
    ComponentManager.prototype.getById = function (id) {
        return this.componentsById[id] || null;
    };
    ComponentManager.prototype.destroy = function () {
        var _a;
        var all = this.allById();
        Object.keys(all).forEach(function (id) { return all[id] && all[id].remove(); });
        (_a = this.componentView) === null || _a === void 0 ? void 0 : _a.remove();
        [this.em, this.componentsById, this.componentView].forEach(function (i) { return (i = {}); });
    };
    return ComponentManager;
}(ItemManagerModule));
/* harmony default export */ const dom_components = (ComponentManager);

;// CONCATENATED MODULE: ./src/css_composer/config/config.ts
var css_composer_config_config_config = {
    stylePrefix: 'css-',
    rules: [],
};
/* harmony default export */ const css_composer_config_config = (css_composer_config_config_config);

;// CONCATENATED MODULE: ./src/code_manager/model/CssGenerator.ts
var CssGenerator_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();



var maxValue = Number.MAX_VALUE;
var getMediaLength = function (mediaQuery) {
    var length = /(-?\d*\.?\d+)\w{0,}/.exec(mediaQuery);
    return !length ? '' : length[0];
};
var CssGenerator = /** @class */ (function (_super) {
    CssGenerator_extends(CssGenerator, _super);
    function CssGenerator() {
        var _this = _super.call(this) || this;
        (0,index_all.bindAll)(_this, 'sortRules');
        _this.compCls = [];
        _this.ids = [];
        return _this;
    }
    /**
     * Get CSS from a component
     * @param {Model} model
     * @return {String}
     */
    CssGenerator.prototype.buildFromModel = function (model, opts) {
        var _this = this;
        if (opts === void 0) { opts = {}; }
        var code = '';
        var em = this.em;
        var avoidInline = em && em.getConfig().avoidInlineStyle;
        var style = model.styleToString();
        var classes = model.classes;
        this.ids.push("#".concat(model.getId()));
        // Let's know what classes I've found
        classes.forEach(function (model) { return _this.compCls.push(model.getFullName()); });
        if (!avoidInline && style) {
            code = "#".concat(model.getId(), "{").concat(style, "}");
        }
        var components = model.components();
        components.forEach(function (model) { return (code += _this.buildFromModel(model, opts)); });
        return code;
    };
    CssGenerator.prototype.build = function (model, opts) {
        var _this = this;
        if (opts === void 0) { opts = {}; }
        var json = opts.json;
        var em = opts.em;
        var cssc = opts.cssc || (em === null || em === void 0 ? void 0 : em.Css);
        this.em = em;
        this.compCls = [];
        this.ids = [];
        this.model = model;
        var codeJson = [];
        var code = model ? this.buildFromModel(model, opts) : '';
        var clearStyles = (0,index_all.isUndefined)(opts.clearStyles) && em ? em.getConfig().clearStyles : opts.clearStyles;
        if (cssc) {
            var rules = opts.rules || cssc.getAll();
            var atRules_1 = {};
            var dump_1 = [];
            if (opts.onlyMatched && model && (0,mixins.hasWin)()) {
                rules = this.matchedRules(model, rules);
            }
            rules.forEach(function (rule) {
                var atRule = rule.getAtRule();
                if (atRule) {
                    var mRules = atRules_1[atRule];
                    if (mRules) {
                        mRules.push(rule);
                    }
                    else {
                        atRules_1[atRule] = [rule];
                    }
                    return;
                }
                var res = _this.buildFromRule(rule, dump_1, opts);
                if (json) {
                    codeJson.push(res);
                }
                else {
                    code += res;
                }
            });
            this.sortMediaObject(atRules_1).forEach(function (item) {
                var rulesStr = '';
                var atRule = item.key;
                var mRules = item.value;
                mRules.forEach(function (rule) {
                    var ruleStr = _this.buildFromRule(rule, dump_1, opts);
                    if (rule.get('singleAtRule')) {
                        code += "".concat(atRule, "{").concat(ruleStr, "}");
                    }
                    else {
                        rulesStr += ruleStr;
                    }
                    json && codeJson.push(ruleStr);
                });
                if (rulesStr) {
                    code += "".concat(atRule, "{").concat(rulesStr, "}");
                }
            });
            // @ts-ignore
            em && clearStyles && rules.remove && rules.remove(dump_1);
        }
        return json ? codeJson.filter(function (r) { return r; }) : code;
    };
    /**
     * Get CSS from the rule model
     * @param {Model} rule
     * @return {string} CSS string
     */
    CssGenerator.prototype.buildFromRule = function (rule, dump, opts) {
        var _this = this;
        var _a;
        if (opts === void 0) { opts = {}; }
        var result = '';
        var model = this.model;
        var selectorStrNoAdd = rule.selectorsToString({ skipAdd: 1 });
        var selectorsAdd = rule.get('selectorsAdd');
        var singleAtRule = rule.get('singleAtRule');
        var found;
        // This will not render a rule if there is no its component
        (_a = rule.get('selectors')) === null || _a === void 0 ? void 0 : _a.forEach(function (selector) {
            var name = selector.getFullName();
            if (_this.compCls.indexOf(name) >= 0 || _this.ids.indexOf(name) >= 0 || opts.keepUnusedStyles) {
                found = 1;
            }
        });
        if ((selectorStrNoAdd && found) || selectorsAdd || singleAtRule || !model) {
            var block = rule.getDeclaration({ body: 1 });
            block && (opts.json ? (result = rule) : (result += block));
        }
        else {
            dump.push(rule);
        }
        return result;
    };
    /**
     * Get matched rules of a component
     * @param {Component} component
     * @param {Array<CSSRule>} rules
     * @returns {Array<CSSRule>}
     */
    CssGenerator.prototype.matchedRules = function (component, rules) {
        var _this = this;
        var el = component.getEl();
        var result = [];
        rules.forEach(function (rule) {
            try {
                if (rule
                    .selectorsToString()
                    .split(',')
                    .some(function (selector) { return el === null || el === void 0 ? void 0 : el.matches(_this.__cleanSelector(selector)); })) {
                    result.push(rule);
                }
            }
            catch (err) { }
        });
        component.components().forEach(function (component) {
            result = result.concat(_this.matchedRules(component, rules));
        });
        // Remove duplicates
        result = result.filter(function (rule, i) { return result.indexOf(rule) === i; });
        return result;
    };
    /**
     * Get the numeric length of the media query string
     * @param  {String} mediaQuery Media query string
     * @return {Number}
     */
    CssGenerator.prototype.getQueryLength = function (mediaQuery) {
        var length = /(-?\d*\.?\d+)\w{0,}/.exec(mediaQuery);
        if (!length)
            return maxValue;
        return parseFloat(length[1]);
    };
    /**
     * Return a sorted array from media query object
     * @param  {Object} items
     * @return {Array}
     */
    CssGenerator.prototype.sortMediaObject = function (items) {
        var _this = this;
        if (items === void 0) { items = {}; }
        var itemsArr = [];
        (0,index_all.each)(items, function (value, key) { return itemsArr.push({ key: key, value: value }); });
        return itemsArr.sort(function (a, b) {
            var isMobFirst = [a.key, b.key].every(function (mquery) { return mquery.indexOf('min-width') !== -1; });
            var left = isMobFirst ? a.key : b.key;
            var right = isMobFirst ? b.key : a.key;
            return _this.getQueryLength(left) - _this.getQueryLength(right);
        });
    };
    CssGenerator.prototype.sortRules = function (a, b) {
        var getKey = function (rule) { return rule.get('mediaText') || ''; };
        var isMobFirst = [getKey(a), getKey(b)].every(function (q) { return q.indexOf('min-width') !== -1; });
        var left = isMobFirst ? getKey(a) : getKey(b);
        var right = isMobFirst ? getKey(b) : getKey(a);
        return this.getQueryLength(left) - this.getQueryLength(right);
    };
    /**
     * Return passed selector without states
     * @param {String} selector
     * @returns {String}
     * @private
     */
    CssGenerator.prototype.__cleanSelector = function (selector) {
        return selector
            .split(' ')
            .map(function (item) { return item.split(':')[0]; })
            .join(' ');
    };
    return CssGenerator;
}(common/* Model */.Hn));
/* harmony default export */ const model_CssGenerator = (CssGenerator);

;// CONCATENATED MODULE: ./src/css_composer/model/CssRule.ts
var CssRule_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var CssRule_assign = (undefined && undefined.__assign) || function () {
    CssRule_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return CssRule_assign.apply(this, arguments);
};
var CssRule_spreadArray = (undefined && undefined.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};






// @ts-ignore
var CSS = ((0,mixins.hasWin)() ? window : {}).CSS;
/**
 * @typedef CssRule
 * @property {Array<Selector>} selectors Array of selectors
 * @property {Object} style Object containing style definitions
 * @property {String} [selectorsAdd=''] Additional string css selectors
 * @property {String} [atRuleType=''] Type of at-rule, eg. `media`, 'font-face'
 * @property {String} [mediaText=''] At-rule value, eg. `(max-width: 1000px)`
 * @property {Boolean} [singleAtRule=false] This property is used only on at-rules, like 'page' or 'font-face', where the block containes only style declarations
 * @property {String} [state=''] State of the rule, eg: `hover`, `focused`
 * @property {Boolean|Array<String>} [important=false] If true, sets `!important` on all properties. You can also pass an array to specify properties on which use important
 * @property {Boolean} [stylable=true] Indicates if the rule is stylable from the editor
 *
 * [Device]: device.html
 * [State]: state.html
 * [Component]: component.html
 */
var CssRule = /** @class */ (function (_super) {
    CssRule_extends(CssRule, _super);
    function CssRule(props, opt) {
        if (opt === void 0) { opt = {}; }
        var _this = _super.call(this, props) || this;
        _this.config = props || {};
        _this.opt = opt;
        _this.em = opt.em;
        _this.ensureSelectors(null, null, {});
        _this.on('change', _this.__onChange);
        return _this;
    }
    CssRule.prototype.defaults = function () {
        return {
            selectors: [],
            selectorsAdd: '',
            style: {},
            mediaText: '',
            state: '',
            stylable: true,
            atRuleType: '',
            singleAtRule: false,
            important: false,
            group: '',
            shallow: false,
            _undo: true,
        };
    };
    CssRule.prototype.__onChange = function (m, opts) {
        var em = this.em;
        var changed = this.changedAttributes();
        changed && !(0,mixins.isEmptyObj)(changed) && (em === null || em === void 0 ? void 0 : em.changesUp(opts));
    };
    CssRule.prototype.clone = function () {
        var opts = CssRule_assign({}, this.opt);
        var attr = CssRule_assign({}, this.attributes);
        attr.selectors = this.get('selectors').map(function (s) { return s.clone(); });
        // @ts-ignore
        return new this.constructor(attr, opts);
    };
    CssRule.prototype.ensureSelectors = function (m, c, opts) {
        var em = this.em;
        var sm = em === null || em === void 0 ? void 0 : em.get('SelectorManager');
        var toListen = [this, 'change:selectors', this.ensureSelectors];
        var sels = this.getSelectors();
        this.stopListening.apply(this, toListen);
        if (sels.models) {
            sels = CssRule_spreadArray([], sels.models, true);
        }
        sels = (0,index_all.isString)(sels) ? [sels] : sels;
        if (Array.isArray(sels)) {
            var res = sels.filter(function (i) { return i; }).map(function (i) { return (sm ? sm.add(i) : i); });
            sels = new model_Selectors(res);
        }
        this.set('selectors', sels, opts);
        // @ts-ignore
        this.listenTo.apply(this, toListen);
    };
    /**
     * Returns the at-rule statement when exists, eg. `@media (...)`, `@keyframes`
     * @returns {String}
     * @example
     * const cssRule = editor.Css.setRule('.class1', { color: 'red' }, {
     *  atRuleType: 'media',
     *  atRuleParams: '(min-width: 500px)'
     * });
     * cssRule.getAtRule(); // "@media (min-width: 500px)"
     */
    CssRule.prototype.getAtRule = function () {
        var type = this.get('atRuleType');
        var condition = this.get('mediaText');
        // Avoid breaks with the last condition
        var typeStr = type ? "@".concat(type) : condition ? '@media' : '';
        return typeStr + (condition && typeStr ? " ".concat(condition) : '');
    };
    /**
     * Return selectors of the rule as a string
     * @param {Object} [opts] Options
     * @param {Boolean} [opts.skipState] Skip state from the result
     * @returns {String}
     * @example
     * const cssRule = editor.Css.setRule('.class1:hover', { color: 'red' });
     * cssRule.selectorsToString(); // ".class1:hover"
     * cssRule.selectorsToString({ skipState: true }); // ".class1"
     */
    CssRule.prototype.selectorsToString = function (opts) {
        if (opts === void 0) { opts = {}; }
        var result = [];
        var state = this.get('state');
        var addSelector = this.get('selectorsAdd');
        var selOpts = {
            escape: function (str) { return (CSS && CSS.escape ? CSS.escape(str) : str); },
        };
        // @ts-ignore
        var selectors = this.get('selectors').getFullString(0, selOpts);
        var stateStr = state && !opts.skipState ? ":".concat(state) : '';
        selectors && result.push("".concat(selectors).concat(stateStr));
        addSelector && !opts.skipAdd && result.push(addSelector);
        return result.join(', ');
    };
    /**
     * Get declaration block (without the at-rule statement)
     * @param {Object} [opts={}] Options (same as in `selectorsToString`)
     * @returns {String}
     * @example
     * const cssRule = editor.Css.setRule('.class1', { color: 'red' }, {
     *  atRuleType: 'media',
     *  atRuleParams: '(min-width: 500px)'
     * });
     * cssRule.getDeclaration() // ".class1{color:red;}"
     */
    CssRule.prototype.getDeclaration = function (opts) {
        if (opts === void 0) { opts = {}; }
        var result = '';
        var important = this.attributes.important;
        var selectors = this.selectorsToString(opts);
        var style = this.styleToString(CssRule_assign({ important: important }, opts));
        var singleAtRule = this.get('singleAtRule');
        if ((selectors || singleAtRule) && (style || opts.allowEmpty)) {
            result = singleAtRule ? style : "".concat(selectors, "{").concat(style, "}");
        }
        return result;
    };
    /**
     * Get the Device the rule is related to.
     * @returns {[Device]|null}
     * @example
     * const device = rule.getDevice();
     * console.log(device?.getName());
     */
    CssRule.prototype.getDevice = function () {
        var em = this.em;
        var _a = this.attributes, atRuleType = _a.atRuleType, mediaText = _a.mediaText;
        var devices = (em === null || em === void 0 ? void 0 : em.get('DeviceManager').getDevices()) || [];
        var deviceDefault = devices.filter(function (d) { return d.getWidthMedia() === ''; })[0];
        if (atRuleType !== 'media' || !mediaText) {
            return deviceDefault || null;
        }
        return devices.filter(function (d) { return d.getWidthMedia() === getMediaLength(mediaText); })[0] || null;
    };
    /**
     * Get the State the rule is related to.
     * @returns {[State]|null}
     * @example
     * const state = rule.getState();
     * console.log(state?.getLabel());
     */
    CssRule.prototype.getState = function () {
        var em = this.em;
        var stateValue = this.get('state');
        var states = (em === null || em === void 0 ? void 0 : em.get('SelectorManager').getStates()) || [];
        return states.filter(function (s) { return s.getName() === stateValue; })[0] || null;
    };
    /**
     * Returns the related Component (valid only for component-specific rules).
     * @returns {[Component]|null}
     * @example
     * const cmp = rule.getComponent();
     * console.log(cmp?.toHTML());
     */
    CssRule.prototype.getComponent = function () {
        var _a;
        var sel = this.getSelectors();
        var sngl = sel.length == 1 && sel.at(0);
        var cmpId = sngl && sngl.isId() && sngl.get('name');
        return (cmpId && ((_a = this.em) === null || _a === void 0 ? void 0 : _a.Components.getById(cmpId))) || null;
    };
    /**
     * Return the CSS string of the rule
     * @param {Object} [opts={}] Options (same as in `getDeclaration`)
     * @return {String} CSS string
     * @example
     * const cssRule = editor.Css.setRule('.class1', { color: 'red' }, {
     *  atRuleType: 'media',
     *  atRuleParams: '(min-width: 500px)'
     * });
     * cssRule.toCSS() // "@media (min-width: 500px){.class1{color:red;}}"
     */
    CssRule.prototype.toCSS = function (opts) {
        if (opts === void 0) { opts = {}; }
        var result = '';
        var atRule = this.getAtRule();
        var block = this.getDeclaration(opts);
        if (block || opts.allowEmpty) {
            result = block;
        }
        if (atRule && result) {
            result = "".concat(atRule, "{").concat(result, "}");
        }
        return result;
    };
    CssRule.prototype.toJSON = function () {
        var _a;
        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            args[_i] = arguments[_i];
        }
        var obj = common/* Model */.Hn.prototype.toJSON.apply(this, args);
        if ((_a = this.em) === null || _a === void 0 ? void 0 : _a.getConfig().avoidDefaults) {
            var defaults = this.defaults();
            (0,index_all.forEach)(defaults, function (value, key) {
                if (obj[key] === value) {
                    delete obj[key];
                }
            });
            // Delete the property used for partial updates
            delete obj.style.__p;
            if ((0,index_all.isEmpty)(obj.selectors))
                delete obj.selectors;
            if ((0,index_all.isEmpty)(obj.style))
                delete obj.style;
        }
        return obj;
    };
    /**
     * Compare the actual model with parameters
     * @param {Object} selectors Collection of selectors
     * @param {String} state Css rule state
     * @param {String} width For which device this style is oriented
     * @param {Object} ruleProps Other rule props
     * @returns  {Boolean}
     * @private
     */
    CssRule.prototype.compare = function (selectors, state, width, ruleProps) {
        var _a;
        if (ruleProps === void 0) { ruleProps = {}; }
        var st = state || '';
        var wd = width || '';
        var selAdd = ruleProps.selectorsAdd || '';
        var atRule = ruleProps.atRuleType || '';
        var sel = !(0,index_all.isArray)(selectors) && !selectors.models ? [selectors] : selectors.models || selectors;
        // Fix atRuleType in case is not specified with width
        if (wd && !atRule)
            atRule = 'media';
        var a1 = sel.map(function (model) { return model.getFullName(); });
        var a2 = (_a = this.get('selectors')) === null || _a === void 0 ? void 0 : _a.map(function (model) { return model.getFullName(); });
        // Check selectors
        var a1S = a1.slice().sort();
        var a2S = a2.slice().sort();
        if (a1.length !== a2.length || !a1S.every(function (v, i) { return v === a2S[i]; })) {
            return false;
        }
        // Check other properties
        if (this.get('state') !== st ||
            this.get('mediaText') !== wd ||
            this.get('selectorsAdd') !== selAdd ||
            this.get('atRuleType') !== atRule) {
            return false;
        }
        return true;
    };
    return CssRule;
}(model_StyleableModel));
/* harmony default export */ const model_CssRule = (CssRule);

;// CONCATENATED MODULE: ./src/css_composer/model/CssRules.ts
var CssRules_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();


var CssRules = /** @class */ (function (_super) {
    CssRules_extends(CssRules, _super);
    function CssRules(props, opt) {
        var _this = _super.call(this, props) || this;
        // Inject editor
        _this.editor = opt === null || opt === void 0 ? void 0 : opt.em;
        // This will put the listener post CssComposer.postLoad
        setTimeout(function () {
            _this.on('remove', _this.onRemove);
            _this.on('add', _this.onAdd);
        });
        return _this;
    }
    CssRules.prototype.toJSON = function (opts) {
        var result = common/* Collection */.FE.prototype.toJSON.call(this, opts);
        return result.filter(function (rule) { return rule.style && !rule.shallow; });
    };
    CssRules.prototype.onAdd = function (model, c, o) {
        model.ensureSelectors(model, c, o); // required for undo
    };
    CssRules.prototype.onRemove = function (removed) {
        var em = this.editor;
        em.stopListening(removed);
        em.UndoManager.remove(removed);
    };
    /** @ts-ignore */
    CssRules.prototype.add = function (models, opt) {
        if (opt === void 0) { opt = {}; }
        if (typeof models === 'string') {
            models = this.editor.get('Parser').parseCss(models);
        }
        opt.em = this.editor;
        return common/* Collection */.FE.prototype.add.apply(this, [models, opt]);
    };
    return CssRules;
}(common/* Collection */.FE));
/* harmony default export */ const model_CssRules = (CssRules);
CssRules.prototype.model = model_CssRule;

;// CONCATENATED MODULE: ./src/css_composer/index.ts
/**
 * This module manages CSS rules in the canvas.
 * You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](https://github.com/GrapesJS/grapesjs/blob/master/src/css_composer/config/config.ts)
 * ```js
 * const editor = grapesjs.init({
 *  cssComposer: {
 *    // options
 *  }
 * })
 * ```
 *
 * Once the editor is instantiated you can use its API. Before using these methods you should get the module from the instance
 *
 * ```js
 * const css = editor.Css;
 * ```
 *
 * * [addRules](#addrules)
 * * [setRule](#setrule)
 * * [getRule](#getrule)
 * * [getRules](#getrules)
 * * [remove](#remove)
 * * [clear](#clear)
 *
 * [CssRule]: css_rule.html
 *
 * @module Css
 */
var css_composer_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var css_composer_assign = (undefined && undefined.__assign) || function () {
    css_composer_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return css_composer_assign.apply(this, arguments);
};
var css_composer_spreadArray = (undefined && undefined.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};









var CssComposer = /** @class */ (function (_super) {
    css_composer_extends(CssComposer, _super);
    /**
     * Initializes module. Automatically called with a new instance of the editor
     * @param {Object} config Configurations
     * @private
     */
    function CssComposer(em) {
        var _this = _super.call(this, em, 'CssComposer', null, {}, css_composer_config_config) || this;
        _this.Selectors = model_Selectors;
        _this.storageKey = 'styles';
        var config = _this.config;
        var ppfx = config.pStylePrefix;
        if (ppfx)
            config.stylePrefix = ppfx + config.stylePrefix;
        // @ts-ignore
        config.rules = _this.em.config.style || config.rules || '';
        _this.rules = new model_CssRules([], config);
        return _this;
    }
    /**
     * On load callback
     * @private
     */
    CssComposer.prototype.onLoad = function () {
        this.rules.add(this.config.rules, { silent: true });
    };
    /**
     * Do stuff after load
     * @param  {Editor} em
     * @private
     */
    CssComposer.prototype.postLoad = function () {
        var _a;
        var um = (_a = this.em) === null || _a === void 0 ? void 0 : _a.get('UndoManager');
        um && um.add(this.getAll());
    };
    CssComposer.prototype.store = function () {
        return this.getProjectData();
    };
    CssComposer.prototype.load = function (data) {
        return this.loadProjectData(data, {
            // @ts-ignore Fix add() first in CssRules
            all: this.rules,
        });
    };
    /**
     * Add new rule to the collection, if not yet exists with the same selectors
     * @param {Array<Selector>} selectors Array of selectors
     * @param {String} state Css rule state
     * @param {String} width For which device this style is oriented
     * @param {Object} props Other props for the rule
     * @param {Object} opts Options for the add of new rule
     * @return {Model}
     * @private
     * @example
     * var sm = editor.SelectorManager;
     * var sel1 = sm.add('myClass1');
     * var sel2 = sm.add('myClass2');
     * var rule = cssComposer.add([sel1, sel2], 'hover');
     * rule.set('style', {
     *   width: '100px',
     *   color: '#fff',
     * });
     * */
    CssComposer.prototype.add = function (selectors, state, width, opts, addOpts) {
        if (opts === void 0) { opts = {}; }
        if (addOpts === void 0) { addOpts = {}; }
        var s = state || '';
        var w = width || '';
        var opt = css_composer_assign({}, opts);
        var rule = this.get(selectors, s, w, opt);
        // do not create rules that were found before
        // unless this is a single at-rule, for which multiple declarations
        // make sense (e.g. multiple `@font-type`s)
        if (rule && rule.config && !rule.config.singleAtRule) {
            return rule;
        }
        else {
            opt.state = s;
            opt.mediaText = w;
            opt.selectors = [];
            // #4727: Prevent updating atRuleType if already defined
            if (w && !opt.atRuleType) {
                opt.atRuleType = 'media';
            }
            rule = new model_CssRule(opt, this.config);
            // @ts-ignore
            rule.get('selectors').add(selectors, addOpts);
            this.rules.add(rule, addOpts);
            return rule;
        }
    };
    /**
     * Get the rule
     * @param {String|Array<Selector>} selectors Array of selectors or selector string, eg `.myClass1.myClass2`
     * @param {String} state Css rule state, eg. 'hover'
     * @param {String} width Media rule value, eg. '(max-width: 992px)'
     * @param {Object} ruleProps Other rule props
     * @return  {Model|null}
     * @private
     * @example
     * const sm = editor.SelectorManager;
     * const sel1 = sm.add('myClass1');
     * const sel2 = sm.add('myClass2');
     * const rule = cssComposer.get([sel1, sel2], 'hover', '(max-width: 992px)');
     * // Update the style
     * rule.set('style', {
     *   width: '300px',
     *   color: '#000',
     * });
     * */
    CssComposer.prototype.get = function (selectors, state, width, ruleProps) {
        var slc = selectors;
        if ((0,index_all.isString)(selectors)) {
            var sm = this.em.Selectors;
            var singleSel = selectors.split(',')[0].trim();
            var node = this.em.Parser.parserCss.checkNode({ selectors: singleSel })[0];
            slc = sm.get(node.selectors);
        }
        return this.rules.find(function (rule) { return rule.compare(slc, state, width, ruleProps); }) || null;
    };
    CssComposer.prototype.getAll = function () {
        return this.rules;
    };
    /**
     * Add a raw collection of rule objects
     * This method overrides styles, in case, of already defined rule
     * @param {String|Array<Object>} data CSS string or an array of rule objects, eg. [{selectors: ['class1'], style: {....}}, ..]
     * @param {Object} opts Options
     * @param {Object} props Additional properties to add on rules
     * @return {Array<Model>}
     * @private
     */
    CssComposer.prototype.addCollection = function (data, opts, props) {
        if (opts === void 0) { opts = {}; }
        if (props === void 0) { props = {}; }
        var em = this.em;
        var result = [];
        if ((0,index_all.isString)(data)) {
            data = em.Parser.parseCss(data);
        }
        var d = data instanceof Array ? data : [data];
        for (var i = 0, l = d.length; i < l; i++) {
            var rule = (d[i] || {});
            if (!rule.selectors)
                continue;
            var sm = em === null || em === void 0 ? void 0 : em.Selectors;
            if (!sm)
                console.warn('Selector Manager not found');
            var sl = rule.selectors;
            var sels = sl instanceof Array ? sl : [sl];
            var newSels = [];
            for (var j = 0, le = sels.length; j < le; j++) {
                // @ts-ignore
                var selec = sm.add(sels[j]);
                newSels.push(selec);
            }
            var modelExists = this.get(newSels, rule.state, rule.mediaText, rule);
            var model = this.add(newSels, rule.state, rule.mediaText, rule, opts);
            var updateStyle = !modelExists || !opts.avoidUpdateStyle;
            var style = rule.style || {};
            (0,mixins.isObject)(props) && model.set(props, opts);
            if (updateStyle) {
                var styleUpdate = opts.extend ? css_composer_assign(css_composer_assign({}, model.get('style')), style) : style;
                model.set('style', styleUpdate, opts);
            }
            result.push(model);
        }
        return result;
    };
    /**
     * Add CssRules via CSS string.
     * @param {String} css CSS string of rules to add.
     * @returns {Array<[CssRule]>} Array of rules
     * @example
     * const addedRules = css.addRules('.my-cls{ color: red } @media (max-width: 992px) { .my-cls{ color: darkred } }');
     * // Check rules
     * console.log(addedRules.map(rule => rule.toCSS()));
     */
    CssComposer.prototype.addRules = function (css) {
        return this.addCollection(css);
    };
    /**
     * Add/update the CssRule.
     * @param {String} selectors Selector string, eg. `.myclass`
     * @param {Object} style  Style properties and values. If the rule exists, styles will be replaced unless `addStyles` option is used.
     * @param {Object} [opts={}]  Additional properties.
     * @param {String} [opts.atRuleType='']  At-rule type, eg. `media`.
     * @param {String} [opts.atRuleParams='']  At-rule parameters, eg. `(min-width: 500px)`.
     * @param {Boolean} [opts.addStyles=false] If the rule exists already, merge passed styles instead of replacing them.
     * @returns {[CssRule]} The new/updated CssRule.
     * @example
     * // Simple class-based rule
     * const rule = css.setRule('.class1.class2', { color: 'red' });
     * console.log(rule.toCSS()) // output: .class1.class2 { color: red }
     * // With state and other mixed selector
     * const rule = css.setRule('.class1.class2:hover, div#myid', { color: 'red' });
     * // output: .class1.class2:hover, div#myid { color: red }
     * // With media
     * const rule = css.setRule('.class1:hover', { color: 'red' }, {
     *  atRuleType: 'media',
     *  atRuleParams: '(min-width: 500px)',
     * });
     * // output: `@media (min-width: 500px) { .class1:hover { color: red } }`
     *
     * // Update styles of existent rule
     * css.setRule('.class1', { color: 'red', background: 'red' });
     * css.setRule('.class1', { color: 'blue' }, { addStyles: true });
     * // output: .class1 { color: blue; background: red }
     */
    CssComposer.prototype.setRule = function (selectors, style, opts) {
        if (style === void 0) { style = {}; }
        if (opts === void 0) { opts = {}; }
        var atRuleType = opts.atRuleType, atRuleParams = opts.atRuleParams;
        var node = this.em.Parser.parserCss.checkNode({
            selectors: selectors,
            style: style,
        })[0];
        var state = node.state, selectorsAdd = node.selectorsAdd;
        var sm = this.em.Selectors;
        var selector = sm.add(node.selectors);
        var rule = this.add(selector, state, atRuleParams, {
            selectorsAdd: selectorsAdd,
            atRule: atRuleType,
        });
        if (opts.addStyles) {
            rule.addStyle(style, opts);
        }
        else {
            rule.setStyle(style, opts);
        }
        return rule;
    };
    /**
     * Get the CssRule.
     * @param {String} selectors Selector string, eg. `.myclass:hover`
     * @param {Object} [opts={}]  Additional properties
     * @param {String} [opts.atRuleType='']  At-rule type, eg. `media`
     * @param {String} [opts.atRuleParams='']  At-rule parameters, eg. '(min-width: 500px)'
     * @returns {[CssRule]}
     * @example
     * const rule = css.getRule('.myclass1:hover');
     * const rule2 = css.getRule('.myclass1:hover, div#myid');
     * const rule3 = css.getRule('.myclass1', {
     *  atRuleType: 'media',
     *  atRuleParams: '(min-width: 500px)',
     * });
     */
    CssComposer.prototype.getRule = function (selectors, opts) {
        if (opts === void 0) { opts = {}; }
        var em = this.em;
        var sm = em.Selectors;
        var node = em.Parser.parserCss.checkNode({ selectors: selectors })[0];
        // @ts-ignore
        var selector = sm.get(node.selectors);
        var state = node.state, selectorsAdd = node.selectorsAdd;
        var atRuleType = opts.atRuleType, atRuleParams = opts.atRuleParams;
        return selector
            ? this.get(selector, state, atRuleParams, {
                selectorsAdd: selectorsAdd,
                atRuleType: atRuleType,
            })
            : undefined;
    };
    /**
     * Get all rules or filtered by a matching selector.
     * @param {String} [selector=''] Selector, eg. `.myclass`
     * @returns {Array<[CssRule]>}
     * @example
     * // Take all the component specific rules
     * const id = someComponent.getId();
     * const rules = css.getRules(`#${id}`);
     * console.log(rules.map(rule => rule.toCSS()))
     * // All rules in the project
     * console.log(css.getRules())
     */
    CssComposer.prototype.getRules = function (selector) {
        var rules = this.getAll();
        if (!selector)
            return css_composer_spreadArray([], rules.models, true);
        var optRuleSel = { sort: true };
        var sels = (0,index_all.isString)(selector) ? selector.split(',').map(function (s) { return s.trim(); }) : selector;
        var result = rules.filter(function (r) { return sels.indexOf(r.getSelectors().getFullString(null, optRuleSel)) >= 0; });
        return result;
    };
    /**
     * Add/update the CSS rule with id selector
     * @param {string} name Id selector name, eg. 'my-id'
     * @param {Object} style  Style properties and values
     * @param {Object} [opts={}]  Custom options, like `state` and `mediaText`
     * @return {CssRule} The new/updated rule
     * @private
     * @example
     * const rule = css.setIdRule('myid', { color: 'red' });
     * const ruleHover = css.setIdRule('myid', { color: 'blue' }, { state: 'hover' });
     * // This will add current CSS:
     * // #myid { color: red }
     * // #myid:hover { color: blue }
     */
    CssComposer.prototype.setIdRule = function (name, style, opts) {
        if (style === void 0) { style = {}; }
        if (opts === void 0) { opts = {}; }
        var _a = opts.addOpts, addOpts = _a === void 0 ? {} : _a, mediaText = opts.mediaText;
        var state = opts.state || '';
        var media = !(0,index_all.isUndefined)(mediaText) ? mediaText : this.em.getCurrentMedia();
        var sm = this.em.Selectors;
        var selector = sm.add({ name: name, type: model_Selector.TYPE_ID }, addOpts);
        var rule = this.add(selector, state, media, {}, addOpts);
        rule.setStyle(style, css_composer_assign(css_composer_assign({}, opts), addOpts));
        return rule;
    };
    /**
     * Get the CSS rule by id selector
     * @param {string} name Id selector name, eg. 'my-id'
     * @param  {Object} [opts={}]  Custom options, like `state` and `mediaText`
     * @return {CssRule}
     * @private
     * @example
     * const rule = css.getIdRule('myid');
     * const ruleHover = css.setIdRule('myid', { state: 'hover' });
     */
    CssComposer.prototype.getIdRule = function (name, opts) {
        if (opts === void 0) { opts = {}; }
        var mediaText = opts.mediaText;
        var state = opts.state || '';
        var media = !(0,index_all.isUndefined)(mediaText) ? mediaText : this.em.getCurrentMedia();
        var selector = this.em.Selectors.get(name, model_Selector.TYPE_ID);
        return selector && this.get(selector, state, media);
    };
    /**
     * Add/update the CSS rule with class selector
     * @param {string} name Class selector name, eg. 'my-class'
     * @param {Object} style  Style properties and values
     * @param {Object} [opts={}]  Custom options, like `state` and `mediaText`
     * @return {CssRule} The new/updated rule
     * @private
     * @example
     * const rule = css.setClassRule('myclass', { color: 'red' });
     * const ruleHover = css.setClassRule('myclass', { color: 'blue' }, { state: 'hover' });
     * // This will add current CSS:
     * // .myclass { color: red }
     * // .myclass:hover { color: blue }
     */
    CssComposer.prototype.setClassRule = function (name, style, opts) {
        if (style === void 0) { style = {}; }
        if (opts === void 0) { opts = {}; }
        var state = opts.state || '';
        var media = opts.mediaText || this.em.getCurrentMedia();
        var sm = this.em.Selectors;
        var selector = sm.add({ name: name, type: model_Selector.TYPE_CLASS });
        var rule = this.add(selector, state, media);
        rule.setStyle(style, opts);
        return rule;
    };
    /**
     * Get the CSS rule by class selector
     * @param {string} name Class selector name, eg. 'my-class'
     * @param  {Object} [opts={}]  Custom options, like `state` and `mediaText`
     * @return {CssRule}
     * @private
     * @example
     * const rule = css.getClassRule('myclass');
     * const ruleHover = css.getClassRule('myclass', { state: 'hover' });
     */
    CssComposer.prototype.getClassRule = function (name, opts) {
        if (opts === void 0) { opts = {}; }
        var state = opts.state || '';
        var media = opts.mediaText || this.em.getCurrentMedia();
        var selector = this.em.Selectors.get(name, model_Selector.TYPE_CLASS);
        return selector && this.get(selector, state, media);
    };
    /**
     * Remove rule, by CssRule or matching selector (eg. the selector will match also at-rules like `@media`)
     * @param {String|[CssRule]|Array<[CssRule]>} rule CssRule or matching selector.
     * @return {Array<[CssRule]>} Removed rules
     * @example
     * // Remove by CssRule
     * const toRemove = css.getRules('.my-cls');
     * css.remove(toRemove);
     * // Remove by selector
     * css.remove('.my-cls-2');
     */
    CssComposer.prototype.remove = function (rule, opts) {
        var toRemove = (0,index_all.isString)(rule) ? this.getRules(rule) : rule;
        var result = this.getAll().remove(toRemove, opts);
        return (0,index_all.isArray)(result) ? result : [result];
    };
    /**
     * Remove all rules
     * @return {this}
     */
    CssComposer.prototype.clear = function (opts) {
        if (opts === void 0) { opts = {}; }
        this.getAll().reset([], opts);
        return this;
    };
    CssComposer.prototype.getComponentRules = function (cmp, opts) {
        if (opts === void 0) { opts = {}; }
        var state = opts.state, mediaText = opts.mediaText, current = opts.current;
        if (current) {
            state = this.em.get('state') || '';
            mediaText = this.em.getCurrentMedia();
        }
        var id = cmp.getId();
        var rules = this.getAll().filter(function (r) {
            if (!(0,index_all.isUndefined)(state) && r.get('state') !== state)
                return false;
            if (!(0,index_all.isUndefined)(mediaText) && r.get('mediaText') !== mediaText)
                return false;
            return r.getSelectorsString() === "#".concat(id);
        });
        return rules;
    };
    /**
     * Render the block of CSS rules
     * @return {HTMLElement}
     * @private
     */
    CssComposer.prototype.render = function () {
        var _a;
        (_a = this.rulesView) === null || _a === void 0 ? void 0 : _a.remove();
        this.rulesView = new view_CssRulesView({
            collection: this.rules,
            config: this.config,
        });
        return this.rulesView.render().el;
    };
    CssComposer.prototype.checkId = function (rule, opts) {
        if (opts === void 0) { opts = {}; }
        var _a = opts.idMap, idMap = _a === void 0 ? {} : _a;
        var changed = [];
        if (!Object.keys(idMap).length)
            return changed;
        var rules = Array.isArray(rule) ? rule : [rule];
        rules.forEach(function (rule) {
            var sel = rule.selectors;
            if (sel && sel.length == 1) {
                var sSel = sel[0];
                if ((0,index_all.isString)(sSel)) {
                    if (sSel[0] === '#') {
                        var prevId = sSel.substring(1);
                        var newId = idMap[prevId];
                        if (prevId && newId) {
                            sel[0] = "#".concat(newId);
                            changed.push(rule);
                        }
                    }
                }
                else if (sSel.name && sSel.type === model_Selector.TYPE_ID) {
                    var newId = idMap[sSel.name];
                    if (newId) {
                        sSel.name = newId;
                        changed.push(rule);
                    }
                }
            }
        });
        return changed;
    };
    CssComposer.prototype.destroy = function () {
        var _a;
        this.rules.reset();
        this.rules.stopListening();
        (_a = this.rulesView) === null || _a === void 0 ? void 0 : _a.remove();
    };
    return CssComposer;
}(ItemManagerModule));
/* harmony default export */ const css_composer = (CssComposer);

;// CONCATENATED MODULE: ./src/block_manager/config/config.ts
var block_manager_config_config_config = {
    appendTo: '',
    blocks: [],
    appendOnClick: false,
    custom: false,
};
/* harmony default export */ const block_manager_config_config = (block_manager_config_config_config);

;// CONCATENATED MODULE: ./src/block_manager/model/Block.ts
var Block_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();



/**
 * @property {String} label Block label, eg. `My block`
 * @property {String|Object} content The content of the block. Might be an HTML string or a [Component Defintion](/modules/Components.html#component-definition)
 * @property {String} [media=''] HTML string for the media/icon of the block, eg. `<svg ...`, `<img ...`, etc.
 * @property {String} [category=''] Block category, eg. `Basic blocks`
 * @property {Boolean} [activate=false] If true, triggers the `active` event on the dropped component.
 * @property {Boolean} [select=false] If true, the dropped component will be selected.
 * @property {Boolean} [resetId=false] If true, all IDs of dropped components and their styles will be changed.
 * @property {Boolean} [disable=false] Disable the block from being interacted
 * @property {Function} [onClick] Custom behavior on click, eg. `(block, editor) => editor.getWrapper().append(block.get('content'))`
 * @property {Object} [attributes={}] Block attributes to apply in the view element
 *
 * @module docsjs.Block
 */
var Block = /** @class */ (function (_super) {
    Block_extends(Block, _super);
    function Block() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Block.prototype.defaults = function () {
        return {
            label: '',
            content: '',
            media: '',
            category: '',
            activate: false,
            select: undefined,
            resetId: false,
            disable: false,
            onClick: undefined,
            attributes: {},
        };
    };
    Object.defineProperty(Block.prototype, "category", {
        get: function () {
            var cat = this.get('category');
            return cat instanceof ModuleCategory ? cat : undefined;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Block.prototype, "parent", {
        get: function () {
            return this.collection;
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Get block id
     * @returns {String}
     */
    Block.prototype.getId = function () {
        return this.id;
    };
    /**
     * Get block label
     * @returns {String}
     */
    Block.prototype.getLabel = function () {
        return this.get('label');
    };
    /**
     * Get block media
     * @returns {String}
     */
    Block.prototype.getMedia = function () {
        return this.get('media');
    };
    /**
     * Get block content
     * @returns {Object|String|Array<Object|String>}
     */
    Block.prototype.getContent = function () {
        return this.get('content');
    };
    /**
     * Get block category label
     * @returns {String}
     */
    Block.prototype.getCategoryLabel = function () {
        var ctg = this.get('category');
        // @ts-ignore
        return (0,index_all.isFunction)(ctg === null || ctg === void 0 ? void 0 : ctg.get) ? ctg.get('label') : (ctg === null || ctg === void 0 ? void 0 : ctg.label) ? ctg === null || ctg === void 0 ? void 0 : ctg.label : ctg;
    };
    return Block;
}(common/* Model */.Hn));
/* harmony default export */ const model_Block = (Block);

;// CONCATENATED MODULE: ./src/block_manager/model/Blocks.ts
var Blocks_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();


var Blocks = /** @class */ (function (_super) {
    Blocks_extends(Blocks, _super);
    function Blocks(coll, options) {
        var _this = _super.call(this, coll) || this;
        _this.em = options.em;
        _this.on('add', _this.handleAdd);
        return _this;
    }
    Blocks.prototype.getCategories = function () {
        return this.em.Blocks.getCategories();
    };
    Blocks.prototype.handleAdd = function (model) {
        this.initCategory(model);
    };
    return Blocks;
}(CollectionWithCategories));
/* harmony default export */ const model_Blocks = (Blocks);
Blocks.prototype.model = model_Block;

;// CONCATENATED MODULE: ./src/block_manager/types.ts
/**{START_EVENTS}*/
var BlocksEvents;
(function (BlocksEvents) {
    /**
     * @event `block:add` New block added to the collection. The [Block] is passed as an argument to the callback.
     * @example
     * editor.on('block:add', (block) => { ... });
     */
    BlocksEvents["add"] = "block:add";
    /**
     * @event `block:remove` Block removed from the collection. The [Block] is passed as an argument to the callback.
     * @example
     * editor.on('block:remove', (block) => { ... });
     */
    BlocksEvents["remove"] = "block:remove";
    /**
     * @event `block:remove:before` Event triggered before Block remove.
     * @example
     * editor.on('block:remove:before', (block, remove, opts) => { ... });
     */
    BlocksEvents["removeBefore"] = "block:remove:before";
    /**
     * @event `block:update` Block updated. The [Block] and the object containing changes are passed as arguments to the callback.
     * @example
     * editor.on('block:update', (block, updatedProps) => { ... });
     */
    BlocksEvents["update"] = "block:update";
    /**
     * @event `block:drag:start` Started dragging block. The [Block] is passed as an argument.
     * @example
     * editor.on('block:drag:start', (block) => { ... });
     */
    BlocksEvents["dragStart"] = "block:drag:start";
    /**
     * @event `block:drag` The block is dragging. The [Block] is passed as an argument.
     * @example
     * editor.on('block:drag', (block) => { ... });
     */
    BlocksEvents["drag"] = "block:drag";
    /**
     * @event `block:drag:stop` Dragging of the block is stopped. The dropped [Component] (if dropped successfully) and the [Block] are passed as arguments.
     * @example
     * editor.on('block:drag:stop', (component, block) => { ... });
     */
    BlocksEvents["dragEnd"] = "block:drag:stop";
    /**
     * @event `block:custom` Event to use in case of [custom Block Manager UI](https://grapesjs.com/docs/modules/Blocks.html#customization).
     * @example
     * editor.on('block:custom', ({ container, blocks, ... }) => { ... });
     */
    BlocksEvents["custom"] = "block:custom";
    /**
     * @event `block` Catch-all event for all the events mentioned above. An object containing all the available data about the triggered event is passed as an argument to the callback.
     * @example
     * editor.on('block', ({ event, model, ... }) => { ... });
     */
    BlocksEvents["all"] = "block";
})(BlocksEvents || (BlocksEvents = {}));
/**{END_EVENTS}*/
// need this to avoid the TS documentation generator to break
/* harmony default export */ const block_manager_types = ((/* unused pure expression or super */ null && (BlocksEvents)));

;// CONCATENATED MODULE: ./src/block_manager/view/BlockView.ts
var BlockView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();




var BlockView = /** @class */ (function (_super) {
    BlockView_extends(BlockView, _super);
    function BlockView(o, config) {
        if (config === void 0) { config = {}; }
        var _this = _super.call(this, o) || this;
        var model = _this.model;
        _this.em = config.em;
        _this.config = config;
        _this.endDrag = _this.endDrag.bind(_this);
        _this.ppfx = config.pStylePrefix || '';
        _this.listenTo(model, 'destroy remove', _this.remove);
        _this.listenTo(model, 'change', _this.render);
        return _this;
    }
    BlockView.prototype.events = function () {
        return {
            click: 'handleClick',
            mousedown: 'startDrag',
            dragstart: 'handleDragStart',
            drag: 'handleDrag',
            dragend: 'handleDragEnd',
        };
    };
    BlockView.prototype.__getModule = function () {
        return this.em.Blocks;
    };
    BlockView.prototype.handleClick = function (ev) {
        var _a = this, config = _a.config, model = _a.model, em = _a.em;
        var onClick = model.get('onClick') || config.appendOnClick;
        em.trigger('block:click', model, ev);
        if (!onClick) {
            return;
        }
        else if ((0,index_all.isFunction)(onClick)) {
            return onClick(model, em === null || em === void 0 ? void 0 : em.getEditor(), { event: ev });
        }
        var sorter = config.getSorter();
        var content = model.get('content');
        var selected = em.getSelected();
        sorter.setDropContent(content);
        var target, valid, insertAt;
        // If there is a selected component, try first to append
        // the block inside, otherwise, try to place it as a next sibling
        if (selected) {
            valid = sorter.validTarget(selected.getEl(), content);
            if (valid.valid) {
                target = selected;
            }
            else {
                var parent_1 = selected.parent();
                if (parent_1) {
                    valid = sorter.validTarget(parent_1.getEl(), content);
                    if (valid.valid) {
                        target = parent_1;
                        insertAt = parent_1.components().indexOf(selected) + 1;
                    }
                }
            }
        }
        // If no target found yet, try to append the block to the wrapper
        if (!target) {
            var wrapper = em.getWrapper();
            valid = sorter.validTarget(wrapper.getEl(), content);
            if (valid.valid)
                target = wrapper;
        }
        var result = target && target.append(content, { at: insertAt })[0];
        result && em.setSelected(result, { scroll: 1 });
    };
    /**
     * Start block dragging
     * @private
     */
    BlockView.prototype.startDrag = function (e) {
        var _a = this, config = _a.config, em = _a.em, model = _a.model;
        var disable = model.get('disable');
        //Right or middel click
        if (e.button !== 0 || !config.getSorter || this.el.draggable || disable)
            return;
        em.refreshCanvas();
        var sorter = config.getSorter();
        sorter.__currentBlock = model;
        sorter.setDragHelper(this.el, e);
        sorter.setDropContent(this.model.get('content'));
        sorter.startSort(this.el);
        (0,dom.on)(document, 'mouseup', this.endDrag);
    };
    BlockView.prototype.handleDragStart = function (ev) {
        this.__getModule().__startDrag(this.model, ev);
    };
    BlockView.prototype.handleDrag = function (ev) {
        this.__getModule().__drag(ev);
    };
    BlockView.prototype.handleDragEnd = function () {
        this.__getModule().__endDrag();
    };
    /**
     * Drop block
     * @private
     */
    BlockView.prototype.endDrag = function () {
        (0,dom/* off */.S1)(document, 'mouseup', this.endDrag);
        var sorter = this.config.getSorter();
        // After dropping the block in the canvas the mouseup event is not yet
        // triggerd on 'this.doc' and so clicking outside, the sorter, tries to move
        // things (throws false positives). As this method just need to drop away
        // the block helper I use the trick of 'moved = 0' to void those errors.
        sorter.moved = 0;
        sorter.endMove();
    };
    BlockView.prototype.render = function () {
        var _a;
        var _b = this, em = _b.em, el = _b.el, $el = _b.$el, ppfx = _b.ppfx, model = _b.model;
        var disable = model.get('disable');
        var attr = model.get('attributes') || {};
        var cls = attr.class || '';
        var className = "".concat(ppfx, "block");
        var label = (em && em.t("blockManager.labels.".concat(model.id))) || model.get('label');
        // @ts-ignore deprecated
        var render = model.get('render');
        var media = model.get('media');
        var clsAdd = disable ? "".concat(className, "--disable") : "".concat(ppfx, "four-color-h");
        $el.attr(attr);
        el.className = "".concat(cls, " ").concat(className, " ").concat(ppfx, "one-bg ").concat(clsAdd).trim();
        el.innerHTML = "\n      ".concat(media ? "<div class=\"".concat(className, "__media\">").concat(media, "</div>") : '', "\n      <div class=\"").concat(className, "-label\">").concat(label, "</div>\n    ");
        el.title = attr.title || ((_a = el.textContent) === null || _a === void 0 ? void 0 : _a.trim());
        el.setAttribute('draggable', "".concat((0,mixins.hasDnd)(em) && !disable ? true : false));
        // @ts-ignore
        var result = render && render({ el: el, model: model, className: className, prefix: ppfx });
        if (result)
            el.innerHTML = result;
        return this;
    };
    return BlockView;
}(common/* View */.G7));
/* harmony default export */ const view_BlockView = (BlockView);

;// CONCATENATED MODULE: ./src/abstract/ModuleCategoryView.ts
var ModuleCategoryView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var ModuleCategoryView_makeTemplateObject = (undefined && undefined.__makeTemplateObject) || function (cooked, raw) {
    if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
    return cooked;
};


var CategoryView = /** @class */ (function (_super) {
    ModuleCategoryView_extends(CategoryView, _super);
    function CategoryView(o, config, catName) {
        var _this = _super.call(this, o) || this;
        _this.config = config;
        var pfx = config.pStylePrefix || '';
        _this.em = config.em;
        _this.catName = catName;
        _this.pfx = pfx;
        _this.caretR = 'fa fa-caret-right';
        _this.caretD = 'fa fa-caret-down';
        _this.iconClass = "".concat(pfx, "caret-icon");
        _this.activeClass = "".concat(pfx, "open");
        _this.className = "".concat(pfx).concat(catName, "-category");
        _this.listenTo(_this.model, 'change:open', _this.updateVisibility);
        _this.model.view = _this;
        return _this;
    }
    CategoryView.prototype.events = function () {
        return {
            'click [data-title]': 'toggle',
        };
    };
    CategoryView.prototype.template = function (_a) {
        var pfx = _a.pfx, label = _a.label, catName = _a.catName;
        return html(ModuleCategoryView_templateObject_1 || (ModuleCategoryView_templateObject_1 = ModuleCategoryView_makeTemplateObject(["\n      <div class=\"", "title\" data-title>\n        <i class=\"", "caret-icon\"></i>\n        ", "\n      </div>\n      <div class=\"", "", "s-c\"></div>\n    "], ["\n      <div class=\"", "title\" data-title>\n        <i class=\"", "caret-icon\"></i>\n        ", "\n      </div>\n      <div class=\"", "", "s-c\"></div>\n    "])), pfx, pfx, label, pfx, catName);
    };
    /** @ts-ignore */
    CategoryView.prototype.attributes = function () {
        return this.model.get('attributes') || {};
    };
    CategoryView.prototype.updateVisibility = function () {
        if (this.model.get('open'))
            this.open();
        else
            this.close();
    };
    CategoryView.prototype.open = function () {
        this.$el.addClass(this.activeClass);
        this.getIconEl().className = "".concat(this.iconClass, " ").concat(this.caretD);
        this.getTypeEl().style.display = '';
    };
    CategoryView.prototype.close = function () {
        this.$el.removeClass(this.activeClass);
        this.getIconEl().className = "".concat(this.iconClass, " ").concat(this.caretR);
        this.getTypeEl().style.display = 'none';
    };
    CategoryView.prototype.toggle = function () {
        var model = this.model;
        model.set('open', !model.get('open'));
    };
    CategoryView.prototype.getIconEl = function () {
        if (!this.iconEl) {
            this.iconEl = this.el.querySelector(".".concat(this.iconClass));
        }
        return this.iconEl;
    };
    CategoryView.prototype.getTypeEl = function () {
        if (!this.typeEl) {
            this.typeEl = this.el.querySelector(".".concat(this.pfx).concat(this.catName, "s-c"));
        }
        return this.typeEl;
    };
    CategoryView.prototype.append = function (el) {
        this.getTypeEl().appendChild(el);
    };
    CategoryView.prototype.render = function () {
        var _a = this, em = _a.em, el = _a.el, $el = _a.$el, model = _a.model, pfx = _a.pfx, catName = _a.catName;
        var label = em.t("".concat(catName, "Manager.categories.").concat(model.id)) || model.get('label');
        el.innerHTML = this.template({ pfx: pfx, label: label, catName: catName });
        $el.addClass(this.className);
        $el.css({ order: model.get('order') });
        this.updateVisibility();
        return this;
    };
    return CategoryView;
}(common/* View */.G7));
/* harmony default export */ const ModuleCategoryView = (CategoryView);
var ModuleCategoryView_templateObject_1;

;// CONCATENATED MODULE: ./src/block_manager/view/BlocksView.ts
var BlocksView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var BlocksView_assign = (undefined && undefined.__assign) || function () {
    BlocksView_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return BlocksView_assign.apply(this, arguments);
};




var BlocksView = /** @class */ (function (_super) {
    BlocksView_extends(BlocksView, _super);
    function BlocksView(opts, config) {
        var _this = _super.call(this, opts) || this;
        _this.renderedCategories = new Map();
        (0,index_all.bindAll)(_this, 'getSorter', 'onDrag', 'onDrop', 'onMove');
        _this.config = config || {};
        _this.categories = opts.categories || '';
        var ppfx = _this.config.pStylePrefix || '';
        _this.ppfx = ppfx;
        _this.noCatClass = "".concat(ppfx, "blocks-no-cat");
        _this.blockContClass = "".concat(ppfx, "blocks-c");
        _this.catsClass = "".concat(ppfx, "block-categories");
        var coll = _this.collection;
        _this.listenTo(coll, 'add', _this.addTo);
        _this.listenTo(coll, 'reset', _this.render);
        _this.em = _this.config.em;
        if (_this.em) {
            _this.config.getSorter = _this.getSorter;
        }
        return _this;
    }
    BlocksView.prototype.__getModule = function () {
        return this.em.Blocks;
    };
    BlocksView.prototype.updateConfig = function (opts) {
        if (opts === void 0) { opts = {}; }
        this.config = BlocksView_assign(BlocksView_assign({}, this.config), opts);
    };
    /**
     * Get sorter
     * @private
     */
    BlocksView.prototype.getSorter = function () {
        var em = this.em;
        if (!em)
            return;
        if (!this.sorter) {
            var utils = em.Utils;
            var canvas = em.Canvas;
            this.sorter = new utils.Sorter({
                // @ts-ignore
                container: canvas.getBody(),
                placer: canvas.getPlacerEl(),
                containerSel: '*',
                itemSel: '*',
                pfx: this.ppfx,
                onStart: this.onDrag,
                onEndMove: this.onDrop,
                onMove: this.onMove,
                document: canvas.getFrameEl().contentDocument,
                direction: 'a',
                wmargin: 1,
                nested: 1,
                em: em,
                canvasRelative: 1,
            });
        }
        return this.sorter;
    };
    BlocksView.prototype.onDrag = function (ev) {
        this.em.stopDefault();
        this.__getModule().__startDrag(this.sorter.__currentBlock, ev);
    };
    BlocksView.prototype.onMove = function (ev) {
        this.__getModule().__drag(ev);
    };
    BlocksView.prototype.onDrop = function (component) {
        this.em.runDefault();
        this.__getModule().__endDrag({ component: component });
        delete this.sorter.__currentBlock;
    };
    /**
     * Add new model to the collection
     * @param {Model} model
     * @private
     * */
    BlocksView.prototype.addTo = function (model) {
        this.add(model);
    };
    /**
     * Render new model inside the view
     * @param {Model} model
     * @param {Object} fragment Fragment collection
     * @private
     * */
    BlocksView.prototype.add = function (model, fragment) {
        var _a = this, config = _a.config, renderedCategories = _a.renderedCategories;
        var attributes = model.get('attributes');
        var view = new view_BlockView({ model: model, attributes: attributes }, config);
        var rendered = view.render().el;
        var category = model.parent.initCategory(model);
        // Check for categories
        if (category && this.categories && !config.ignoreCategories) {
            var catId = category.getId();
            var categories = this.getCategoriesEl();
            var catView = renderedCategories.get(catId);
            if (!catView && categories) {
                catView = new ModuleCategoryView({ model: category }, config, 'block').render();
                renderedCategories.set(catId, catView);
                categories.appendChild(catView.el);
            }
            catView === null || catView === void 0 ? void 0 : catView.append(rendered);
            return;
        }
        fragment ? fragment.appendChild(rendered) : this.append(rendered);
    };
    BlocksView.prototype.getCategoriesEl = function () {
        if (!this.catsEl) {
            this.catsEl = this.el.querySelector(".".concat(this.catsClass));
        }
        return this.catsEl;
    };
    BlocksView.prototype.getBlocksEl = function () {
        if (!this.blocksEl) {
            this.blocksEl = this.el.querySelector(".".concat(this.noCatClass, " .").concat(this.blockContClass));
        }
        return this.blocksEl;
    };
    BlocksView.prototype.append = function (el) {
        var blocks = this.getBlocksEl();
        blocks && blocks.appendChild(el);
    };
    BlocksView.prototype.render = function () {
        var _this = this;
        var ppfx = this.ppfx;
        var frag = document.createDocumentFragment();
        delete this.catsEl;
        delete this.blocksEl;
        this.renderedCategories = new Map();
        this.el.innerHTML = "\n      <div class=\"".concat(this.catsClass, "\"></div>\n      <div class=\"").concat(this.noCatClass, "\">\n        <div class=\"").concat(this.blockContClass, "\"></div>\n      </div>\n    ");
        this.collection.each(function (model) { return _this.add(model, frag); });
        this.append(frag);
        var cls = "".concat(this.blockContClass, "s ").concat(ppfx, "one-bg ").concat(ppfx, "two-color");
        this.$el.addClass(cls);
        this.rendered = true;
        return this;
    };
    return BlocksView;
}(common/* View */.G7));
/* harmony default export */ const view_BlocksView = (BlocksView);

;// CONCATENATED MODULE: ./src/block_manager/index.ts
var block_manager_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var block_manager_assign = (undefined && undefined.__assign) || function () {
    block_manager_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return block_manager_assign.apply(this, arguments);
};
/**
 * You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](https://github.com/GrapesJS/grapesjs/blob/master/src/block_manager/config/config.ts)
 * ```js
 * const editor = grapesjs.init({
 *  blockManager: {
 *    // options
 *  }
 * })
 * ```
 *
 * Once the editor is instantiated you can use its API and listen to its events. Before using these methods, you should get the module from the instance.
 *
 * ```js
 * // Listen to events
 * editor.on('block:add', (block) => { ... });
 *
 * // Use the API
 * const blockManager = editor.Blocks;
 * blockManager.add(...);
 * ```
 *
 * {REPLACE_EVENTS}
 *
 * [Block]: block.html
 * [Component]: component.html
 *
 * @module Blocks
 */









var BlockManager = /** @class */ (function (_super) {
    block_manager_extends(BlockManager, _super);
    function BlockManager(em) {
        var _a;
        var _this = _super.call(this, em, 'BlockManager', new model_Blocks(((_a = em.config.blockManager) === null || _a === void 0 ? void 0 : _a.blocks) || [], { em: em }), BlocksEvents, block_manager_config_config) || this;
        _this.events = BlocksEvents;
        _this.Block = model_Block;
        _this.Blocks = model_Blocks;
        _this.Category = ModuleCategory;
        _this.Categories = ModuleCategories;
        _this.storageKey = '';
        // Global blocks collection
        _this.blocks = _this.all;
        _this.blocksVisible = new model_Blocks(_this.blocks.models, { em: em });
        _this.categories = new ModuleCategories();
        // Setup the sync between the global and public collections
        _this.blocks.on('add', function (model) { return _this.blocksVisible.add(model); });
        _this.blocks.on('remove', function (model) { return _this.blocksVisible.remove(model); });
        _this.blocks.on('reset', function (coll) { return _this.blocksVisible.reset(coll.models); });
        _this.__onAllEvent = (0,index_all.debounce)(function () { return _this.__trgCustom(); }, 0);
        return _this;
    }
    /**
     * Get configuration object
     * @name getConfig
     * @function
     * @return {Object}
     */
    BlockManager.prototype.__trgCustom = function () {
        this.em.trigger(this.events.custom, this.__customData());
    };
    BlockManager.prototype.__customData = function () {
        var _this = this;
        var bhv = this.__getBehaviour();
        return {
            bm: this,
            blocks: this.getAll().models,
            container: bhv.container,
            dragStart: function (block, ev) { return _this.startDrag(block, ev); },
            drag: function (ev) { return _this.__drag(ev); },
            dragStop: function (cancel) { return _this.endDrag(cancel); },
        };
    };
    BlockManager.prototype.__startDrag = function (block, ev) {
        var _a = this, em = _a.em, events = _a.events, blocks = _a.blocks;
        var content = block.getContent ? block.getContent() : block;
        this._dragBlock = block;
        em.set({ dragResult: null, dragContent: content });
        [em, blocks].map(function (i) { return i.trigger(events.dragStart, block, ev); });
    };
    BlockManager.prototype.__drag = function (ev) {
        var _a = this, em = _a.em, events = _a.events, blocks = _a.blocks;
        var block = this._dragBlock;
        [em, blocks].map(function (i) { return i.trigger(events.drag, block, ev); });
    };
    BlockManager.prototype.__endDrag = function (opts) {
        if (opts === void 0) { opts = {}; }
        var _a = this, em = _a.em, events = _a.events, blocks = _a.blocks;
        var block = this._dragBlock;
        var cmp = opts.component || em.get('dragResult');
        delete this._dragBlock;
        if (cmp && block) {
            var oldKey = 'activeOnRender';
            var oldActive = cmp.get && cmp.get(oldKey);
            var toActive = block.get('activate') || oldActive;
            var toSelect = block.get('select');
            var first = (0,index_all.isArray)(cmp) ? cmp[0] : cmp;
            if (toSelect || (toActive && toSelect !== false)) {
                em.setSelected(first);
            }
            if (toActive) {
                first.trigger('active');
                oldActive && first.unset(oldKey);
            }
            if (block.get('resetId')) {
                first.onAll(function (cmp) { return cmp.resetId(); });
            }
        }
        em.set({ dragResult: null, dragContent: null });
        if (block) {
            [em, blocks].map(function (i) { return i.trigger(events.dragEnd, cmp, block); });
        }
    };
    BlockManager.prototype.__getFrameViews = function () {
        return this.em.Canvas.getFrames()
            .map(function (frame) { return frame.view; })
            .filter(Boolean);
    };
    BlockManager.prototype.__behaviour = function (opts) {
        if (opts === void 0) { opts = {}; }
        return (this._bhv = block_manager_assign(block_manager_assign({}, (this._bhv || {})), opts));
    };
    BlockManager.prototype.__getBehaviour = function () {
        return this._bhv || {};
    };
    BlockManager.prototype.startDrag = function (block, ev) {
        this.__startDrag(block, ev);
        this.__getFrameViews().forEach(function (fv) { var _a; return (_a = fv.droppable) === null || _a === void 0 ? void 0 : _a.startCustom(); });
    };
    BlockManager.prototype.endDrag = function (cancel) {
        this.__getFrameViews().forEach(function (fv) { var _a; return (_a = fv.droppable) === null || _a === void 0 ? void 0 : _a.endCustom(cancel); });
        this.__endDrag();
    };
    BlockManager.prototype.postRender = function () {
        var _a = this, categories = _a.categories, config = _a.config, em = _a.em;
        var collection = this.blocksVisible;
        this.blocksView = new view_BlocksView({ collection: collection, categories: categories }, block_manager_assign(block_manager_assign({}, config), { em: em }));
        this.__appendTo(collection.models);
        this.__trgCustom();
    };
    /**
     * Add new block.
     * @param {String} id Block ID
     * @param {[Block]} props Block properties
     * @returns {[Block]} Added block
     * @example
     * blockManager.add('h1-block', {
     *   label: 'Heading',
     *   content: '<h1>Put your title here</h1>',
     *   category: 'Basic',
     *   attributes: {
     *     title: 'Insert h1 block'
     *   }
     * });
     */
    BlockManager.prototype.add = function (id, props, opts) {
        if (opts === void 0) { opts = {}; }
        var prp = props || {};
        prp.id = id;
        return this.blocks.add(prp, opts);
    };
    /**
     * Get the block by id.
     * @param  {String} id Block id
     * @returns {[Block]}
     * @example
     * const block = blockManager.get('h1-block');
     * console.log(JSON.stringify(block));
     * // {label: 'Heading', content: '<h1>Put your ...', ...}
     */
    BlockManager.prototype.get = function (id) {
        return this.blocks.get(id);
    };
    /**
     * Return all blocks.
     * @returns {Collection<[Block]>}
     * @example
     * const blocks = blockManager.getAll();
     * console.log(JSON.stringify(blocks));
     * // [{label: 'Heading', content: '<h1>Put your ...'}, ...]
     */
    BlockManager.prototype.getAll = function () {
        return this.blocks;
    };
    /**
     * Return the visible collection, which containes blocks actually rendered
     * @returns {Collection<[Block]>}
     */
    BlockManager.prototype.getAllVisible = function () {
        return this.blocksVisible;
    };
    /**
     * Remove block.
     * @param {String|[Block]} block Block or block ID
     * @returns {[Block]} Removed block
     * @example
     * const removed = blockManager.remove('BLOCK_ID');
     * // or by passing the Block
     * const block = blockManager.get('BLOCK_ID');
     * blockManager.remove(block);
     */
    BlockManager.prototype.remove = function (block, opts) {
        if (opts === void 0) { opts = {}; }
        return this.__remove(block, opts);
    };
    /**
     * Get all available categories.
     * It's possible to add categories only within blocks via 'add()' method
     * @return {Array|Collection}
     */
    BlockManager.prototype.getCategories = function () {
        return this.categories;
    };
    /**
     * Return the Blocks container element
     * @return {HTMLElement}
     */
    BlockManager.prototype.getContainer = function () {
        var _a;
        return (_a = this.blocksView) === null || _a === void 0 ? void 0 : _a.el;
    };
    /**
     * Returns currently dragging block.
     * Updated when the drag starts and cleared once it's done.
     * @returns {[Block]|undefined}
     */
    BlockManager.prototype.getDragBlock = function () {
        return this._dragBlock;
    };
    /**
     * Get blocks by category.
     * @example
     * blockManager.getBlocksByCategory();
     * // Returns an array of items of this type
     * // > { category?: Category; items: Block[] }
     *
     * // NOTE: The item without category is the one containing blocks without category.
     *
     * // You can also get the same output format by passing your own array of Blocks
     * const myFilteredBlocks: Block[] = [...];
     * blockManager.getBlocksByCategorymyFilteredBlocks
     */
    BlockManager.prototype.getBlocksByCategory = function (blocks) {
        return getItemsByCategory(blocks || this.getAll().models);
    };
    /**
     * Render blocks
     * @param  {Array} blocks Blocks to render, without the argument will render all global blocks
     * @param  {Object} [opts={}] Options
     * @param  {Boolean} [opts.external] Render blocks in a new container (HTMLElement will be returned)
     * @param  {Boolean} [opts.ignoreCategories] Render blocks without categories
     * @return {HTMLElement} Rendered element
     * @example
     * // Render all blocks (inside the global collection)
     * blockManager.render();
     *
     * // Render new set of blocks
     * const blocks = blockManager.getAll();
     * const filtered = blocks.filter(block => block.get('category') == 'sections')
     *
     * blockManager.render(filtered);
     * // Or a new set from an array
     * blockManager.render([
     *  {label: 'Label text', content: '<div>Content</div>'}
     * ]);
     *
     * // Back to blocks from the global collection
     * blockManager.render();
     *
     * // You can also render your blocks outside of the main block container
     * const newBlocksEl = blockManager.render(filtered, { external: true });
     * document.getElementById('some-id').appendChild(newBlocksEl);
     */
    BlockManager.prototype.render = function (blocks, opts) {
        if (opts === void 0) { opts = {}; }
        var _a = this, categories = _a.categories, config = _a.config, em = _a.em;
        var toRender = blocks || this.getAll().models;
        if (opts.external) {
            var collection = new model_Blocks(toRender, { em: em });
            return new view_BlocksView({ collection: collection, categories: categories }, block_manager_assign(block_manager_assign({ em: em }, config), opts)).render().el;
        }
        if (this.blocksView) {
            this.blocksView.updateConfig(opts);
            this.blocksView.collection.reset(toRender);
            if (!this.blocksView.rendered) {
                this.blocksView.render();
                this.blocksView.rendered = true;
            }
        }
        return this.getContainer();
    };
    BlockManager.prototype.destroy = function () {
        var _a;
        var colls = [this.blocks, this.blocksVisible, this.categories];
        colls.map(function (c) { return c.stopListening(); });
        colls.map(function (c) { return c.reset(); });
        (_a = this.blocksView) === null || _a === void 0 ? void 0 : _a.remove();
    };
    return BlockManager;
}(ItemManagerModule));
/* harmony default export */ const block_manager = (BlockManager);

;// CONCATENATED MODULE: ./src/selector_manager/config/config.ts
var selector_manager_config_config_config = {
    stylePrefix: 'clm-',
    appendTo: '',
    selectors: [],
    states: [{ name: 'hover' }, { name: 'active' }, { name: 'nth-of-type(2n)' }],
    iconAdd: '<svg viewBox="0 0 24 24"><path d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"></path></svg>',
    iconSync: '<svg viewBox="0 0 24 24"><path d="M12 18c-3.31 0-6-2.69-6-6 0-1 .25-1.97.7-2.8L5.24 7.74A7.93 7.93 0 0 0 4 12c0 4.42 3.58 8 8 8v3l4-4-4-4m0-11V1L8 5l4 4V6c3.31 0 6 2.69 6 6 0 1-.25 1.97-.7 2.8l1.46 1.46A7.93 7.93 0 0 0 20 12c0-4.42-3.58-8-8-8z"></path></svg>',
    iconTagOn: '<svg viewBox="0 0 24 24"><path d="M19 19H5V5h10V3H5c-1.11 0-2 .89-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2v-8h-2m-11.09-.92L6.5 11.5 11 16 21 6l-1.41-1.42L11 13.17l-3.09-3.09z"></path></svg>',
    iconTagOff: '<svg viewBox="0 0 24 24"><path d="M19 3H5c-1.11 0-2 .89-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5a2 2 0 0 0-2-2m0 2v14H5V5h14z"></path></svg>',
    iconTagRemove: '<svg viewBox="0 0 24 24"><path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12 19 6.41z"></path></svg>',
    componentFirst: false,
    custom: false,
};
/* harmony default export */ const selector_manager_config_config = (selector_manager_config_config_config);

;// CONCATENATED MODULE: ./src/selector_manager/model/State.ts
var State_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();

/**
 * @typedef State
 * @property {String} name State name, eg. `hover`, `nth-of-type(2n)`
 * @property {String} label State label, eg. `Hover`, `Even/Odd`
 */
var State = /** @class */ (function (_super) {
    State_extends(State, _super);
    function State() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    State.prototype.defaults = function () {
        return {
            name: '',
            label: '',
        };
    };
    /**
     * Get state name
     * @returns {String}
     */
    State.prototype.getName = function () {
        return this.get('name');
    };
    /**
     * Get state label. If label was not provided, the name will be returned.
     * @returns {String}
     */
    State.prototype.getLabel = function () {
        return this.get('label') || this.getName();
    };
    return State;
}(common/* Model */.Hn));
/* harmony default export */ const model_State = (State);
State.prototype.idAttribute = 'name';

;// CONCATENATED MODULE: ./src/selector_manager/view/ClassTagView.ts
var ClassTagView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var ClassTagView_makeTemplateObject = (undefined && undefined.__makeTemplateObject) || function (cooked, raw) {
    if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
    return cooked;
};


var inputProp = 'contentEditable';
var ClassTagView = /** @class */ (function (_super) {
    ClassTagView_extends(ClassTagView, _super);
    function ClassTagView(o) {
        if (o === void 0) { o = {}; }
        var _this = _super.call(this, o) || this;
        var config = o.config || {};
        _this.config = config;
        _this.module = o.module;
        _this.coll = o.coll || null;
        _this.pfx = config.stylePrefix || '';
        _this.ppfx = config.pStylePrefix || '';
        _this.em = config.em;
        _this.listenTo(_this.model, 'change:active', _this.updateStatus);
        return _this;
    }
    ClassTagView.prototype.template = function () {
        var _a = this, pfx = _a.pfx, model = _a.model, config = _a.config;
        var label = model.get('label') || '';
        return html(ClassTagView_templateObject_1 || (ClassTagView_templateObject_1 = ClassTagView_makeTemplateObject(["\n      <span id=\"", "checkbox\" class=\"", "tag-status\" data-tag-status></span>\n      <span id=\"", "tag-label\" data-tag-name>", "</span>\n      <span id=\"", "close\" class=\"", "tag-close\" data-tag-remove> $", " </span>\n    "], ["\n      <span id=\"", "checkbox\" class=\"", "tag-status\" data-tag-status></span>\n      <span id=\"", "tag-label\" data-tag-name>", "</span>\n      <span id=\"", "close\" class=\"", "tag-close\" data-tag-remove> $", " </span>\n    "])), pfx, pfx, pfx, label, pfx, pfx, config.iconTagRemove);
    };
    ClassTagView.prototype.events = function () {
        return {
            'click [data-tag-remove]': 'removeTag',
            'click [data-tag-status]': 'changeStatus',
            'dblclick [data-tag-name]': 'startEditTag',
            'focusout [data-tag-name]': 'endEditTag',
        };
    };
    /**
     * Returns the element which containes the anme of the tag
     * @return {HTMLElement}
     */
    ClassTagView.prototype.getInputEl = function () {
        if (!this.inputEl) {
            this.inputEl = this.el.querySelector('[data-tag-name]');
        }
        return this.inputEl;
    };
    /**
     * Start editing tag
     * @private
     */
    ClassTagView.prototype.startEditTag = function () {
        var em = this.em;
        var inputEl = this.getInputEl();
        inputEl[inputProp] = 'true';
        inputEl.focus();
        em === null || em === void 0 ? void 0 : em.setEditing(true);
    };
    /**
     * End editing tag. If the class typed already exists the
     * old one will be restored otherwise will be changed
     * @private
     */
    ClassTagView.prototype.endEditTag = function () {
        var _a = this, model = _a.model, em = _a.em;
        var inputEl = this.getInputEl();
        var label = inputEl.textContent || '';
        var sm = em === null || em === void 0 ? void 0 : em.Selectors;
        inputEl[inputProp] = 'false';
        em === null || em === void 0 ? void 0 : em.setEditing(false);
        if (sm && sm.rename(model, label) !== model) {
            inputEl.innerText = model.getLabel();
        }
    };
    /**
     * Update status of the tag
     * @private
     */
    ClassTagView.prototype.changeStatus = function () {
        var model = this.model;
        model.set('active', !model.getActive());
    };
    /**
     * Remove tag from the selected component
     * @param {Object} e
     * @private
     */
    ClassTagView.prototype.removeTag = function () {
        this.module.removeSelected(this.model);
    };
    /**
     * Update status of the checkbox
     * @private
     */
    ClassTagView.prototype.updateStatus = function () {
        var _a = this, model = _a.model, $el = _a.$el, config = _a.config;
        var iconTagOn = config.iconTagOn, iconTagOff = config.iconTagOff;
        var $chk = $el.find('[data-tag-status]');
        if (model.get('active')) {
            $chk.html(iconTagOn);
            $el.removeClass('opac50');
        }
        else {
            $chk.html(iconTagOff);
            $el.addClass('opac50');
        }
    };
    ClassTagView.prototype.render = function () {
        var _a = this, pfx = _a.pfx, ppfx = _a.ppfx, $el = _a.$el, model = _a.model;
        var mainCls = "".concat(pfx, "tag");
        var classes = ["".concat(mainCls, " ").concat(ppfx, "three-bg")];
        model.get('protected') && classes.push("".concat(mainCls, "-protected"));
        $el.html(this.template());
        $el.attr('class', classes.join(' '));
        this.updateStatus();
        return this;
    };
    return ClassTagView;
}(common/* View */.G7));
/* harmony default export */ const view_ClassTagView = (ClassTagView);
var ClassTagView_templateObject_1;

;// CONCATENATED MODULE: ./src/selector_manager/view/ClassTagsView.ts
var ClassTagsView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var ClassTagsView_makeTemplateObject = (undefined && undefined.__makeTemplateObject) || function (cooked, raw) {
    if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
    return cooked;
};




var ClassTagsView = /** @class */ (function (_super) {
    ClassTagsView_extends(ClassTagsView, _super);
    function ClassTagsView(o) {
        if (o === void 0) { o = {}; }
        var _this = _super.call(this, o) || this;
        _this.config = o.config || {};
        _this.pfx = _this.config.stylePrefix || '';
        _this.ppfx = _this.config.pStylePrefix || '';
        _this.className = _this.pfx + 'tags';
        _this.stateInputId = _this.pfx + 'states';
        _this.stateInputC = _this.pfx + 'input-c';
        _this.states = _this.config.states || [];
        var em = _this.config.em;
        var coll = _this.collection;
        _this.target = em;
        var md = em.Selectors;
        _this.module = md;
        _this.em = em;
        _this.componentChanged = (0,index_all.debounce)(_this.componentChanged.bind(_this), 0);
        _this.checkSync = (0,index_all.debounce)(_this.checkSync.bind(_this), 0);
        var toList = 'component:toggled component:update:classes';
        var toListCls = 'component:update:classes change:state';
        _this.listenTo(em, toList, _this.componentChanged);
        _this.listenTo(em, 'styleManager:update', _this.componentChanged);
        _this.listenTo(em, toListCls, _this.__handleStateChange);
        _this.listenTo(em, 'styleable:change change:device', _this.checkSync);
        _this.listenTo(coll, 'add', _this.addNew);
        _this.listenTo(coll, 'reset', _this.renderClasses);
        _this.listenTo(coll, 'remove', _this.tagRemoved);
        _this.listenTo(md.getAll(), md.events.state, (0,index_all.debounce)(function () { return _this.renderStates(); }, 0));
        _this.delegateEvents();
        return _this;
    }
    ClassTagsView.prototype.template = function (_a) {
        var labelInfo = _a.labelInfo, labelHead = _a.labelHead, iconSync = _a.iconSync, iconAdd = _a.iconAdd, pfx = _a.pfx, ppfx = _a.ppfx;
        return html(ClassTagsView_templateObject_1 || (ClassTagsView_templateObject_1 = ClassTagsView_makeTemplateObject([" <div id=\"", "up\" class=\"", "header\">\n        <div id=\"", "label\" class=\"", "header-label\">", "</div>\n        <div id=\"", "status-c\" class=\"", "header-status\">\n          <span id=\"", "input-c\" data-states-c>\n            <div class=\"", "field ", "select\">\n              <span id=\"", "input-holder\">\n                <select id=\"", "states\" data-states></select>\n              </span>\n              <div class=\"", "sel-arrow\">\n                <div class=\"", "d-s-arrow\"></div>\n              </div>\n            </div>\n          </span>\n        </div>\n      </div>\n      <div id=\"", "tags-field\" class=\"", "field\">\n        <div id=\"", "tags-c\" data-selectors></div>\n        <input id=\"", "new\" data-input />\n        <span id=\"", "add-tag\" class=\"", "tags-btn ", "tags-btn__add\" data-add> $", " </span>\n        <span class=\"", "tags-btn ", "tags-btn__sync\" style=\"display: none\" data-sync-style> $", " </span>\n      </div>\n      <div class=\"", "sels-info\">\n        <div class=\"", "label-sel\">", ":</div>\n        <div class=\"", "sels\" data-selected></div>\n      </div>"], [" <div id=\"", "up\" class=\"", "header\">\n        <div id=\"", "label\" class=\"", "header-label\">", "</div>\n        <div id=\"", "status-c\" class=\"", "header-status\">\n          <span id=\"", "input-c\" data-states-c>\n            <div class=\"", "field ", "select\">\n              <span id=\"", "input-holder\">\n                <select id=\"", "states\" data-states></select>\n              </span>\n              <div class=\"", "sel-arrow\">\n                <div class=\"", "d-s-arrow\"></div>\n              </div>\n            </div>\n          </span>\n        </div>\n      </div>\n      <div id=\"", "tags-field\" class=\"", "field\">\n        <div id=\"", "tags-c\" data-selectors></div>\n        <input id=\"", "new\" data-input />\n        <span id=\"", "add-tag\" class=\"", "tags-btn ", "tags-btn__add\" data-add> $", " </span>\n        <span class=\"", "tags-btn ", "tags-btn__sync\" style=\"display: none\" data-sync-style> $", " </span>\n      </div>\n      <div class=\"", "sels-info\">\n        <div class=\"", "label-sel\">", ":</div>\n        <div class=\"", "sels\" data-selected></div>\n      </div>"])), pfx, pfx, pfx, pfx, labelHead, pfx, pfx, pfx, ppfx, ppfx, ppfx, pfx, ppfx, ppfx, pfx, ppfx, pfx, pfx, pfx, pfx, pfx, iconAdd, pfx, pfx, iconSync, pfx, pfx, labelInfo, pfx);
    };
    ClassTagsView.prototype.events = function () {
        return {
            'change [data-states]': 'stateChanged',
            'click [data-add]': 'startNewTag',
            'focusout [data-input]': 'endNewTag',
            'keyup [data-input]': 'onInputKeyUp',
            'click [data-sync-style]': 'syncStyle',
        };
    };
    ClassTagsView.prototype.syncStyle = function () {
        var em = this.em;
        var target = this.getTarget();
        var cssC = em.Css;
        var opts = { noDisabled: 1 };
        var selectors = this.getCommonSelectors({ opts: opts });
        var state = em.get('state');
        var mediaText = em.getCurrentMedia();
        var ruleComponents = [];
        var rule = cssC.get(selectors, state, mediaText) || cssC.add(selectors, state, mediaText);
        var style;
        this.getTargets().forEach(function (target) {
            var ruleComponent = cssC.getIdRule(target.getId(), {
                state: state,
                mediaText: mediaText,
            });
            style = ruleComponent.getStyle();
            ruleComponent.setStyle({});
            ruleComponents.push(ruleComponent);
        });
        style && rule.addStyle(style);
        em.trigger('component:toggled');
        em.trigger('component:sync-style', {
            component: target,
            selectors: selectors,
            mediaText: mediaText,
            rule: rule,
            ruleComponents: ruleComponents,
            state: state,
        });
    };
    /**
     * Triggered when a tag is removed from collection
     * @param {Object} model Removed model
     * @private
     */
    ClassTagsView.prototype.tagRemoved = function (model) {
        this.updateStateVis();
    };
    /**
     * Add new model
     * @param {Object} model
     * @private
     */
    ClassTagsView.prototype.addNew = function (model) {
        this.addToClasses(model);
    };
    /**
     * Start tag creation
     * @param {Object} e
     * @private
     */
    ClassTagsView.prototype.startNewTag = function () {
        var _a, _b;
        (_a = this.$addBtn) === null || _a === void 0 ? void 0 : _a.css({ display: 'none' });
        (_b = this.$input) === null || _b === void 0 ? void 0 : _b.show().focus();
    };
    /**
     * End tag creation
     * @param {Object} e
     * @private
     */
    ClassTagsView.prototype.endNewTag = function () {
        var _a, _b;
        (_a = this.$addBtn) === null || _a === void 0 ? void 0 : _a.css({ display: '' });
        (_b = this.$input) === null || _b === void 0 ? void 0 : _b.hide().val('');
    };
    /**
     * Checks what to do on keyup event
     * @param  {Object} e
     * @private
     */
    ClassTagsView.prototype.onInputKeyUp = function (e) {
        var _a;
        if (e.keyCode === 13) {
            e.preventDefault();
            this.addNewTag((_a = this.$input) === null || _a === void 0 ? void 0 : _a.val());
        }
        else if (e.keyCode === 27) {
            this.endNewTag();
        }
    };
    ClassTagsView.prototype.checkStates = function () {
        var state = this.em.getState();
        var statesEl = this.getStates();
        statesEl && statesEl.val(state);
    };
    /**
     * Triggered when component is changed
     * @param  {Object} e
     * @public
     */
    ClassTagsView.prototype.componentChanged = function (_a) {
        var _b = _a === void 0 ? {} : _a, targets = _b.targets;
        this.updateSelection(targets);
    };
    ClassTagsView.prototype.updateSelection = function (targets) {
        var trgs = targets || this.getTargets();
        trgs = (0,index_all.isArray)(trgs) ? trgs : [trgs];
        var selectors = [];
        if (trgs && trgs.length) {
            selectors = this.getCommonSelectors({ targets: trgs });
            //@ts-ignore TODO This parameters are not in use why do we have them?
            this.checkSync({ validSelectors: selectors });
        }
        this.collection.reset(selectors);
        this.updateStateVis(trgs);
        this.module.__trgCustom();
        return selectors;
    };
    ClassTagsView.prototype.getCommonSelectors = function (_a) {
        var _b = _a === void 0 ? {} : _a, targets = _b.targets, _c = _b.opts, opts = _c === void 0 ? {} : _c;
        var trgs = targets || this.getTargets();
        return this.module.__getCommonSelectors(trgs, opts);
    };
    ClassTagsView.prototype._commonSelectors = function () {
        var _a;
        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            args[_i] = arguments[_i];
        }
        return (_a = this.module).__common.apply(_a, args);
    };
    ClassTagsView.prototype.checkSync = function () {
        var _a = this, $btnSyncEl = _a.$btnSyncEl, config = _a.config, collection = _a.collection;
        var target = this.getTarget();
        var hasStyle;
        if (target && config.componentFirst && collection.length) {
            var style = target.getStyle();
            hasStyle = !(0,index_all.isEmpty)(style);
        }
        $btnSyncEl && $btnSyncEl[hasStyle ? 'show' : 'hide']();
    };
    ClassTagsView.prototype.getTarget = function () {
        return this.target.getSelected();
    };
    ClassTagsView.prototype.getTargets = function () {
        return this.target.getSelectedAll();
    };
    /**
     * Update states visibility. Hides states in case there is no tags
     * inside collection
     * @private
     */
    ClassTagsView.prototype.updateStateVis = function (targets) {
        var em = this.em;
        var avoidInline = em && em.getConfig().avoidInlineStyle;
        var display = this.collection.length || avoidInline ? '' : 'none';
        this.getStatesC().css('display', display);
        this.updateSelector(targets);
    };
    ClassTagsView.prototype.__handleStateChange = function () {
        this.updateSelector(this.getTargets());
    };
    /**
     * Update selector helper
     * @return {this}
     * @private
     */
    ClassTagsView.prototype.updateSelector = function (targets) {
        var _this = this;
        var elSel = this.el.querySelector('[data-selected]');
        var result = [];
        var trgs = targets || this.getTargets();
        trgs = (0,index_all.isArray)(trgs) ? trgs : [trgs];
        trgs.forEach(function (target) { return result.push(_this.__getName(target)); });
        elSel && (elSel.innerHTML = result.join(', '));
        this.checkStates();
    };
    ClassTagsView.prototype.__getName = function (target) {
        var _a = this, pfx = _a.pfx, config = _a.config, em = _a.em;
        var selectedName = config.selectedName, componentFirst = config.componentFirst;
        var result;
        if ((0,index_all.isString)(target)) {
            result = html(templateObject_2 || (templateObject_2 = ClassTagsView_makeTemplateObject(["<span class=\"", "sel-gen\">", "</span>"], ["<span class=\"", "sel-gen\">", "</span>"])), pfx, target);
        }
        else {
            var sel = target === null || target === void 0 ? void 0 : target.getSelectors();
            if (!sel)
                return '';
            var selectors = sel.getStyleable();
            var state = em.get('state');
            var idRes = target.getId
                ? html(templateObject_3 || (templateObject_3 = ClassTagsView_makeTemplateObject(["<span class=\"", "sel-cmp\">", "</span>\n            <span class=\"", "sel-id\">#", "</span>"], ["<span class=\"", "sel-cmp\">", "</span>\n            <span class=\"", "sel-id\">#", "</span>"])), pfx, target.getName(), pfx, target.getId()) : '';
            result = this.collection.getFullString(selectors);
            result = result ? html(templateObject_4 || (templateObject_4 = ClassTagsView_makeTemplateObject(["<span class=\"", "sel-rule\">", "</span>"], ["<span class=\"", "sel-rule\">", "</span>"])), pfx, result) : target.get('selectorsAdd') || idRes;
            result = componentFirst && idRes ? idRes : result;
            result += state ? html(templateObject_5 || (templateObject_5 = ClassTagsView_makeTemplateObject(["<span class=\"", "sel-state\">:", "</span>"], ["<span class=\"", "sel-state\">:", "</span>"])), pfx, state) : '';
            result = selectedName ? selectedName({ result: result, state: state, target: target }) : result;
        }
        return result && "<span class=\"".concat(pfx, "sel\">").concat(result, "</span>");
    };
    /**
     * Triggered when the select with states is changed
     * @param  {Object} e
     * @private
     */
    ClassTagsView.prototype.stateChanged = function (ev) {
        var em = this.em;
        var value = ev.target.value;
        em.set('state', value);
    };
    /**
     * Add new tag to collection, if possible, and to the component
     * @param  {Object} e
     * @private
     */
    ClassTagsView.prototype.addNewTag = function (value) {
        var label = value.trim();
        if (!label)
            return;
        this.module.addSelected({ label: label });
        this.endNewTag();
        // this.updateStateVis(); // Check if required
    };
    /**
     * Add new object to collection
     * @param   {Object} model  Model
     * @param   {Object} fragmentEl   Fragment collection
     * @return {Object} Object created
     * @private
     * */
    ClassTagsView.prototype.addToClasses = function (model, fragmentEl) {
        var fragment = fragmentEl;
        var classes = this.getClasses();
        var rendered = new view_ClassTagView({
            model: model,
            config: this.config,
            coll: this.collection,
            module: this.module,
        }).render().el;
        fragment ? fragment.appendChild(rendered) : classes.append(rendered);
        return rendered;
    };
    /**
     * Render the collection of classes
     * @private
     */
    ClassTagsView.prototype.renderClasses = function () {
        var _this = this;
        var frag = document.createDocumentFragment();
        var classes = this.getClasses();
        classes.empty();
        this.collection.each(function (model) { return _this.addToClasses(model, frag); });
        classes.append(frag);
    };
    /**
     * Return classes element
     * @return {HTMLElement}
     * @private
     */
    ClassTagsView.prototype.getClasses = function () {
        return this.$el.find('[data-selectors]');
    };
    /**
     * Return states element
     * @return {HTMLElement}
     * @private
     */
    ClassTagsView.prototype.getStates = function () {
        if (!this.$states) {
            var el = this.$el.find('[data-states]');
            this.$states = el[0] && el;
        }
        return this.$states;
    };
    /**
     * Return states container element
     * @return {HTMLElement}
     * @private
     */
    ClassTagsView.prototype.getStatesC = function () {
        if (!this.$statesC)
            this.$statesC = this.$el.find('#' + this.stateInputC);
        return this.$statesC;
    };
    ClassTagsView.prototype.renderStates = function () {
        var _a = this, module = _a.module, em = _a.em;
        var labelStates = em.t('selectorManager.emptyState');
        var options = module
            .getStates()
            .map(function (state) {
            var label = em.t("selectorManager.states.".concat(state.id)) || state.getLabel() || state.id;
            return "<option value=\"".concat(state.id, "\">").concat(label, "</option>");
        })
            .join('');
        var statesEl = this.getStates();
        statesEl && statesEl.html("<option value=\"\">".concat(labelStates, "</option>").concat(options));
        this.checkStates();
    };
    ClassTagsView.prototype.render = function () {
        var _a = this, em = _a.em, pfx = _a.pfx, ppfx = _a.ppfx, config = _a.config, $el = _a.$el, el = _a.el;
        var render = config.render, iconSync = config.iconSync, iconAdd = config.iconAdd;
        var tmpOpts = {
            iconSync: iconSync,
            iconAdd: iconAdd,
            labelHead: em.t('selectorManager.label'),
            labelInfo: em.t('selectorManager.selected'),
            ppfx: ppfx,
            pfx: pfx,
            el: el,
        };
        $el.html(this.template(tmpOpts));
        var renderRes = render && render(tmpOpts);
        renderRes && renderRes !== el && $el.empty().append(renderRes);
        this.$input = $el.find('[data-input]');
        this.$addBtn = $el.find('[data-add]');
        this.$classes = $el.find('#' + pfx + 'tags-c');
        this.$btnSyncEl = $el.find('[data-sync-style]');
        this.$input.hide();
        this.renderStates();
        this.renderClasses();
        $el.attr('class', "".concat(this.className, " ").concat(ppfx, "one-bg ").concat(ppfx, "two-color"));
        return this;
    };
    return ClassTagsView;
}(common/* View */.G7));
/* harmony default export */ const view_ClassTagsView = (ClassTagsView);
var ClassTagsView_templateObject_1, templateObject_2, templateObject_3, templateObject_4, templateObject_5;

;// CONCATENATED MODULE: ./src/selector_manager/index.ts
/**
 * Selectors in GrapesJS are used in CSS Composer inside Rules and in Components as classes. To illustrate this concept let's take
 * a look at this code:
 *
 * ```css
 * span > #send-btn.btn{
 *  ...
 * }
 * ```
 * ```html
 * <span>
 *   <button id="send-btn" class="btn"></button>
 * </span>
 * ```
 *
 * In this scenario we get:
 * * span     -> selector of type `tag`
 * * send-btn -> selector of type `id`
 * * btn      -> selector of type `class`
 *
 * So, for example, being `btn` the same class entity it'll be easier to refactor and track things.
 *
 * You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](https://github.com/GrapesJS/grapesjs/blob/master/src/selector_manager/config/config.ts)
 * ```js
 * const editor = grapesjs.init({
 *  selectorManager: {
 *    // options
 *  }
 * })
 * ```
 *
 * Once the editor is instantiated you can use its API and listen to its events. Before using these methods, you should get the module from the instance.
 *
 * ```js
 * // Listen to events
 * editor.on('selector:add', (selector) => { ... });
 *
 * // Use the API
 * const sm = editor.Selectors;
 * sm.add(...);
 * ```
 *
 * ## Available Events
 * * `selector:add` - Selector added. The [Selector] is passed as an argument to the callback.
 * * `selector:remove` - Selector removed. The [Selector] is passed as an argument to the callback.
 * * `selector:update` - Selector updated. The [Selector] and the object containing changes are passed as arguments to the callback.
 * * `selector:state` - States changed. An object containing all the available data about the triggered event is passed as an argument to the callback.
 * * `selector` - Catch-all event for all the events mentioned above. An object containing all the available data about the triggered event is passed as an argument to the callback.
 *
 * ## Methods
 * * [getConfig](#getconfig)
 * * [add](#add)
 * * [get](#get)
 * * [remove](#remove)
 * * [rename](#rename)
 * * [getAll](#getall)
 * * [setState](#setstate)
 * * [getState](#getstate)
 * * [getStates](#getstates)
 * * [setStates](#setstates)
 * * [getSelected](#getselected)
 * * [addSelected](#addselected)
 * * [removeSelected](#removeselected)
 * * [getSelectedTargets](#getselectedtargets)
 * * [setComponentFirst](#setcomponentfirst)
 * * [getComponentFirst](#getcomponentfirst)
 *
 * [Selector]: selector.html
 * [State]: state.html
 * [Component]: component.html
 * [CssRule]: css_rule.html
 *
 * @module Selectors
 */
var selector_manager_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var selector_manager_assign = (undefined && undefined.__assign) || function () {
    selector_manager_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return selector_manager_assign.apply(this, arguments);
};
var selector_manager_spreadArray = (undefined && undefined.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};









var isId = function (str) { return (0,index_all.isString)(str) && str[0] == '#'; };
var isClass = function (str) { return (0,index_all.isString)(str) && str[0] == '.'; };
var selector_manager_evAll = 'selector';
var selector_manager_evPfx = "".concat(selector_manager_evAll, ":");
var selector_manager_evAdd = "".concat(selector_manager_evPfx, "add");
var selector_manager_evUpdate = "".concat(selector_manager_evPfx, "update");
var selector_manager_evRemove = "".concat(selector_manager_evPfx, "remove");
var selector_manager_evRemoveBefore = "".concat(selector_manager_evRemove, ":before");
var evCustom = "".concat(selector_manager_evPfx, "custom");
var evState = "".concat(selector_manager_evPfx, "state");
var selectorEvents = {
    all: selector_manager_evAll,
    update: selector_manager_evUpdate,
    add: selector_manager_evAdd,
    remove: selector_manager_evRemove,
    removeBefore: selector_manager_evRemoveBefore,
    state: evState,
    custom: evCustom,
};
var SelectorManager = /** @class */ (function (_super) {
    selector_manager_extends(SelectorManager, _super);
    /**
     * Get configuration object
     * @name getConfig
     * @function
     * @return {Object}
     */
    function SelectorManager(em) {
        var _this = _super.call(this, em, 'SelectorManager', new model_Selectors([]), selectorEvents, selector_manager_config_config, { skipListen: true }) || this;
        _this.Selector = model_Selector;
        _this.Selectors = model_Selectors;
        _this.storageKey = '';
        (0,index_all.bindAll)(_this, '__updateSelectedByComponents');
        var config = _this.config;
        var ppfx = config.pStylePrefix;
        if (ppfx)
            config.stylePrefix = ppfx + config.stylePrefix;
        // Global selectors container
        _this.all = new model_Selectors(config.selectors);
        _this.selected = new model_Selectors([], { em: em, config: config });
        _this.states = new common/* Collection */.FE(config.states.map(function (state) { return new model_State(state); }), { model: model_State });
        _this.model = new common/* Model */.Hn({ cFirst: config.componentFirst, _undo: true });
        _this.__update = (0,index_all.debounce)(function () { return _this.__trgCustom(); }, 0);
        _this.__initListen({
            collections: [_this.states, _this.selected],
            propagate: [{ entity: _this.states, event: _this.events.state }],
        });
        em.on('change:state', function (m, value) { return em.trigger(evState, value); });
        _this.model.on('change:cFirst', function (m, value) { return em.trigger('selector:type', value); });
        em.on('component:toggled component:update:classes', _this.__updateSelectedByComponents);
        var listenTo = 'component:toggled component:update:classes change:device styleManager:update selector:state selector:type style:target';
        _this.model.listenTo(em, listenTo, function () { return _this.__update(); });
        return _this;
    }
    SelectorManager.prototype.__trgCustom = function (opts) {
        this.em.trigger(this.events.custom, this.__customData(opts));
    };
    SelectorManager.prototype.getAll = function (opts) {
        if (opts === void 0) { opts = {}; }
        return (this.all ? (opts.array ? selector_manager_spreadArray([], this.all.models, true) : this.all) : []);
    };
    SelectorManager.prototype.__customData = function (opts) {
        if (opts === void 0) { opts = {}; }
        this.__ctn = this.__ctn || opts.container;
        return {
            states: this.getStates(),
            selected: this.getSelected(),
            container: this.__ctn,
        };
    };
    // postLoad() {
    //   this.__postLoad();
    //   const { em, model } = this;
    //   const um = em.get('UndoManager');
    //   um && um.add(model);
    //   um && um.add(this.pages);
    // },
    SelectorManager.prototype.postRender = function () {
        this.__appendTo();
        this.__trgCustom();
    };
    SelectorManager.prototype.select = function (value, opts) {
        if (opts === void 0) { opts = {}; }
        var targets = Array.isArray(value) ? value : [value];
        var toSelect = this.em.Styles.select(targets, opts);
        this.selected.reset(this.__getCommonSelectors(toSelect));
        var selTags = this.selectorTags;
        var res = toSelect
            .filter(function (i) { return i; })
            .map(function (sel) { return ((0,mixins.isComponent)(sel) ? sel : (0,mixins.isRule)(sel) && !sel.get('selectorsAdd') ? sel : sel.getSelectorsString()); });
        selTags && selTags.componentChanged({ targets: res });
        return this;
    };
    SelectorManager.prototype.addSelector = function (name, opts, cOpts) {
        if (opts === void 0) { opts = {}; }
        if (cOpts === void 0) { cOpts = {}; }
        var props = selector_manager_assign({}, opts);
        if ((0,index_all.isObject)(name)) {
            props = name;
        }
        else {
            props.name = name;
        }
        if (isId(props.name)) {
            props.name = props.name.substr(1);
            props.type = model_Selector.TYPE_ID;
        }
        else if (isClass(props.name)) {
            props.name = props.name.substr(1);
        }
        if (props.label && !props.name) {
            props.name = this.escapeName(props.label);
        }
        var cname = props.name;
        var config = this.getConfig();
        var _a = this, all = _a.all, em = _a.em;
        var selector = cname ? this.get(cname, props.type) : all.where(props)[0];
        if (!selector) {
            var selModel = props instanceof model_Selector ? props : new model_Selector(props, selector_manager_assign(selector_manager_assign({}, cOpts), { config: config, em: em }));
            return all.add(selModel, cOpts);
        }
        return selector;
    };
    SelectorManager.prototype.getSelector = function (name, type) {
        if (type === void 0) { type = model_Selector.TYPE_CLASS; }
        if (isId(name)) {
            name = name.substr(1);
            type = model_Selector.TYPE_ID;
        }
        else if (isClass(name)) {
            name = name.substr(1);
        }
        return this.all.where({ name: name, type: type })[0];
    };
    /**
     * Add a new selector to the collection if it does not already exist.
     * You can pass selectors properties or string identifiers.
     * @param {Object|String} props Selector properties or string identifiers, eg. `{ name: 'my-class', label: 'My class' }`, `.my-cls`
     * @param {Object} [opts] Selector options
     * @return {[Selector]}
     * @example
     * const selector = selectorManager.add({ name: 'my-class', label: 'My class' });
     * console.log(selector.toString()) // `.my-class`
     * // Same as
     * const selector = selectorManager.add('.my-class');
     * console.log(selector.toString()) // `.my-class`
     * */
    SelectorManager.prototype.add = function (props, opts) {
        var _this = this;
        if (opts === void 0) { opts = {}; }
        var cOpts = (0,index_all.isString)(props) ? {} : opts;
        // Keep support for arrays but avoid it in docs
        if ((0,index_all.isArray)(props)) {
            return props.map(function (item) { return _this.addSelector(item, opts, cOpts); });
        }
        else {
            return this.addSelector(props, opts, cOpts);
        }
    };
    /**
     * Add class selectors
     * @param {Array|string} classes Array or string of classes
     * @return {Array} Array of added selectors
     * @private
     * @example
     * sm.addClass('class1');
     * sm.addClass('class1 class2');
     * sm.addClass(['class1', 'class2']);
     * // -> [SelectorObject, ...]
     */
    SelectorManager.prototype.addClass = function (classes) {
        var _this = this;
        var added = [];
        if ((0,index_all.isString)(classes)) {
            classes = classes.trim().split(' ');
        }
        classes.forEach(function (name) { return added.push(_this.addSelector(name)); });
        return added;
    };
    /**
     * Get the selector by its name/type
     * @param {String} name Selector name or string identifier
     * @returns {[Selector]|null}
     * @example
     * const selector = selectorManager.get('.my-class');
     * // Get Id
     * const selectorId = selectorManager.get('#my-id');
     * */
    SelectorManager.prototype.get = function (name, type) {
        var _this = this;
        // Keep support for arrays but avoid it in docs
        if ((0,index_all.isArray)(name)) {
            var result_1 = [];
            var selectors = name.map(function (item) { return _this.getSelector(item); }).filter(Boolean);
            selectors.forEach(function (item) { return result_1.indexOf(item) < 0 && result_1.push(item); });
            // @ts-ignore
            return result_1;
        }
        else {
            // @ts-ignore
            return this.getSelector(name, type);
        }
    };
    /**
     * Remove Selector.
     * @param {String|[Selector]} selector Selector instance or Selector string identifier
     * @returns {[Selector]} Removed Selector
     * @example
     * const removed = selectorManager.remove('.myclass');
     * // or by passing the Selector
     * selectorManager.remove(selectorManager.get('.myclass'));
     */
    SelectorManager.prototype.remove = function (selector, opts) {
        return this.__remove(selector, opts);
    };
    /**
     * Rename Selector.
     * @param {[Selector]} selector Selector to update.
     * @param {String} name New name for the selector.
     * @returns {[Selector]} Selector containing the passed name.
     * @example
     * const selector = selectorManager.get('myclass');
     * const result = selectorManager.rename(selector, 'myclass2');
     * console.log(result === selector ? 'Selector updated' : 'Selector with this name exists already');
     */
    SelectorManager.prototype.rename = function (selector, name, opts) {
        var newName = this.escapeName(name);
        var result = this.get(newName);
        return result || selector.set({ name: newName, label: name }, opts);
    };
    /**
     * Change the selector state
     * @param {String} value State value
     * @returns {this}
     * @example
     * selectorManager.setState('hover');
     */
    SelectorManager.prototype.setState = function (value) {
        this.em.setState(value);
        return this;
    };
    /**
     * Get the current selector state value
     * @returns {String}
     */
    SelectorManager.prototype.getState = function () {
        return this.em.getState();
    };
    /**
     * Get states
     * @returns {Array<[State]>}
     */
    SelectorManager.prototype.getStates = function () {
        return selector_manager_spreadArray([], this.states.models, true);
    };
    /**
     * Set a new collection of states
     * @param {Array<Object>} states Array of new states
     * @returns {Array<[State]>}
     * @example
     * const states = selectorManager.setStates([
     *   { name: 'hover', label: 'Hover' },
     *   { name: 'nth-of-type(2n)', label: 'Even/Odd' }
     * ]);
     */
    SelectorManager.prototype.setStates = function (states, opts) {
        return this.states.reset(states.map(function (state) { return new model_State(state); }), opts);
    };
    /**
     * Get commonly selected selectors, based on all selected components.
     * @returns {Array<[Selector]>}
     * @example
     * const selected = selectorManager.getSelected();
     * console.log(selected.map(s => s.toString()))
     */
    SelectorManager.prototype.getSelected = function () {
        return this.__getCommon();
    };
    /**
     * Get selected selectors.
     * @returns {Array<[Selector]>}
     * @example
     * const selected = selectorManager.getSelectedAll();
     * console.log(selected.map(s => s.toString()))
     */
    SelectorManager.prototype.getSelectedAll = function () {
        return selector_manager_spreadArray([], this.selected.models, true);
    };
    /**
     * Add new selector to all selected components.
     * @param {Object|String} props Selector properties or string identifiers, eg. `{ name: 'my-class', label: 'My class' }`, `.my-cls`
     * @example
     * selectorManager.addSelected('.new-class');
     */
    SelectorManager.prototype.addSelected = function (props) {
        var added = this.add(props);
        this.em.getSelectedAll().forEach(function (target) {
            target.getSelectors().add(added);
        });
        // TODO: update selected collection
    };
    /**
     * Remove a common selector from all selected components.
     * @param {String|[Selector]} selector Selector instance or Selector string identifier
     * @example
     * selectorManager.removeSelected('.myclass');
     */
    SelectorManager.prototype.removeSelected = function (selector) {
        this.em.getSelectedAll().forEach(function (trg) {
            !selector.get('protected') && trg && trg.getSelectors().remove(selector);
        });
    };
    SelectorManager.prototype.duplicateSelected = function (selector, opts) {
        var _this = this;
        if (opts === void 0) { opts = {}; }
        var em = this.em;
        var commonSelectors = this.getSelected();
        if (commonSelectors.indexOf(selector) < 0)
            return;
        var state = this.getState();
        var media = em.getCurrentMedia();
        var rule = em.Css.get(commonSelectors, state, media);
        var styleToApply = rule === null || rule === void 0 ? void 0 : rule.getStyle();
        em.getSelectedAll().forEach(function (component) {
            var selectors = component.getSelectors();
            if (selectors.includes(selector)) {
                var suffix = opts.suffix || ' copy';
                var label = selector.getLabel();
                var newSelector = _this.addSelector("".concat(label).concat(suffix));
                var at = selectors.indexOf(selector);
                selectors.remove(selector);
                selectors.add(newSelector, { at: at });
            }
        });
        if (styleToApply) {
            var newRule = em.Css.add(this.getSelected(), state, media);
            newRule.setStyle(styleToApply);
        }
    };
    /**
     * Get the array of currently selected targets.
     * @returns {Array<[Component]|[CssRule]>}
     * @example
     * const targetsToStyle = selectorManager.getSelectedTargets();
     * console.log(targetsToStyle.map(target => target.getSelectorsString()))
     */
    SelectorManager.prototype.getSelectedTargets = function () {
        return this.em.Styles.getSelectedAll();
    };
    /**
     * Update component-first option.
     * If the component-first is enabled, all the style changes will be applied on selected components (ID rules) instead
     * of selectors (which would change styles on all components with those classes).
     * @param {Boolean} value
     */
    SelectorManager.prototype.setComponentFirst = function (value) {
        this.getConfig().componentFirst = value;
        this.model.set({ cFirst: value });
    };
    /**
     * Get the value of component-first option.
     * @return {Boolean}
     */
    SelectorManager.prototype.getComponentFirst = function () {
        return this.getConfig().componentFirst;
    };
    /**
     * Get all selectors
     * @name getAll
     * @function
     * @return {Collection<[Selector]>}
     * */
    /**
     * Return escaped selector name
     * @param {String} name Selector name to escape
     * @returns {String} Escaped name
     * @private
     */
    SelectorManager.prototype.escapeName = function (name) {
        var escapeName = this.getConfig().escapeName;
        return escapeName ? escapeName(name) : model_Selector.escapeName(name);
    };
    /**
     * Render class selectors. If an array of selectors is provided a new instance of the collection will be rendered
     * @param {Array<Object>} selectors
     * @return {HTMLElement}
     * @private
     */
    SelectorManager.prototype.render = function (selectors) {
        var selectorTags = this.selectorTags;
        var config = this.getConfig();
        var el = selectorTags === null || selectorTags === void 0 ? void 0 : selectorTags.el;
        this.selected.reset(selectors);
        this.selectorTags = new view_ClassTagsView({
            el: el,
            collection: this.selected,
            //@ts-ignore
            module: this,
            config: config,
        });
        return this.selectorTags.render().el;
    };
    SelectorManager.prototype.destroy = function () {
        var _a = this, selectorTags = _a.selectorTags, model = _a.model;
        model.stopListening();
        this.__update.cancel();
        this.__destroy();
        selectorTags === null || selectorTags === void 0 ? void 0 : selectorTags.remove();
        this.selectorTags = undefined;
    };
    /**
     * Get common selectors from the current selection.
     * @return {Array<Selector>}
     * @private
     */
    SelectorManager.prototype.__getCommon = function () {
        return this.__getCommonSelectors(this.em.getSelectedAll());
    };
    SelectorManager.prototype.__getCommonSelectors = function (components, opts) {
        if (opts === void 0) { opts = {}; }
        var selectors = components.map(function (cmp) { return cmp.getSelectors && cmp.getSelectors().getValid(opts); }).filter(Boolean);
        return this.__common.apply(this, selectors);
    };
    SelectorManager.prototype.__common = function () {
        var _this = this;
        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            args[_i] = arguments[_i];
        }
        if (!args.length)
            return [];
        if (args.length === 1)
            return args[0];
        if (args.length === 2)
            return args[0].filter(function (item) { return args[1].indexOf(item) >= 0; });
        return (args
            .slice(1)
            //@ts-ignore
            .reduce(function (acc, item) { return _this.__common(acc, item); }, args[0]));
    };
    SelectorManager.prototype.__updateSelectedByComponents = function () {
        this.selected.reset(this.__getCommon());
    };
    return SelectorManager;
}(ItemManagerModule));
/* harmony default export */ const selector_manager = (SelectorManager);

;// CONCATENATED MODULE: ./src/parser/config/config.ts
var parser_config_config_config = {
    textTags: ['br', 'b', 'i', 'u', 'a', 'ul', 'ol'],
    textTypes: ['text', 'textnode', 'comment'],
    parserCss: undefined,
    parserHtml: undefined,
    optionsHtml: {
        htmlType: 'text/html',
        allowScripts: false,
        allowUnsafeAttr: false,
        allowUnsafeAttrValue: false,
        keepEmptyTextNodes: false,
    },
};
/* harmony default export */ const parser_config_config = (parser_config_config_config);

;// CONCATENATED MODULE: ./src/parser/model/BrowserParserCss.ts
var _a;

/** @see https://developer.mozilla.org/en-US/docs/Web/API/CSSRule/type */
var CSS_RULE_TYPES = {
    STYLE_RULE: 1,
    CHARSET_RULE: 2,
    IMPORT_RULE: 3,
    MEDIA_RULE: 4,
    FONT_FACE_RULE: 5,
    PAGE_RULE: 6,
    KEYFRAMES_RULE: 7,
    KEYFRAME_RULE: 8,
    NAMESPACE_RULE: 10,
    COUNTER_STYLE_RULE: 11,
    SUPPORTS_RULE: 12,
    DOCUMENT_RULE: 13,
    FONT_FEATURE_VALUES_RULE: 14,
    VIEWPORT_RULE: 15,
    REGION_STYLE_RULE: 16,
};
/** @see https://developer.mozilla.org/en-US/docs/Web/CSS/At-rule  */
var AT_RULE_NAMES = (_a = {},
    _a[CSS_RULE_TYPES.MEDIA_RULE] = 'media',
    _a[CSS_RULE_TYPES.FONT_FACE_RULE] = 'font-face',
    _a[CSS_RULE_TYPES.PAGE_RULE] = 'page',
    _a[CSS_RULE_TYPES.KEYFRAMES_RULE] = 'keyframes',
    _a[CSS_RULE_TYPES.COUNTER_STYLE_RULE] = 'counter-style',
    _a[CSS_RULE_TYPES.SUPPORTS_RULE] = 'supports',
    _a[CSS_RULE_TYPES.DOCUMENT_RULE] = 'document',
    _a[CSS_RULE_TYPES.FONT_FEATURE_VALUES_RULE] = 'font-feature-values',
    _a[CSS_RULE_TYPES.VIEWPORT_RULE] = 'viewport',
    _a);
var AT_RULE_KEYS = (0,index_all.keys)(AT_RULE_NAMES);
var SINGLE_AT_RULE_TYPES = [
    CSS_RULE_TYPES.FONT_FACE_RULE,
    CSS_RULE_TYPES.PAGE_RULE,
    CSS_RULE_TYPES.COUNTER_STYLE_RULE,
    CSS_RULE_TYPES.VIEWPORT_RULE,
];
var NESTABLE_AT_RULE_NAMES = AT_RULE_KEYS.filter(function (i) { return SINGLE_AT_RULE_TYPES.indexOf(Number(i)) < 0; })
    .map(function (i) { return AT_RULE_NAMES[i]; })
    .concat(['container', 'layer']);
var SINGLE_AT_RULE_NAMES = SINGLE_AT_RULE_TYPES.map(function (n) { return AT_RULE_NAMES[n]; });
/**
 * Parse selector string to array.
 * Only classe based are valid as CSS rules inside editor, not valid
 * selectors will be dropped as additional
 * It's ok with the last part of the string as state (:hover, :active)
 * @param  {string} str Selectors string
 * @return {Object}
 * @example
 * var res = parseSelector('.test1, .test1.test2, .test2 .test3');
 * console.log(res);
 * // { result: [['test1'], ['test1', 'test2']], add: ['.test2 .test3'] }
 */
var parseSelector = function (str) {
    if (str === void 0) { str = ''; }
    var add = [];
    var result = [];
    var sels = str.split(',');
    for (var i = 0, len = sels.length; i < len; i++) {
        var sel = sels[i].trim();
        // Will accept only concatenated classes and last
        // class might be with state (eg. :hover), nothing else.
        // Can also accept SINGLE ID selectors, eg. `#myid`, `#myid:hover`
        // Composed are not valid: `#myid.some-class`, `#myid.some-class:hover`
        if (/^(\.{1}[\w\-]+)+(:{1,2}[\w\-()]+)?$/gi.test(sel) || /^(#{1}[\w\-]+){1}(:{1,2}[\w\-()]+)?$/gi.test(sel)) {
            var cls = sel.split('.').filter(Boolean);
            result.push(cls);
        }
        else {
            add.push(sel);
        }
    }
    return {
        result: result,
        add: add,
    };
};
/**
 * Parse style declarations of the node.
 * @param {CSSRule} node
 * @return {Object}
 */
var parseStyle = function (node) {
    var stl = node.style;
    var style = {};
    for (var i = 0, len = stl.length; i < len; i++) {
        var propName = stl[i];
        var propValue = stl.getPropertyValue(propName);
        var important = stl.getPropertyPriority(propName);
        style[propName] = "".concat(propValue).concat(important ? " !".concat(important) : '');
    }
    return style;
};
/**
 * Get the condition when possible
 * @param  {CSSRule} node
 * @return {string}
 */
var parseCondition = function (node) {
    // @ts-ignore
    var condition = node.conditionText || (node.media && node.media.mediaText) || node.name || node.selectorText || '';
    return condition.trim();
};
/**
 * Create node for the editor
 * @param  {Array<String>} selectors Array containing strings of classes
 * @param {Object} style Key-value object of style declarations
 * @return {Object}
 */
var createNode = function (selectors, style, opts) {
    if (style === void 0) { style = {}; }
    if (opts === void 0) { opts = {}; }
    var node = {};
    var selLen = selectors.length;
    var lastClass = selectors[selLen - 1];
    var stateArr = lastClass ? lastClass.split(/:(.+)/) : [];
    var state = stateArr[1];
    // @ts-ignore
    var atRule = opts.atRule, selectorsAdd = opts.selectorsAdd, mediaText = opts.mediaText;
    var singleAtRule = SINGLE_AT_RULE_NAMES.indexOf(atRule) >= 0;
    singleAtRule && (node.singleAtRule = true);
    atRule && (node.atRuleType = atRule);
    selectorsAdd && (node.selectorsAdd = selectorsAdd);
    mediaText && (node.mediaText = mediaText);
    // Isolate the state from selectors
    if (state) {
        selectors[selLen - 1] = stateArr[0];
        node.state = state;
        stateArr.splice(stateArr.length - 1, 1);
    }
    node.selectors = selectors;
    node.style = style;
    return node;
};
var getNestableAtRule = function (node) {
    var _a = node.cssText, cssText = _a === void 0 ? '' : _a;
    return NESTABLE_AT_RULE_NAMES.find(function (name) { return cssText.indexOf("@".concat(name)) === 0; });
};
/**
 * Fetch data from node
 * @param  {StyleSheet|CSSRule} el
 * @return {Array<Object>}
 */
var parseNode = function (el) {
    var result = [];
    var nodes = el.cssRules || [];
    for (var i = 0, len = nodes.length; i < len; i++) {
        var node = nodes[i];
        var type = node.type;
        var singleAtRule = false;
        var atRuleType = '';
        var condition = '';
        var sels = node.selectorText || node.keyText || '';
        var isSingleAtRule = SINGLE_AT_RULE_TYPES.indexOf(type) >= 0;
        // Check if the node is an at-rule
        if (isSingleAtRule) {
            singleAtRule = true;
            atRuleType = AT_RULE_NAMES[type];
            condition = parseCondition(node);
        }
        else if (AT_RULE_KEYS.indexOf("".concat(type)) >= 0 || (!type && getNestableAtRule(node))) {
            var subRules = parseNode(node);
            var subAtRuleType = AT_RULE_NAMES[type] || getNestableAtRule(node);
            condition = parseCondition(node);
            for (var s = 0, lens = subRules.length; s < lens; s++) {
                var subRule = subRules[s];
                condition && (subRule.mediaText = condition);
                subRule.atRuleType = subAtRuleType;
            }
            result = result.concat(subRules);
        }
        if (!sels && !isSingleAtRule)
            continue;
        var style = parseStyle(node);
        var selsParsed = parseSelector(sels);
        var selsAdd = selsParsed.add;
        var selsArr = selsParsed.result;
        var lastRule = void 0;
        // For each group of selectors
        for (var k = 0, len3 = selsArr.length; k < len3; k++) {
            var model = createNode(selsArr[k], style, {
                atRule: AT_RULE_NAMES[type],
            });
            result.push(model);
            lastRule = model;
        }
        // Need to push somewhere not class-based selectors, if some rule was
        // created will push them there, otherwise will create a new rule
        if (selsAdd.length) {
            var selsAddStr = selsAdd.join(', ');
            if (lastRule) {
                lastRule.selectorsAdd = selsAddStr;
            }
            else {
                var model = {
                    selectors: [],
                    selectorsAdd: selsAddStr,
                    style: style,
                };
                singleAtRule && (model.singleAtRule = singleAtRule);
                atRuleType && (model.atRuleType = atRuleType);
                condition && (model.mediaText = condition);
                result.push(model);
            }
        }
    }
    return result;
};
/**
 * Parse CSS string and return the array of objects
 * @param  {String} str CSS string
 * @return {Array<Object>} Array of objects for the definition of CSSRules
 */
/* harmony default export */ const BrowserParserCss = (function (str) {
    var el = document.createElement('style');
    el.innerHTML = str;
    // There is no .sheet before adding it to the <head>
    document.head.appendChild(el);
    var sheet = el.sheet;
    document.head.removeChild(el);
    return sheet ? parseNode(sheet) : [];
});

;// CONCATENATED MODULE: ./src/parser/model/ParserCss.ts


var ParserCss = function (em, config) {
    if (config === void 0) { config = {}; }
    return ({
        /**
         * Parse CSS string to a desired model object
         * @param  {String} input CSS string
         * @return {Array<Object>}
         */
        parse: function (input) {
            var _this = this;
            var output = [];
            var parserCss = config.parserCss;
            var editor = em === null || em === void 0 ? void 0 : em.Editor;
            var nodes = parserCss ? parserCss(input, editor) : BrowserParserCss(input);
            nodes.forEach(function (node) { return (output = output.concat(_this.checkNode(node))); });
            em === null || em === void 0 ? void 0 : em.trigger('parse:css', { input: input, output: output, nodes: nodes });
            return output;
        },
        /**
         * Check the returned node from a custom parser and transforms it to
         * a valid object for the CSS composer
         * @return {[type]}
         */
        checkNode: function (node) {
            var selectors = node.selectors, style = node.style;
            var result = [node];
            if ((0,index_all.isString)(selectors)) {
                var nodes_1 = [];
                var parsedNode = node;
                var selsParsed = parseSelector(selectors);
                var classSets = selsParsed.result;
                var selectorsAdd = selsParsed.add.join(', ');
                var opts_1 = { atRule: parsedNode.atRule, mediaText: parsedNode.params };
                if (classSets.length) {
                    classSets.forEach(function (classSet) {
                        nodes_1.push(createNode(classSet, style, opts_1));
                    });
                }
                else {
                    nodes_1.push(createNode([], style, opts_1));
                }
                if (selectorsAdd) {
                    var lastNode = nodes_1[nodes_1.length - 1];
                    lastNode.selectorsAdd = selectorsAdd;
                }
                result = nodes_1;
            }
            return result;
        },
    });
};
/* harmony default export */ const model_ParserCss = (ParserCss);

;// CONCATENATED MODULE: ./src/parser/index.ts
var parser_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
/**
 * You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](https://github.com/GrapesJS/grapesjs/blob/master/src/parser/config/config.ts)
 * ```js
 * const editor = grapesjs.init({
 *  parser: {
 *    // options
 *  }
 * })
 * ```
 *
 * Once the editor is instantiated you can use its API. Before using these methods you should get the module from the instance
 *
 * ```js
 * const { Parser } = editor;
 * ```
 * ## Available Events
 * * `parse:html` - On HTML parse, an object containing the input and the output of the parser is passed as an argument
 * * `parse:css` - On CSS parse, an object containing the input and the output of the parser is passed as an argument
 *
 * ## Methods
 * * [getConfig](#getconfig)
 * * [parseHtml](#parsehtml)
 * * [parseCss](#parsecss)
 *
 * @module Parser
 */




var ParserModule = /** @class */ (function (_super) {
    parser_extends(ParserModule, _super);
    function ParserModule(em) {
        var _this = _super.call(this, em, 'Parser', parser_config_config) || this;
        var config = _this.config;
        _this.parserCss = model_ParserCss(em, config);
        _this.parserHtml = model_ParserHtml(em, config);
        return _this;
    }
    /**
     * Get configuration object
     * @name getConfig
     * @function
     * @return {Object}
     */
    /**
     * Parse HTML string and return the object containing the Component Definition
     * @param  {String} input HTML string to parse
     * @param  {Object} [options] Options
     * @param  {String} [options.htmlType] [HTML mime type](https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString#Argument02) to parse
     * @param  {Boolean} [options.allowScripts=false] Allow `<script>` tags
     * @param  {Boolean} [options.allowUnsafeAttr=false] Allow unsafe HTML attributes (eg. `on*` inline event handlers)
     * @returns {Object} Object containing the result `{ html: ..., css: ... }`
     * @example
     * const resHtml = Parser.parseHtml(`<table><div>Hi</div></table>`, {
     *   htmlType: 'text/html', // default
     * });
     * // By using the `text/html`, this will fix automatically all the HTML syntax issues
     * // Indeed the final representation, in this case, will be `<div>Hi</div><table></table>`
     * const resXml = Parser.parseHtml(`<table><div>Hi</div></table>`, {
     *   htmlType: 'application/xml',
     * });
     * // This will preserve the original format as, from the XML point of view, is a valid format
     */
    ParserModule.prototype.parseHtml = function (input, options) {
        if (options === void 0) { options = {}; }
        var _a = this, em = _a.em, parserHtml = _a.parserHtml;
        parserHtml.compTypes = (em.Components.getTypes() || {});
        return parserHtml.parse(input, this.parserCss, options);
    };
    /**
     * Parse CSS string and return an array of valid definition objects for CSSRules
     * @param  {String} input CSS string to parse
     * @returns {Array<Object>} Array containing the result
     * @example
     * const res = Parser.parseCss('.cls { color: red }');
     * // [{ ... }]
     */
    ParserModule.prototype.parseCss = function (input) {
        return this.parserCss.parse(input);
    };
    ParserModule.prototype.destroy = function () { };
    return ParserModule;
}(abstract_Module));
/* harmony default export */ const parser = (ParserModule);

;// CONCATENATED MODULE: ./src/storage_manager/config/config.ts
var storage_manager_config_config_config = {
    id: 'gjs-',
    type: 'local',
    autosave: true,
    autoload: true,
    stepsBeforeSave: 1,
    recovery: false,
    onStore: function (data) { return data; },
    onLoad: function (data) { return data; },
    options: {
        local: {
            key: 'gjsProject',
            checkLocal: true,
        },
        remote: {
            headers: {},
            urlStore: '',
            urlLoad: '',
            contentTypeJson: true,
            fetchOptions: '',
            credentials: 'include',
            onStore: function (data) { return data; },
            onLoad: function (result) { return result; },
        },
    },
};
/* harmony default export */ const storage_manager_config_config = (storage_manager_config_config_config);

;// CONCATENATED MODULE: ./src/storage_manager/model/LocalStorage.ts
var LocalStorage_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var LocalStorage_generator = (undefined && undefined.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};

var LocalStorage = /** @class */ (function () {
    function LocalStorage() {
    }
    LocalStorage.prototype.store = function (data, opts) {
        if (opts === void 0) { opts = {}; }
        return LocalStorage_awaiter(this, void 0, void 0, function () {
            return LocalStorage_generator(this, function (_a) {
                if (this.hasLocal(opts, true)) {
                    localStorage.setItem(opts.key, JSON.stringify(data));
                }
                return [2 /*return*/, data];
            });
        });
    };
    LocalStorage.prototype.load = function (opts) {
        if (opts === void 0) { opts = {}; }
        return LocalStorage_awaiter(this, void 0, void 0, function () {
            var result;
            return LocalStorage_generator(this, function (_a) {
                result = {};
                if (this.hasLocal(opts, true)) {
                    result = JSON.parse(localStorage.getItem(opts.key) || '{}');
                }
                return [2 /*return*/, result];
            });
        });
    };
    LocalStorage.prototype.hasLocal = function (opts, thr) {
        if (opts === void 0) { opts = {}; }
        if (opts.checkLocal && (!(0,mixins.hasWin)() || !localStorage)) {
            if (thr)
                throw new Error('localStorage not available');
            return false;
        }
        return true;
    };
    return LocalStorage;
}());
/* harmony default export */ const model_LocalStorage = (LocalStorage);

;// CONCATENATED MODULE: ./node_modules/@babel/runtime/helpers/esm/typeof.js
function _typeof(o) {
  "@babel/helpers - typeof";

  return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
    return typeof o;
  } : function (o) {
    return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
  }, _typeof(o);
}
;// CONCATENATED MODULE: ./node_modules/promise-polyfill/src/finally.js
/**
 * @this {Promise}
 */
function finallyConstructor(callback) {
  var constructor = this.constructor;
  return this.then(function (value) {
    // @ts-ignore
    return constructor.resolve(callback()).then(function () {
      return value;
    });
  }, function (reason) {
    // @ts-ignore
    return constructor.resolve(callback()).then(function () {
      // @ts-ignore
      return constructor.reject(reason);
    });
  });
}
/* harmony default export */ const src_finally = (finallyConstructor);
;// CONCATENATED MODULE: ./node_modules/promise-polyfill/src/allSettled.js

function allSettled(arr) {
  var P = this;
  return new P(function (resolve, reject) {
    if (!(arr && typeof arr.length !== 'undefined')) {
      return reject(new TypeError(_typeof(arr) + ' ' + arr + ' is not iterable(cannot read property Symbol(Symbol.iterator))'));
    }
    var args = Array.prototype.slice.call(arr);
    if (args.length === 0) return resolve([]);
    var remaining = args.length;
    function res(i, val) {
      if (val && (_typeof(val) === 'object' || typeof val === 'function')) {
        var then = val.then;
        if (typeof then === 'function') {
          then.call(val, function (val) {
            res(i, val);
          }, function (e) {
            args[i] = {
              status: 'rejected',
              reason: e
            };
            if (--remaining === 0) {
              resolve(args);
            }
          });
          return;
        }
      }
      args[i] = {
        status: 'fulfilled',
        value: val
      };
      if (--remaining === 0) {
        resolve(args);
      }
    }
    for (var i = 0; i < args.length; i++) {
      res(i, args[i]);
    }
  });
}
/* harmony default export */ const src_allSettled = (allSettled);
;// CONCATENATED MODULE: ./node_modules/promise-polyfill/src/any.js
/**
 * @constructor
 */
function AggregateError(errors, message) {
  this.name = 'AggregateError', this.errors = errors;
  this.message = message || '';
}
AggregateError.prototype = Error.prototype;
function any(arr) {
  var P = this;
  return new P(function (resolve, reject) {
    if (!(arr && typeof arr.length !== 'undefined')) {
      return reject(new TypeError('Promise.any accepts an array'));
    }
    var args = Array.prototype.slice.call(arr);
    if (args.length === 0) return reject();
    var rejectionReasons = [];
    for (var i = 0; i < args.length; i++) {
      try {
        P.resolve(args[i]).then(resolve).catch(function (error) {
          rejectionReasons.push(error);
          if (rejectionReasons.length === args.length) {
            reject(new AggregateError(rejectionReasons, 'All promises were rejected'));
          }
        });
      } catch (ex) {
        reject(ex);
      }
    }
  });
}
/* harmony default export */ const src_any = (any);
;// CONCATENATED MODULE: ./node_modules/promise-polyfill/src/index.js





// Store setTimeout reference so promise-polyfill will be unaffected by
// other code modifying setTimeout (like sinon.useFakeTimers())
var setTimeoutFunc = setTimeout;
function isArray(x) {
  return Boolean(x && typeof x.length !== 'undefined');
}
function noop() {}

// Polyfill for Function.prototype.bind
function bind(fn, thisArg) {
  return function () {
    fn.apply(thisArg, arguments);
  };
}

/**
 * @constructor
 * @param {Function} fn
 */
function src_Promise(fn) {
  if (!(this instanceof src_Promise)) throw new TypeError('Promises must be constructed via new');
  if (typeof fn !== 'function') throw new TypeError('not a function');
  /** @type {!number} */
  this._state = 0;
  /** @type {!boolean} */
  this._handled = false;
  /** @type {Promise|undefined} */
  this._value = undefined;
  /** @type {!Array<!Function>} */
  this._deferreds = [];
  doResolve(fn, this);
}
function handle(self, deferred) {
  while (self._state === 3) {
    self = self._value;
  }
  if (self._state === 0) {
    self._deferreds.push(deferred);
    return;
  }
  self._handled = true;
  src_Promise._immediateFn(function () {
    var cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected;
    if (cb === null) {
      (self._state === 1 ? resolve : reject)(deferred.promise, self._value);
      return;
    }
    var ret;
    try {
      ret = cb(self._value);
    } catch (e) {
      reject(deferred.promise, e);
      return;
    }
    resolve(deferred.promise, ret);
  });
}
function resolve(self, newValue) {
  try {
    // Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure
    if (newValue === self) throw new TypeError('A promise cannot be resolved with itself.');
    if (newValue && (_typeof(newValue) === 'object' || typeof newValue === 'function')) {
      var then = newValue.then;
      if (newValue instanceof src_Promise) {
        self._state = 3;
        self._value = newValue;
        finale(self);
        return;
      } else if (typeof then === 'function') {
        doResolve(bind(then, newValue), self);
        return;
      }
    }
    self._state = 1;
    self._value = newValue;
    finale(self);
  } catch (e) {
    reject(self, e);
  }
}
function reject(self, newValue) {
  self._state = 2;
  self._value = newValue;
  finale(self);
}
function finale(self) {
  if (self._state === 2 && self._deferreds.length === 0) {
    src_Promise._immediateFn(function () {
      if (!self._handled) {
        src_Promise._unhandledRejectionFn(self._value);
      }
    });
  }
  for (var i = 0, len = self._deferreds.length; i < len; i++) {
    handle(self, self._deferreds[i]);
  }
  self._deferreds = null;
}

/**
 * @constructor
 */
function Handler(onFulfilled, onRejected, promise) {
  this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
  this.onRejected = typeof onRejected === 'function' ? onRejected : null;
  this.promise = promise;
}

/**
 * Take a potentially misbehaving resolver function and make sure
 * onFulfilled and onRejected are only called once.
 *
 * Makes no guarantees about asynchrony.
 */
function doResolve(fn, self) {
  var done = false;
  try {
    fn(function (value) {
      if (done) return;
      done = true;
      resolve(self, value);
    }, function (reason) {
      if (done) return;
      done = true;
      reject(self, reason);
    });
  } catch (ex) {
    if (done) return;
    done = true;
    reject(self, ex);
  }
}
src_Promise.prototype['catch'] = function (onRejected) {
  return this.then(null, onRejected);
};
src_Promise.prototype.then = function (onFulfilled, onRejected) {
  // @ts-ignore
  var prom = new this.constructor(noop);
  handle(this, new Handler(onFulfilled, onRejected, prom));
  return prom;
};
src_Promise.prototype['finally'] = src_finally;
src_Promise.all = function (arr) {
  return new src_Promise(function (resolve, reject) {
    if (!isArray(arr)) {
      return reject(new TypeError('Promise.all accepts an array'));
    }
    var args = Array.prototype.slice.call(arr);
    if (args.length === 0) return resolve([]);
    var remaining = args.length;
    function res(i, val) {
      try {
        if (val && (_typeof(val) === 'object' || typeof val === 'function')) {
          var then = val.then;
          if (typeof then === 'function') {
            then.call(val, function (val) {
              res(i, val);
            }, reject);
            return;
          }
        }
        args[i] = val;
        if (--remaining === 0) {
          resolve(args);
        }
      } catch (ex) {
        reject(ex);
      }
    }
    for (var i = 0; i < args.length; i++) {
      res(i, args[i]);
    }
  });
};
src_Promise.any = src_any;
src_Promise.allSettled = src_allSettled;
src_Promise.resolve = function (value) {
  if (value && _typeof(value) === 'object' && value.constructor === src_Promise) {
    return value;
  }
  return new src_Promise(function (resolve) {
    resolve(value);
  });
};
src_Promise.reject = function (value) {
  return new src_Promise(function (resolve, reject) {
    reject(value);
  });
};
src_Promise.race = function (arr) {
  return new src_Promise(function (resolve, reject) {
    if (!isArray(arr)) {
      return reject(new TypeError('Promise.race accepts an array'));
    }
    for (var i = 0, len = arr.length; i < len; i++) {
      src_Promise.resolve(arr[i]).then(resolve, reject);
    }
  });
};

// Use polyfill for setImmediate for performance gains
src_Promise._immediateFn =
// @ts-ignore
typeof setImmediate === 'function' && function (fn) {
  // @ts-ignore
  setImmediate(fn);
} || function (fn) {
  setTimeoutFunc(fn, 0);
};
src_Promise._unhandledRejectionFn = function _unhandledRejectionFn(err) {
  if (typeof console !== 'undefined' && console) {
    console.warn('Possible Unhandled Promise Rejection:', err); // eslint-disable-line no-console
  }
};

/* harmony default export */ const src = (src_Promise);
;// CONCATENATED MODULE: ./src/utils/fetch.ts
// @ts-ignore avoid errors during TS build


if ((0,mixins.hasWin)()) {
    window.Promise = window.Promise || src;
}
/* harmony default export */ const utils_fetch = (typeof fetch == 'function'
    ? // @ts-ignore
        fetch.bind()
    : function (url, options) {
        // @ts-ignore avoid errors during TS build
        return new src(function (res, rej) {
            var req = new XMLHttpRequest();
            req.open(options.method || 'get', url);
            req.withCredentials = options.credentials == 'include';
            for (var k in options.headers || {}) {
                req.setRequestHeader(k, options.headers[k]);
            }
            req.onload = function (e) {
                return res({
                    status: req.status,
                    statusText: req.statusText,
                    text: function () { return src.resolve(req.responseText); },
                });
            };
            req.onerror = rej;
            // Actually, fetch doesn't support onProgress feature
            if (req.upload && options.onProgress) {
                req.upload.onprogress = options.onProgress;
            }
            // Include body only if present
            options.body ? req.send(options.body) : req.send();
        });
    });

;// CONCATENATED MODULE: ./src/storage_manager/model/RemoteStorage.ts
var RemoteStorage_assign = (undefined && undefined.__assign) || function () {
    RemoteStorage_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return RemoteStorage_assign.apply(this, arguments);
};
var RemoteStorage_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var RemoteStorage_generator = (undefined && undefined.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};


var RemoteStorage = /** @class */ (function () {
    function RemoteStorage() {
    }
    RemoteStorage.prototype.store = function (data, opts) {
        if (opts === void 0) { opts = {}; }
        return RemoteStorage_awaiter(this, void 0, void 0, function () {
            return RemoteStorage_generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.request(opts.urlStore, this.__props(opts, data), opts)];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    RemoteStorage.prototype.load = function (opts) {
        if (opts === void 0) { opts = {}; }
        return RemoteStorage_awaiter(this, void 0, void 0, function () {
            return RemoteStorage_generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.request(opts.urlLoad, this.__props(opts), opts)];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    RemoteStorage.prototype.request = function (url, props, opts) {
        if (props === void 0) { props = {}; }
        if (opts === void 0) { opts = {}; }
        return utils_fetch(url, props)
            .then(function (res) {
            var result = res.text();
            var isOk = ((res.status / 200) | 0) === 1;
            return isOk ? result : result.then(Promise.reject);
        })
            .then(function (text) {
            var parsable = text && (0,index_all.isString)(text);
            return opts.contentTypeJson && parsable ? JSON.parse(text) : text;
        });
    };
    RemoteStorage.prototype.__props = function (opts, data) {
        if (opts === void 0) { opts = {}; }
        var typeJson = opts.contentTypeJson;
        var headers = opts.headers || {};
        var fetchOpts = opts.fetchOptions || {};
        var reqHead = 'X-Requested-With';
        var typeHead = 'Content-Type';
        var body;
        if ((0,index_all.isUndefined)(headers[reqHead])) {
            headers[reqHead] = 'XMLHttpRequest';
        }
        if ((0,index_all.isUndefined)(headers[typeHead]) && typeJson) {
            headers[typeHead] = 'application/json; charset=utf-8';
        }
        if (data) {
            if (typeJson) {
                body = JSON.stringify(data);
            }
            else {
                body = new FormData();
                for (var key in data) {
                    body.append(key, data[key]);
                }
            }
        }
        var result = {
            method: body ? 'POST' : 'GET',
            credentials: opts.credentials,
            headers: headers,
            body: body,
        };
        return RemoteStorage_assign(RemoteStorage_assign({}, result), ((0,index_all.isFunction)(fetchOpts) ? fetchOpts(result) : fetchOpts));
    };
    return RemoteStorage;
}());
/* harmony default export */ const model_RemoteStorage = (RemoteStorage);

;// CONCATENATED MODULE: ./src/storage_manager/types.ts
/**{START_EVENTS}*/
var StorageEvents;
(function (StorageEvents) {
    /**
     * @event `storage:start` Storage request start.
     * @example
     * editor.on('storage:start', (type) => {
     *  console.log('Storage start');
     * });
     */
    StorageEvents["start"] = "storage:start";
    /**
     * @event `storage:start:store` Storage store request start.
     * The project JSON object to store is passed as an argument (which you can edit).
     * @example
     * editor.on('storage:start:store', (data) => {
     *  console.log('Storage start store');
     * });
     */
    StorageEvents["startStore"] = "storage:start:store";
    /**
     * @event `storage:start:load` Storage load request start.
     * @example
     * editor.on('storage:start:load', () => {
     *  console.log('Storage start load');
     * });
     */
    StorageEvents["startLoad"] = "storage:start:load";
    /**
     * @event `storage:load` Storage loaded the project.
     * The loaded project is passed as an argument.
     * @example
     * editor.on('storage:load', (data, res) => {
     *  console.log('Storage loaded the project');
     * });
     */
    StorageEvents["load"] = "storage:load";
    /**
     * @event `storage:store` Storage stored the project.
     * The stored project is passed as an argument.
     * @example
     * editor.on('storage:store', (data, res) => {
     *  console.log('Storage stored the project');
     * });
     */
    StorageEvents["store"] = "storage:store";
    /**
     * @event `storage:after` Storage request completed.
     * Triggered right after `storage:load`/`storage:store`.
     * @example
     * editor.on('storage:after', (type) => {
     *  console.log('Storage request completed');
     * });
     */
    StorageEvents["after"] = "storage:after";
    StorageEvents["afterStore"] = "storage:after:store";
    StorageEvents["afterLoad"] = "storage:after:load";
    /**
     * @event `storage:end` Storage request ended.
     * This event triggers also in case of errors.
     * @example
     * editor.on('storage:end', (type) => {
     *  console.log('Storage request ended');
     * });
     */
    StorageEvents["end"] = "storage:end";
    /**
     * @event `storage:end:store` Storage store request ended.
     * This event triggers also in case of errors.
     * @example
     * editor.on('storage:end:store', () => {
     *  console.log('Storage store request ended');
     * });
     */
    StorageEvents["endStore"] = "storage:end:store";
    /**
     * @event `storage:end:load` Storage load request ended.
     * This event triggers also in case of errors.
     * @example
     * editor.on('storage:end:load', () => {
     *  console.log('Storage load request ended');
     * });
     */
    StorageEvents["endLoad"] = "storage:end:load";
    /**
     * @event `storage:error` Error on storage request.
     * @example
     * editor.on('storage:error', (err, type) => {
     *  console.log('Storage error');
     * });
     */
    StorageEvents["error"] = "storage:error";
    /**
     * @event `storage:error:store` Error on store request.
     * @example
     * editor.on('storage:error:store', (err) => {
     *  console.log('Error on store');
     * });
     */
    StorageEvents["errorStore"] = "storage:error:store";
    /**
     * @event `storage:error:load` Error on load request.
     * @example
     * editor.on('storage:error:load', (err) => {
     *  console.log('Error on load');
     * });
     */
    StorageEvents["errorLoad"] = "storage:error:load";
})(StorageEvents || (StorageEvents = {}));
/**{END_EVENTS}*/
// need this to avoid the TS documentation generator to break
/* harmony default export */ const storage_manager_types = (StorageEvents);

;// CONCATENATED MODULE: ./src/storage_manager/index.ts
/**
 * You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](https://github.com/GrapesJS/grapesjs/blob/master/src/storage_manager/config/config.ts)
 * ```js
 * const editor = grapesjs.init({
 *  storageManager: {
 *    // options
 *  }
 * })
 * ```
 *
 * Once the editor is instantiated you can use its API and listen to its events. Before using these methods, you should get the module from the instance.
 *
 * ```js
 * // Listen to events
 * editor.on('storage:start', () => { ... });
 *
 * // Use the API
 * const storageManager = editor.Storage;
 * storageManager.add(...);
 * ```
 *
 * {REPLACE_EVENTS}
 *
 * ## Methods
 * * [getConfig](#getconfig)
 * * [isAutosave](#isautosave)
 * * [setAutosave](#setautosave)
 * * [getStepsBeforeSave](#getstepsbeforesave)
 * * [setStepsBeforeSave](#setstepsbeforesave)
 * * [getStorages](#getstorages)
 * * [getCurrent](#getcurrent)
 * * [getCurrentStorage](#getcurrentstorage)
 * * [setCurrent](#setcurrent)
 * * [getStorageOptions](#getstorageoptions)
 * * [add](#add)
 * * [get](#get)
 * * [store](#store)
 * * [load](#load)
 *
 * @module Storage
 */
var storage_manager_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var storage_manager_assign = (undefined && undefined.__assign) || function () {
    storage_manager_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return storage_manager_assign.apply(this, arguments);
};
var storage_manager_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var storage_manager_generator = (undefined && undefined.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};






var STORAGE_LOCAL = 'local';
var STORAGE_REMOTE = 'remote';
var StorageManager = /** @class */ (function (_super) {
    storage_manager_extends(StorageManager, _super);
    function StorageManager(em) {
        var _this = _super.call(this, em, 'StorageManager', storage_manager_config_config) || this;
        _this.storages = {};
        _this.events = storage_manager_types;
        var config = _this.config;
        if (config._disable)
            config.type = undefined;
        _this.storages = {};
        _this.add(STORAGE_LOCAL, new model_LocalStorage());
        _this.add(STORAGE_REMOTE, new model_RemoteStorage());
        _this.setCurrent(config.type);
        return _this;
    }
    /**
     * Get configuration object
     * @name getConfig
     * @function
     * @return {Object}
     */
    /**
     * Check if autosave is enabled.
     * @returns {Boolean}
     * */
    StorageManager.prototype.isAutosave = function () {
        return !!this.config.autosave;
    };
    /**
     * Set autosave value.
     * @param  {Boolean} value
     * */
    StorageManager.prototype.setAutosave = function (value) {
        this.config.autosave = !!value;
        return this;
    };
    /**
     * Returns number of steps required before trigger autosave.
     * @returns {Number}
     * */
    StorageManager.prototype.getStepsBeforeSave = function () {
        return this.config.stepsBeforeSave;
    };
    /**
     * Set steps required before trigger autosave.
     * @param {Number} value
     * */
    StorageManager.prototype.setStepsBeforeSave = function (value) {
        this.config.stepsBeforeSave = value;
        return this;
    };
    /**
     * Add new storage.
     * @param {String} type Storage type
     * @param {Object} storage Storage definition
     * @param {Function} storage.load Load method
     * @param  {Function} storage.store Store method
     * @example
     * storageManager.add('local2', {
     *   async load(storageOptions) {
     *     // ...
     *   },
     *   async store(data, storageOptions) {
     *     // ...
     *   },
     * });
     * */
    StorageManager.prototype.add = function (type, storage) {
        this.storages[type] = storage;
        return this;
    };
    /**
     * Return storage by type.
     * @param {String} type Storage type
     * @returns {Object|null}
     * */
    StorageManager.prototype.get = function (type) {
        return this.storages[type];
    };
    /**
     * Get all storages.
     * @returns {Object}
     * */
    StorageManager.prototype.getStorages = function () {
        return this.storages;
    };
    /**
     * Get current storage type.
     * @returns {String}
     * */
    StorageManager.prototype.getCurrent = function () {
        return this.config.currentStorage;
    };
    /**
     * Set current storage type.
     * @param {String} type Storage type
     * */
    StorageManager.prototype.setCurrent = function (type) {
        this.getConfig().currentStorage = type;
        return this;
    };
    StorageManager.prototype.getCurrentStorage = function () {
        return this.get(this.getCurrent());
    };
    /**
     * Get storage options by type.
     * @param {String} type Storage type
     * @returns {Object}
     * */
    StorageManager.prototype.getStorageOptions = function (type) {
        return this.getCurrentOptions(type);
    };
    /**
     * Store data in the current storage.
     * @param {Object} data Project data.
     * @param {Object} [options] Storage options.
     * @returns {Object} Stored data.
     * @example
     * const data = editor.getProjectData();
     * await storageManager.store(data);
     * */
    StorageManager.prototype.store = function (data, options) {
        if (options === void 0) { options = {}; }
        return storage_manager_awaiter(this, void 0, void 0, function () {
            var st, opts, recovery, recoveryOpts, _a, error_1;
            return storage_manager_generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        st = this.getCurrentStorage();
                        opts = storage_manager_assign(storage_manager_assign({}, this.getCurrentOptions()), options);
                        recovery = this.getRecoveryStorage();
                        recoveryOpts = this.getCurrentOptions(STORAGE_LOCAL);
                        _b.label = 1;
                    case 1:
                        _b.trys.push([1, 5, , 9]);
                        return [4 /*yield*/, this.__exec(st, opts, data)];
                    case 2:
                        _b.sent();
                        _a = recovery;
                        if (!_a) return [3 /*break*/, 4];
                        return [4 /*yield*/, this.__exec(recovery, recoveryOpts, {})];
                    case 3:
                        _a = (_b.sent());
                        _b.label = 4;
                    case 4:
                        _a;
                        return [3 /*break*/, 9];
                    case 5:
                        error_1 = _b.sent();
                        if (!recovery) return [3 /*break*/, 7];
                        return [4 /*yield*/, this.__exec(recovery, recoveryOpts, data)];
                    case 6:
                        _b.sent();
                        return [3 /*break*/, 8];
                    case 7: throw error_1;
                    case 8: return [3 /*break*/, 9];
                    case 9: return [2 /*return*/, data];
                }
            });
        });
    };
    /**
     * Load resource from the current storage by keys
     * @param {Object} [options] Storage options.
     * @returns {Object} Loaded data.
     * @example
     * const data = await storageManager.load();
     * editor.loadProjectData(data);
     * */
    StorageManager.prototype.load = function (options) {
        if (options === void 0) { options = {}; }
        return storage_manager_awaiter(this, void 0, void 0, function () {
            var st, opts, recoveryStorage, result, recoveryData, error_2;
            return storage_manager_generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        st = this.getCurrentStorage();
                        opts = storage_manager_assign(storage_manager_assign({}, this.getCurrentOptions()), options);
                        recoveryStorage = this.getRecoveryStorage();
                        if (!recoveryStorage) return [3 /*break*/, 5];
                        return [4 /*yield*/, this.__exec(recoveryStorage, this.getCurrentOptions(STORAGE_LOCAL))];
                    case 1:
                        recoveryData = _a.sent();
                        if (!!(0,index_all.isEmpty)(recoveryData)) return [3 /*break*/, 5];
                        _a.label = 2;
                    case 2:
                        _a.trys.push([2, 4, , 5]);
                        return [4 /*yield*/, this.__askRecovery()];
                    case 3:
                        _a.sent();
                        result = recoveryData;
                        return [3 /*break*/, 5];
                    case 4:
                        error_2 = _a.sent();
                        return [3 /*break*/, 5];
                    case 5:
                        if (!!result) return [3 /*break*/, 7];
                        return [4 /*yield*/, this.__exec(st, opts)];
                    case 6:
                        result = _a.sent();
                        _a.label = 7;
                    case 7: return [2 /*return*/, result || {}];
                }
            });
        });
    };
    StorageManager.prototype.__askRecovery = function () {
        var em = this.em;
        var recovery = this.getRecovery();
        return new Promise(function (res, rej) {
            if ((0,index_all.isFunction)(recovery)) {
                recovery(res, rej, em === null || em === void 0 ? void 0 : em.getEditor());
            }
            else {
                confirm(em === null || em === void 0 ? void 0 : em.t('storageManager.recover')) ? res(null) : rej();
            }
        });
    };
    StorageManager.prototype.getRecovery = function () {
        return this.config.recovery;
    };
    StorageManager.prototype.getRecoveryStorage = function () {
        var recovery = this.getRecovery();
        return recovery && this.getCurrent() === STORAGE_REMOTE && this.get(STORAGE_LOCAL);
    };
    StorageManager.prototype.__exec = function (storage, opts, data) {
        var _a;
        return storage_manager_awaiter(this, void 0, void 0, function () {
            var ev, _b, onStore, onLoad, result, editor, response, toStore, _c, _d, _e, _f, error_3;
            return storage_manager_generator(this, function (_g) {
                switch (_g.label) {
                    case 0:
                        ev = data ? 'store' : 'load';
                        _b = this.getConfig(), onStore = _b.onStore, onLoad = _b.onLoad;
                        this.onStart(ev, data);
                        if (!storage) {
                            return [2 /*return*/, data || {}];
                        }
                        _g.label = 1;
                    case 1:
                        _g.trys.push([1, 14, , 15]);
                        editor = (_a = this.em) === null || _a === void 0 ? void 0 : _a.getEditor();
                        response = void 0;
                        if (!data) return [3 /*break*/, 7];
                        _c = onStore;
                        if (!_c) return [3 /*break*/, 3];
                        return [4 /*yield*/, onStore(data, editor)];
                    case 2:
                        _c = (_g.sent());
                        _g.label = 3;
                    case 3:
                        toStore = (_c) || data;
                        _d = opts.onStore;
                        if (!_d) return [3 /*break*/, 5];
                        return [4 /*yield*/, opts.onStore(toStore, editor)];
                    case 4:
                        _d = (_g.sent());
                        _g.label = 5;
                    case 5:
                        toStore = (_d) || toStore;
                        return [4 /*yield*/, storage.store(toStore, opts)];
                    case 6:
                        response = _g.sent();
                        result = data;
                        return [3 /*break*/, 13];
                    case 7: return [4 /*yield*/, storage.load(opts)];
                    case 8:
                        response = _g.sent();
                        result = this.__clearKeys(response);
                        _e = opts.onLoad;
                        if (!_e) return [3 /*break*/, 10];
                        return [4 /*yield*/, opts.onLoad(result, editor)];
                    case 9:
                        _e = (_g.sent());
                        _g.label = 10;
                    case 10:
                        result = (_e) || result;
                        _f = onLoad;
                        if (!_f) return [3 /*break*/, 12];
                        return [4 /*yield*/, onLoad(result, editor)];
                    case 11:
                        _f = (_g.sent());
                        _g.label = 12;
                    case 12:
                        result = (_f) || result;
                        _g.label = 13;
                    case 13:
                        this.onAfter(ev, result, response);
                        this.onEnd(ev, result, response);
                        return [3 /*break*/, 15];
                    case 14:
                        error_3 = _g.sent();
                        this.onError(ev, error_3);
                        throw error_3;
                    case 15: return [2 /*return*/, result];
                }
            });
        });
    };
    StorageManager.prototype.__clearKeys = function (data) {
        if (data === void 0) { data = {}; }
        var config = this.getConfig();
        var reg = new RegExp("^".concat(config.id));
        var result = {};
        for (var itemKey in data) {
            var itemKeyR = itemKey.replace(reg, '');
            result[itemKeyR] = data[itemKey];
        }
        return result;
    };
    StorageManager.prototype.getCurrentOptions = function (type) {
        var config = this.getConfig();
        var current = type || this.getCurrent();
        return config.options[current] || {};
    };
    /**
     * On start callback
     * @private
     */
    StorageManager.prototype.onStart = function (type, data) {
        var em = this.em;
        if (em) {
            var ev = type === 'load' ? storage_manager_types.startLoad : storage_manager_types.startStore;
            em.trigger(storage_manager_types.start, type, data);
            em.trigger(ev, data);
        }
    };
    /**
     * On after callback (before passing data to the callback)
     * @private
     */
    StorageManager.prototype.onAfter = function (type, data, response) {
        var em = this.em;
        if (em) {
            var evAfter = type === 'load' ? storage_manager_types.afterLoad : storage_manager_types.afterStore;
            em.trigger(storage_manager_types.after);
            em.trigger(evAfter, data, response);
            var ev = type === 'load' ? storage_manager_types.load : storage_manager_types.store;
            em.trigger(ev, data, response);
        }
    };
    /**
     * On end callback
     * @private
     */
    StorageManager.prototype.onEnd = function (type, data, response) {
        var em = this.em;
        if (em) {
            var ev = type === 'load' ? storage_manager_types.endLoad : storage_manager_types.endStore;
            em.trigger(storage_manager_types.end, type, data, response);
            em.trigger(ev, data, response);
        }
    };
    /**
     * On error callback
     * @private
     */
    StorageManager.prototype.onError = function (type, error) {
        var em = this.em;
        if (em) {
            var ev = type === 'load' ? storage_manager_types.errorLoad : storage_manager_types.errorStore;
            em.trigger(storage_manager_types.error, error, type);
            em.trigger(ev, error);
            this.onEnd(type, error);
        }
    };
    /**
     * Check if autoload is possible
     * @return {Boolean}
     * @private
     * */
    StorageManager.prototype.canAutoload = function () {
        var storage = this.getCurrentStorage();
        return !!storage && !!this.config.autoload;
    };
    StorageManager.prototype.destroy = function () {
        this.storages = {};
    };
    return StorageManager;
}(abstract_Module));
/* harmony default export */ const storage_manager = (StorageManager);

;// CONCATENATED MODULE: ./src/trait_manager/config/config.ts
var trait_manager_config_config_config = {
    stylePrefix: 'trt-',
    appendTo: '',
    optionsTarget: [{ value: false }, { value: '_blank' }],
    custom: false,
};
/* harmony default export */ const trait_manager_config_config = (trait_manager_config_config_config);

;// CONCATENATED MODULE: ./src/trait_manager/view/TraitView.ts
var TraitView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var TraitView_assign = (undefined && undefined.__assign) || function () {
    TraitView_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return TraitView_assign.apply(this, arguments);
};



var TraitView = /** @class */ (function (_super) {
    TraitView_extends(TraitView, _super);
    function TraitView(o) {
        if (o === void 0) { o = {}; }
        var _this = _super.call(this, o) || this;
        _this.events = {};
        _this.appendInput = true;
        var _a = o.config, config = _a === void 0 ? {} : _a;
        var _b = _this, model = _b.model, eventCapture = _b.eventCapture;
        var target = model.target;
        var type = model.attributes.type;
        _this.config = config;
        _this.em = config.em;
        _this.pfx = config.stylePrefix || '';
        _this.ppfx = config.pStylePrefix || '';
        _this.target = target;
        _this.className = _this.pfx + 'trait';
        _this.clsField = "".concat(_this.ppfx, "field ").concat(_this.ppfx, "field-").concat(type);
        var evToListen = [
            ['change:value', _this.onValueChange],
            ['remove', _this.removeView],
        ];
        evToListen.forEach(function (_a) {
            var event = _a[0], clb = _a[1];
            model.off(event, clb);
            _this.listenTo(model, event, clb);
        });
        model.view = _this;
        _this.listenTo(model, 'change:label', _this.render);
        _this.listenTo(model, 'change:placeholder', _this.rerender);
        _this.events = {};
        eventCapture.forEach(function (event) { return (_this.events[event] = 'onChange'); });
        _this.delegateEvents();
        _this.init();
        return _this;
    }
    /** @ts-ignore */
    TraitView.prototype.attributes = function () {
        return this.model.get('attributes') || {};
    };
    TraitView.prototype.templateLabel = function (cmp) {
        var ppfx = this.ppfx;
        var label = this.getLabel();
        return "<div class=\"".concat(ppfx, "label\" title=\"").concat(label, "\">").concat(label, "</div>");
    };
    TraitView.prototype.templateInput = function (data) {
        var clsField = this.clsField;
        return "<div class=\"".concat(clsField, "\" data-input></div>");
    };
    TraitView.prototype.getClbOpts = function () {
        return {
            component: this.target,
            trait: this.model,
            elInput: this.getInputElem(),
        };
    };
    TraitView.prototype.removeView = function () {
        this.remove();
        this.removed();
    };
    TraitView.prototype.init = function () { };
    TraitView.prototype.removed = function () { };
    TraitView.prototype.onRender = function (props) { };
    TraitView.prototype.onUpdate = function (props) { };
    TraitView.prototype.onEvent = function (props) { };
    /**
     * Fires when the input is changed
     * @private
     */
    TraitView.prototype.onChange = function (event) {
        var el = this.getInputElem();
        if (el && !(0,index_all.isUndefined)(el.value)) {
            this.model.set('value', el.value);
        }
        this.onEvent(TraitView_assign(TraitView_assign({}, this.getClbOpts()), { event: event }));
    };
    TraitView.prototype.getValueForTarget = function () {
        return this.model.get('value');
    };
    TraitView.prototype.setInputValue = function (value) {
        var el = this.getInputElem();
        el && (el.value = value);
    };
    /**
     * On change callback
     * @private
     */
    TraitView.prototype.onValueChange = function (model, value, opts) {
        if (opts === void 0) { opts = {}; }
        if (opts.fromTarget) {
            this.setInputValue(model.get('value'));
            this.postUpdate();
        }
        else {
            var val = this.getValueForTarget();
            model.setTargetValue(val, opts);
        }
    };
    /**
     * Render label
     * @private
     */
    TraitView.prototype.renderLabel = function () {
        var _a = this, $el = _a.$el, target = _a.target;
        var label = this.getLabel();
        var tpl = this.templateLabel(target);
        if (this.createLabel) {
            tpl =
                this.createLabel({
                    label: label,
                    component: target,
                    trait: this,
                }) || '';
        }
        $el.find('[data-label]').append(tpl);
    };
    /**
     * Returns label for the input
     * @return {string}
     * @private
     */
    TraitView.prototype.getLabel = function () {
        var em = this.em;
        var _a = this.model.attributes, label = _a.label, name = _a.name;
        return em.t("traitManager.traits.labels.".concat(name)) || (0,mixins.capitalize)(label || name).replace(/-/g, ' ');
    };
    /**
     * Returns current target component
     */
    TraitView.prototype.getComponent = function () {
        return this.target;
    };
    /**
     * Returns input element
     * @return {HTMLElement}
     * @private
     */
    TraitView.prototype.getInputEl = function () {
        if (!this.$input) {
            var _a = this, em = _a.em, model = _a.model;
            var md = model;
            var name_1 = model.attributes.name;
            var placeholder = md.get('placeholder') || md.get('default') || '';
            var type = md.get('type') || 'text';
            var min = md.get('min');
            var max = md.get('max');
            var value = this.getModelValue();
            var input = (0,cash_dom["default"])("<input type=\"".concat(type, "\">"));
            var i18nAttr = em.t("traitManager.traits.attributes.".concat(name_1)) || {};
            input.attr(TraitView_assign({ placeholder: placeholder }, i18nAttr));
            if (!(0,index_all.isUndefined)(value)) {
                md.set({ value: value }, { silent: true });
                input.prop('value', value);
            }
            if (min) {
                input.prop('min', min);
            }
            if (max) {
                input.prop('max', max);
            }
            this.$input = input;
        }
        return this.$input.get(0);
    };
    TraitView.prototype.getInputElem = function () {
        var _a = this, input = _a.input, $input = _a.$input;
        return input || ($input && $input.get && $input.get(0)) || this.getElInput();
    };
    TraitView.prototype.getModelValue = function () {
        return this.model.getValue();
    };
    TraitView.prototype.getElInput = function () {
        return this.elInput;
    };
    /**
     * Renders input
     * @private
     * */
    TraitView.prototype.renderField = function () {
        var _a = this, $el = _a.$el, appendInput = _a.appendInput, model = _a.model;
        var inputs = $el.find('[data-input]');
        var el = inputs[inputs.length - 1];
        var tpl = model.el;
        if (!tpl) {
            tpl = this.createInput ? this.createInput(this.getClbOpts()) : this.getInputEl();
        }
        if ((0,index_all.isString)(tpl)) {
            el.innerHTML = tpl;
            this.elInput = el.firstChild;
        }
        else {
            appendInput ? el.appendChild(tpl) : el.insertBefore(tpl, el.firstChild);
            this.elInput = tpl;
        }
        model.el = this.elInput;
    };
    TraitView.prototype.hasLabel = function () {
        var label = this.model.attributes.label;
        return !this.noLabel && label !== false;
    };
    TraitView.prototype.rerender = function () {
        delete this.model.el;
        this.render();
    };
    TraitView.prototype.postUpdate = function () {
        this.onUpdate(this.getClbOpts());
    };
    TraitView.prototype.render = function () {
        var _a = this, $el = _a.$el, pfx = _a.pfx, ppfx = _a.ppfx, model = _a.model;
        var _b = model.attributes, type = _b.type, id = _b.id;
        var hasLabel = this.hasLabel && this.hasLabel();
        var cls = "".concat(pfx, "trait");
        delete this.$input;
        var tmpl = "<div class=\"".concat(cls, " ").concat(cls, "--").concat(type, "\">\n      ").concat(hasLabel ? "<div class=\"".concat(ppfx, "label-wrp\" data-label></div>") : '', "\n      <div class=\"").concat(ppfx, "field-wrp ").concat(ppfx, "field-wrp--").concat(type, "\" data-input>\n        ").concat(this.templateInput
            ? (0,index_all.isFunction)(this.templateInput)
                ? this.templateInput(this.getClbOpts())
                : this.templateInput
            : '', "\n      </div>\n    </div>");
        $el.empty().append(tmpl);
        hasLabel && this.renderLabel();
        this.renderField();
        this.el.className = "".concat(cls, "__wrp ").concat(cls, "__wrp-").concat(id);
        this.postUpdate();
        this.onRender(this.getClbOpts());
        return this;
    };
    return TraitView;
}(common/* View */.G7));
/* harmony default export */ const view_TraitView = (TraitView);
TraitView.prototype.eventCapture = ['change'];

;// CONCATENATED MODULE: ./src/trait_manager/view/TraitButtonView.ts
var TraitButtonView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();

var TraitButtonView = /** @class */ (function (_super) {
    TraitButtonView_extends(TraitButtonView, _super);
    function TraitButtonView() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    TraitButtonView.prototype.templateInput = function () {
        return '';
    };
    TraitButtonView.prototype.onChange = function () {
        this.handleClick();
    };
    TraitButtonView.prototype.handleClick = function () {
        this.model.runCommand();
    };
    TraitButtonView.prototype.renderLabel = function () {
        if (this.model.get('label')) {
            view_TraitView.prototype.renderLabel.apply(this);
        }
    };
    TraitButtonView.prototype.getInputEl = function () {
        var _a = this, model = _a.model, ppfx = _a.ppfx;
        var _b = model.props(), labelButton = _b.labelButton, text = _b.text, full = _b.full;
        var label = labelButton || text;
        var className = "".concat(ppfx, "btn");
        var input = "<button type=\"button\" class=\"".concat(className, "-prim").concat(full ? " ".concat(className, "--full") : '', "\">").concat(label, "</button>");
        return input;
    };
    return TraitButtonView;
}(view_TraitView));
/* harmony default export */ const view_TraitButtonView = (TraitButtonView);
// Fix #4388
TraitButtonView.prototype.eventCapture = ['click button'];

;// CONCATENATED MODULE: ./src/trait_manager/view/TraitCheckboxView.ts
var TraitCheckboxView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();


var TraitCheckboxView = /** @class */ (function (_super) {
    TraitCheckboxView_extends(TraitCheckboxView, _super);
    function TraitCheckboxView() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.appendInput = false;
        return _this;
    }
    TraitCheckboxView.prototype.templateInput = function () {
        var _a = this, ppfx = _a.ppfx, clsField = _a.clsField;
        return "<label class=\"".concat(clsField, "\" data-input>\n    <i class=\"").concat(ppfx, "chk-icon\"></i>\n  </label>");
    };
    /**
     * Fires when the input is changed
     * @private
     */
    TraitCheckboxView.prototype.onChange = function () {
        this.model.set('value', this.getInputElem().checked);
    };
    TraitCheckboxView.prototype.setInputValue = function (value) {
        var el = this.getInputElem();
        el && (el.checked = !!value);
    };
    /**
     * Returns input element
     * @return {HTMLElement}
     * @private
     */
    TraitCheckboxView.prototype.getInputEl = function () {
        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            args[_i] = arguments[_i];
        }
        var toInit = !this.$input;
        var el = view_TraitView.prototype.getInputEl.apply(this, args);
        if (toInit) {
            var checked = void 0, targetValue = void 0;
            var _a = this, model = _a.model, target = _a.target;
            var valueFalse = model.attributes.valueFalse;
            var name_1 = model.getName();
            if (model.changeProp) {
                checked = target.get(name_1);
                targetValue = checked;
            }
            else {
                targetValue = target.get('attributes')[name_1];
                checked = targetValue || targetValue === '' ? !0 : !1;
            }
            if (!(0,index_all.isUndefined)(valueFalse) && targetValue === valueFalse) {
                checked = !1;
            }
            el.checked = checked;
        }
        return el;
    };
    return TraitCheckboxView;
}(view_TraitView));
/* harmony default export */ const view_TraitCheckboxView = (TraitCheckboxView);

;// CONCATENATED MODULE: ./src/utils/ColorPicker.ts
// @ts-nocheck
// Without jquery I have to update few stuff
//
// Spectrum Colorpicker v1.8.0
// https://github.com/bgrins/spectrum
// Author: Brian Grinstead
// License: MIT

/* harmony default export */ function ColorPicker($, undefined) {
    'use strict';
    if (!(0,mixins.hasWin)())
        return;
    var defaultOpts = {
        // Callbacks
        beforeShow: noop,
        move: noop,
        change: noop,
        show: noop,
        hide: noop,
        // Options
        color: false,
        flat: false,
        showInput: false,
        allowEmpty: false,
        showButtons: true,
        clickoutFiresChange: true,
        showInitial: false,
        showPalette: false,
        showPaletteOnly: false,
        hideAfterPaletteSelect: false,
        togglePaletteOnly: false,
        showSelectionPalette: true,
        localStorageKey: false,
        appendTo: 'body',
        maxSelectionSize: 7,
        cancelText: 'cancel',
        chooseText: 'choose',
        togglePaletteMoreText: 'more',
        togglePaletteLessText: 'less',
        clearText: 'Clear Color Selection',
        noColorSelectedText: 'No Color Selected',
        preferredFormat: false,
        className: '',
        containerClassName: '',
        replacerClassName: '',
        showAlpha: false,
        theme: 'sp-light',
        palette: [['#ffffff', '#000000', '#ff0000', '#ff8000', '#ffff00', '#008000', '#0000ff', '#4b0082', '#9400d3']],
        selectionPalette: [],
        disabled: false,
        offset: null,
    }, spectrums = [], IE = !!/msie/i.exec(window.navigator.userAgent), rgbaSupport = (function () {
        function contains(str, substr) {
            return !!~('' + str).indexOf(substr);
        }
        var elem = document.createElement('div');
        var style = elem.style;
        style.cssText = 'background-color:rgba(0,0,0,.5)';
        return contains(style.backgroundColor, 'rgba') || contains(style.backgroundColor, 'hsla');
    })(), replaceInput = [
        "<div class='sp-replacer'>",
        "<div class='sp-preview'><div class='sp-preview-inner'></div></div>",
        "<div class='sp-dd'>&#9660;</div>",
        '</div>',
    ].join(''), markup = (function () {
        // IE does not support gradients with multiple stops, so we need to simulate
        //  that for the rainbow slider with 8 divs that each have a single gradient
        var gradientFix = '';
        if (IE) {
            for (var i = 1; i <= 6; i++) {
                gradientFix += "<div class='sp-" + i + "'></div>";
            }
        }
        return [
            "<div class='sp-container sp-hidden'>",
            "<div class='sp-palette-container'>",
            "<div class='sp-palette sp-thumb sp-cf'></div>",
            "<div class='sp-palette-button-container sp-cf'>",
            "<button type='button' class='sp-palette-toggle'></button>",
            '</div>',
            '</div>',
            "<div class='sp-picker-container'>",
            "<div class='sp-top sp-cf'>",
            "<div class='sp-fill'></div>",
            "<div class='sp-top-inner'>",
            "<div class='sp-color'>",
            "<div class='sp-sat'>",
            "<div class='sp-val'>",
            "<div class='sp-dragger'></div>",
            '</div>',
            '</div>',
            '</div>',
            "<div class='sp-clear sp-clear-display'>",
            '</div>',
            "<div class='sp-hue'>",
            "<div class='sp-slider'></div>",
            gradientFix,
            '</div>',
            '</div>',
            "<div class='sp-alpha'><div class='sp-alpha-inner'><div class='sp-alpha-handle'></div></div></div>",
            '</div>',
            "<div class='sp-input-container sp-cf'>",
            "<input class='sp-input' type='text' spellcheck='false'  />",
            '</div>',
            "<div class='sp-initial sp-thumb sp-cf'></div>",
            "<div class='sp-button-container sp-cf'>",
            "<a class='sp-cancel' href='#'></a>",
            "<button type='button' class='sp-choose'></button>",
            '</div>',
            '</div>',
            '</div>',
        ].join('');
    })();
    function paletteTemplate(p, color, className, opts) {
        var html = [];
        for (var i = 0; i < p.length; i++) {
            var current = p[i];
            if (current) {
                var tiny = tinycolor(current);
                var c = tiny.toHsl().l < 0.5 ? 'sp-thumb-el sp-thumb-dark' : 'sp-thumb-el sp-thumb-light';
                c += tinycolor.equals(color, current) ? ' sp-thumb-active' : '';
                var formattedString = tiny.toString(opts.preferredFormat || 'rgb');
                var swatchStyle = rgbaSupport ? 'background-color:' + tiny.toRgbString() : 'filter:' + tiny.toFilter();
                html.push('<span title="' +
                    formattedString +
                    '" data-color="' +
                    tiny.toRgbString() +
                    '" class="' +
                    c +
                    '"><span class="sp-thumb-inner" style="' +
                    swatchStyle +
                    ';"></span></span>');
            }
            else {
                var cls = 'sp-clear-display';
                html.push($('<div />')
                    .append($('<span data-color="" style="background-color:transparent;" class="' + cls + '"></span>').attr('title', opts.noColorSelectedText))
                    .html());
            }
        }
        return "<div class='sp-cf " + className + "'>" + html.join('') + '</div>';
    }
    function hideAll() {
        for (var i = 0; i < spectrums.length; i++) {
            if (spectrums[i]) {
                spectrums[i].hide();
            }
        }
    }
    function instanceOptions(o, callbackContext) {
        var opts = $.extend({}, defaultOpts, o);
        opts.callbacks = {
            move: bind(opts.move, callbackContext),
            change: bind(opts.change, callbackContext),
            show: bind(opts.show, callbackContext),
            hide: bind(opts.hide, callbackContext),
            beforeShow: bind(opts.beforeShow, callbackContext),
        };
        return opts;
    }
    function spectrum(element, o) {
        var opts = instanceOptions(o, element), flat = opts.flat, showSelectionPalette = opts.showSelectionPalette, localStorageKey = opts.localStorageKey, theme = opts.theme, callbacks = opts.callbacks, resize = throttle(reflow, 10), visible = false, isDragging = false, isDefault = true, dragWidth = 0, dragHeight = 0, dragHelperHeight = 0, slideHeight = 0, slideWidth = 0, alphaWidth = 0, alphaSlideHelperWidth = 0, slideHelperHeight = 0, currentHue = 0, currentSaturation = 0, currentValue = 0, currentAlpha = 1, palette = [], paletteArray = [], paletteLookup = {}, selectionPalette = opts.selectionPalette.slice(0), maxSelectionSize = opts.maxSelectionSize, draggingClass = 'sp-dragging', shiftMovementDirection = null;
        var doc = element.ownerDocument, body = doc.body, boundElement = $(element), disabled = false, container = $(markup, doc).addClass(theme), pickerContainer = container.find('.sp-picker-container'), dragger = container.find('.sp-color'), dragHelper = container.find('.sp-dragger'), slider = container.find('.sp-hue'), slideHelper = container.find('.sp-slider'), alphaSliderInner = container.find('.sp-alpha-inner'), alphaSlider = container.find('.sp-alpha'), alphaSlideHelper = container.find('.sp-alpha-handle'), textInput = container.find('.sp-input'), paletteContainer = container.find('.sp-palette'), initialColorContainer = container.find('.sp-initial'), cancelButton = container.find('.sp-cancel'), clearButton = container.find('.sp-clear'), chooseButton = container.find('.sp-choose'), toggleButton = container.find('.sp-palette-toggle'), isInput = boundElement.is('input'), isInputTypeColor = isInput && boundElement.attr('type') === 'color' && inputTypeColorSupport(), shouldReplace = isInput && !flat, replacer = shouldReplace
            ? $(replaceInput).addClass(theme).addClass(opts.className).addClass(opts.replacerClassName)
            : $([]), offsetElement = shouldReplace ? replacer : boundElement, previewElement = replacer.find('.sp-preview-inner'), initialColor = opts.color || (isInput && boundElement.val()), colorOnShow = false, currentPreferredFormat = opts.preferredFormat, clickoutFiresChange = !opts.showButtons || opts.clickoutFiresChange, isEmpty = !initialColor, allowEmpty = opts.allowEmpty && !isInputTypeColor;
        function applyOptions() {
            if (opts.showPaletteOnly) {
                opts.showPalette = true;
            }
            toggleButton.text(opts.showPaletteOnly ? opts.togglePaletteMoreText : opts.togglePaletteLessText);
            if (opts.palette) {
                palette = opts.palette.slice(0);
                paletteArray = $.isArray(palette[0]) ? palette : [palette];
                paletteLookup = {};
                for (var i = 0; i < paletteArray.length; i++) {
                    for (var j = 0; j < paletteArray[i].length; j++) {
                        var rgb = tinycolor(paletteArray[i][j]).toRgbString();
                        paletteLookup[rgb] = true;
                    }
                }
            }
            container.toggleClass('sp-flat', flat);
            container.toggleClass('sp-input-disabled', !opts.showInput);
            container.toggleClass('sp-alpha-enabled', opts.showAlpha);
            container.toggleClass('sp-clear-enabled', allowEmpty);
            container.toggleClass('sp-buttons-disabled', !opts.showButtons);
            container.toggleClass('sp-palette-buttons-disabled', !opts.togglePaletteOnly);
            container.toggleClass('sp-palette-disabled', !opts.showPalette);
            container.toggleClass('sp-palette-only', opts.showPaletteOnly);
            container.toggleClass('sp-initial-disabled', !opts.showInitial);
            container.addClass(opts.className).addClass(opts.containerClassName);
            reflow();
        }
        function initialize() {
            if (IE) {
                container.find('*:not(input)').attr('unselectable', 'on');
            }
            applyOptions();
            if (shouldReplace) {
                boundElement.after(replacer).hide();
            }
            if (!allowEmpty) {
                clearButton.hide();
            }
            if (flat) {
                boundElement.after(container).hide();
            }
            else {
                var appendTo = opts.appendTo === 'parent' ? boundElement.parent() : $(opts.appendTo);
                if (appendTo.length !== 1) {
                    appendTo = $('body');
                }
                appendTo.append(container);
            }
            updateSelectionPaletteFromStorage();
            offsetElement.bind('click.spectrum touchstart.spectrum', function (e) {
                if (!disabled) {
                    toggle();
                }
                e.stopPropagation();
                if (!$(e.target).is('input')) {
                    e.preventDefault();
                }
            });
            if (boundElement.is(':disabled') || opts.disabled === true) {
                disable();
            }
            // Prevent clicks from bubbling up to document.  This would cause it to be hidden.
            container.click(stopPropagation);
            // Handle user typed input
            textInput.change(setFromTextInput);
            textInput.bind('paste', function () {
                setTimeout(setFromTextInput, 1);
            });
            textInput.keydown(function (e) {
                if (e.keyCode == 13) {
                    setFromTextInput();
                }
            });
            cancelButton.text(opts.cancelText);
            cancelButton.bind('click.spectrum', function (e) {
                e.stopPropagation();
                e.preventDefault();
                revert();
                hide();
            });
            clearButton.attr('title', opts.clearText);
            clearButton.bind('click.spectrum', function (e) {
                e.stopPropagation();
                e.preventDefault();
                isEmpty = true;
                move();
                if (flat) {
                    //for the flat style, this is a change event
                    updateOriginalInput(true);
                }
            });
            chooseButton.text(opts.chooseText);
            chooseButton.bind('click.spectrum', function (e) {
                e.stopPropagation();
                e.preventDefault();
                if (IE && textInput.is(':focus')) {
                    textInput.trigger('change');
                }
                if (isValid()) {
                    updateOriginalInput(true);
                    hide();
                }
            });
            toggleButton.text(opts.showPaletteOnly ? opts.togglePaletteMoreText : opts.togglePaletteLessText);
            toggleButton.bind('click.spectrum', function (e) {
                e.stopPropagation();
                e.preventDefault();
                opts.showPaletteOnly = !opts.showPaletteOnly;
                // To make sure the Picker area is drawn on the right, next to the
                // Palette area (and not below the palette), first move the Palette
                // to the left to make space for the picker, plus 5px extra.
                // The 'applyOptions' function puts the whole container back into place
                // and takes care of the button-text and the sp-palette-only CSS class.
                if (!opts.showPaletteOnly && !flat) {
                    container.css('left', '-=' + (pickerContainer.outerWidth(true) + 5));
                }
                applyOptions();
            });
            draggable(alphaSlider, function (dragX, dragY, e) {
                currentAlpha = dragX / alphaWidth;
                isEmpty = false;
                if (e.shiftKey) {
                    currentAlpha = Math.round(currentAlpha * 10) / 10;
                }
                move();
            }, dragStart, dragStop);
            draggable(slider, function (dragX, dragY) {
                currentHue = parseFloat(dragY / slideHeight);
                isEmpty = false;
                if (!opts.showAlpha) {
                    currentAlpha = 1;
                }
                move();
            }, dragStart, dragStop);
            draggable(dragger, function (dragX, dragY, e) {
                // shift+drag should snap the movement to either the x or y axis.
                if (!e.shiftKey) {
                    shiftMovementDirection = null;
                }
                else if (!shiftMovementDirection) {
                    var oldDragX = currentSaturation * dragWidth;
                    var oldDragY = dragHeight - currentValue * dragHeight;
                    var furtherFromX = Math.abs(dragX - oldDragX) > Math.abs(dragY - oldDragY);
                    shiftMovementDirection = furtherFromX ? 'x' : 'y';
                }
                var setSaturation = !shiftMovementDirection || shiftMovementDirection === 'x';
                var setValue = !shiftMovementDirection || shiftMovementDirection === 'y';
                if (setSaturation) {
                    currentSaturation = parseFloat(dragX / dragWidth);
                }
                if (setValue) {
                    currentValue = parseFloat((dragHeight - dragY) / dragHeight);
                }
                isEmpty = false;
                if (!opts.showAlpha) {
                    currentAlpha = 1;
                }
                move();
            }, dragStart, dragStop);
            if (!!initialColor) {
                set(initialColor);
                // In case color was black - update the preview UI and set the format
                // since the set function will not run (default color is black).
                updateUI();
                currentPreferredFormat = opts.preferredFormat || tinycolor(initialColor).getFormat();
                addColorToSelectionPalette(initialColor);
            }
            else {
                updateUI();
            }
            if (flat) {
                show();
            }
            function paletteElementClick(e) {
                if (e.data && e.data.ignore) {
                    set($(e.target).closest('.sp-thumb-el').data('color'));
                    move();
                }
                else {
                    set($(e.target).closest('.sp-thumb-el').data('color'));
                    move();
                    if (opts.hideAfterPaletteSelect) {
                        updateOriginalInput(true);
                        hide();
                    }
                }
                return false;
            }
            var paletteEvent = IE ? 'mousedown.spectrum' : 'click.spectrum touchstart.spectrum';
            paletteContainer.delegate('.sp-thumb-el', paletteEvent, paletteElementClick);
            initialColorContainer.delegate('.sp-thumb-el:nth-child(1)', paletteEvent, { ignore: true }, paletteElementClick);
        }
        function updateSelectionPaletteFromStorage() {
            if (localStorageKey && window.localStorage) {
                // Migrate old palettes over to new format.  May want to remove this eventually.
                try {
                    var oldPalette = window.localStorage[localStorageKey].split(',#');
                    if (oldPalette.length > 1) {
                        delete window.localStorage[localStorageKey];
                        $.each(oldPalette, function (i, c) {
                            addColorToSelectionPalette(c);
                        });
                    }
                }
                catch (e) { }
                try {
                    selectionPalette = window.localStorage[localStorageKey].split(';');
                }
                catch (e) { }
            }
        }
        function addColorToSelectionPalette(color) {
            if (showSelectionPalette) {
                var rgb = tinycolor(color).toRgbString();
                if (!paletteLookup[rgb] && $.inArray(rgb, selectionPalette) === -1) {
                    selectionPalette.push(rgb);
                    while (selectionPalette.length > maxSelectionSize) {
                        selectionPalette.shift();
                    }
                }
                if (localStorageKey && window.localStorage) {
                    try {
                        window.localStorage[localStorageKey] = selectionPalette.join(';');
                    }
                    catch (e) { }
                }
            }
        }
        function getUniqueSelectionPalette() {
            var unique = [];
            if (opts.showPalette) {
                for (var i = 0; i < selectionPalette.length; i++) {
                    var rgb = tinycolor(selectionPalette[i]).toRgbString();
                    if (!paletteLookup[rgb]) {
                        unique.push(selectionPalette[i]);
                    }
                }
            }
            return unique.reverse().slice(0, opts.maxSelectionSize);
        }
        function drawPalette() {
            var currentColor = get();
            var html = $.map(paletteArray, function (palette, i) {
                return paletteTemplate(palette, currentColor, 'sp-palette-row sp-palette-row-' + i, opts);
            });
            updateSelectionPaletteFromStorage();
            if (selectionPalette) {
                html.push(paletteTemplate(getUniqueSelectionPalette(), currentColor, 'sp-palette-row sp-palette-row-selection', opts));
            }
            paletteContainer.html(html.join(''));
        }
        function drawInitial() {
            if (opts.showInitial) {
                var initial = colorOnShow;
                var current = get();
                initialColorContainer.html(paletteTemplate([initial, current], current, 'sp-palette-row-initial', opts));
            }
        }
        function dragStart() {
            if (dragHeight <= 0 || dragWidth <= 0 || slideHeight <= 0) {
                reflow();
            }
            isDragging = true;
            container.addClass(draggingClass);
            shiftMovementDirection = null;
            boundElement.trigger('dragstart.spectrum', [get()]);
        }
        function dragStop() {
            isDragging = false;
            container.removeClass(draggingClass);
            boundElement.trigger('dragstop.spectrum', [get()]);
        }
        function setFromTextInput() {
            var value = textInput.val();
            if ((value === null || value === '') && allowEmpty) {
                set(null);
                updateOriginalInput(true);
            }
            else {
                var tiny = tinycolor(value);
                if (tiny.isValid()) {
                    set(tiny);
                    updateOriginalInput(true);
                }
                else {
                    textInput.addClass('sp-validation-error');
                }
            }
        }
        function toggle() {
            if (visible) {
                hide();
            }
            else {
                show();
            }
        }
        function show() {
            var event = $.Event('beforeShow.spectrum');
            if (visible) {
                reflow();
                return;
            }
            boundElement.trigger('beforeShow.spectrum', [get()]);
            if (callbacks.beforeShow(get()) === false || event.isDefaultPrevented()) {
                return;
            }
            hideAll();
            visible = true;
            var $doc = $(doc);
            $doc.bind('keydown.spectrum', onkeydown);
            $doc.bind('click.spectrum', clickout);
            $(window).bind('resize.spectrum', resize);
            replacer.addClass('sp-active');
            container.removeClass('sp-hidden');
            reflow();
            updateUI();
            colorOnShow = get();
            drawInitial();
            callbacks.show(colorOnShow);
            boundElement.trigger('show.spectrum', [colorOnShow]);
        }
        function onkeydown(e) {
            // Close on ESC
            if (e.keyCode === 27) {
                hide();
            }
        }
        function clickout(e) {
            // Return on right click.
            if (e.button == 2) {
                return;
            }
            // If a drag event was happening during the mouseup, don't hide
            // on click.
            if (isDragging) {
                return;
            }
            if (clickoutFiresChange) {
                updateOriginalInput(true);
            }
            else {
                revert();
            }
            hide();
        }
        function hide() {
            // Return if hiding is unnecessary
            if (!visible || flat) {
                return;
            }
            visible = false;
            $(doc).unbind('keydown.spectrum', onkeydown);
            $(doc).unbind('click.spectrum', clickout);
            $(window).unbind('resize.spectrum', resize);
            replacer.removeClass('sp-active');
            container.addClass('sp-hidden');
            callbacks.hide(get());
            boundElement.trigger('hide.spectrum', [get()]);
        }
        function revert() {
            set(colorOnShow, true);
        }
        function set(color, ignoreFormatChange) {
            if (tinycolor.equals(color, get())) {
                // Update UI just in case a validation error needs
                // to be cleared.
                updateUI();
                return;
            }
            var newColor, newHsv;
            if (!color && allowEmpty) {
                isEmpty = true;
            }
            else {
                isEmpty = false;
                isDefault = !color; // if no color is available an empty string will be passed.  tinycolor will then set it to #000
                newColor = tinycolor(color);
                newHsv = newColor.toHsv();
                currentHue = (newHsv.h % 360) / 360;
                currentSaturation = newHsv.s;
                currentValue = newHsv.v;
                currentAlpha = newHsv.a;
            }
            updateUI();
            if (newColor && newColor.isValid() && !ignoreFormatChange) {
                currentPreferredFormat = opts.preferredFormat || newColor.getFormat();
            }
        }
        function get(opts) {
            opts = opts || {};
            if (allowEmpty && isEmpty) {
                return null;
            }
            return tinycolor.fromRatio({
                h: currentHue,
                s: currentSaturation,
                v: currentValue,
                a: Math.round(currentAlpha * 100) / 100,
            }, { format: opts.format || currentPreferredFormat });
        }
        function isValid() {
            return !textInput.hasClass('sp-validation-error');
        }
        function move() {
            updateUI();
            callbacks.move(get());
            boundElement.trigger('move.spectrum', [get()]);
        }
        function updateUI() {
            textInput.removeClass('sp-validation-error');
            updateHelperLocations();
            // Update dragger background color (gradients take care of saturation and value).
            var flatColor = tinycolor.fromRatio({ h: currentHue, s: 1, v: 1 });
            dragger.css('background-color', flatColor.toHexString());
            // Get a format that alpha will be included in (hex and names ignore alpha)
            var format = currentPreferredFormat;
            if (currentAlpha < 1 && !(currentAlpha === 0 && format === 'name')) {
                if (format === 'hex' || format === 'hex3' || format === 'hex6' || format === 'name') {
                    format = 'rgb';
                }
            }
            var realColor = get({ format: format }), displayColor = '';
            //reset background info for preview element
            previewElement.removeClass('sp-clear-display');
            previewElement.css('background-color', 'transparent');
            if (!realColor && allowEmpty) {
                // Update the replaced elements background with icon indicating no color selection
                previewElement.addClass('sp-clear-display');
            }
            else {
                var realHex = realColor.toHexString(), realRgb = realColor.toRgbString();
                // Update the replaced elements background color (with actual selected color)
                if (rgbaSupport || realColor.alpha === 1) {
                    previewElement.css('background-color', realRgb);
                }
                else {
                    previewElement.css('background-color', 'transparent');
                    previewElement.css('filter', realColor.toFilter());
                }
                if (opts.showAlpha) {
                    var rgb = realColor.toRgb();
                    rgb.a = 0;
                    var realAlpha = tinycolor(rgb).toRgbString();
                    var gradient = 'linear-gradient(left, ' + realAlpha + ', ' + realHex + ')';
                    if (IE) {
                        alphaSliderInner.css('filter', tinycolor(realAlpha).toFilter({ gradientType: 1 }, realHex));
                    }
                    else {
                        alphaSliderInner.css('background', '-webkit-' + gradient);
                        alphaSliderInner.css('background', '-moz-' + gradient);
                        alphaSliderInner.css('background', '-ms-' + gradient);
                        // Use current syntax gradient on unprefixed property.
                        alphaSliderInner.css('background', 'linear-gradient(to right, ' + realAlpha + ', ' + realHex + ')');
                    }
                }
                displayColor = realColor.toString(format);
            }
            // Update the text entry input as it changes happen
            if (opts.showInput) {
                textInput.val(displayColor);
            }
            if (opts.showPalette) {
                drawPalette();
            }
            drawInitial();
        }
        function updateHelperLocations() {
            var s = currentSaturation;
            var v = currentValue;
            if (allowEmpty && isEmpty) {
                //if selected color is empty, hide the helpers
                alphaSlideHelper.hide();
                slideHelper.hide();
                dragHelper.hide();
            }
            else {
                //make sure helpers are visible
                alphaSlideHelper.show();
                slideHelper.show();
                dragHelper.show();
                // Where to show the little circle in that displays your current selected color
                var dragX = s * dragWidth;
                var dragY = dragHeight - v * dragHeight;
                dragX = Math.max(-dragHelperHeight, Math.min(dragWidth - dragHelperHeight, dragX - dragHelperHeight));
                dragY = Math.max(-dragHelperHeight, Math.min(dragHeight - dragHelperHeight, dragY - dragHelperHeight));
                dragHelper.css({
                    top: dragY + 'px',
                    left: dragX + 'px',
                });
                var alphaX = currentAlpha * alphaWidth;
                alphaSlideHelper.css({
                    left: alphaX - alphaSlideHelperWidth / 2 + 'px',
                });
                // Where to show the bar that displays your current selected hue
                var slideY = currentHue * slideHeight;
                slideHelper.css({
                    top: slideY - slideHelperHeight + 'px',
                });
            }
        }
        function updateOriginalInput(fireCallback) {
            var color = get(), displayColor = '', hasChanged = isDefault ? true : !tinycolor.equals(color, colorOnShow);
            if (color) {
                displayColor = color.toString(currentPreferredFormat);
                // Update the selection palette with the current color
                !visible && addColorToSelectionPalette(color);
            }
            if (isInput) {
                boundElement.val(displayColor);
            }
            if (fireCallback && hasChanged) {
                callbacks.change(color);
                boundElement.trigger('change', [color]);
            }
        }
        function reflow() {
            if (!visible) {
                return; // Calculations would be useless and wouldn't be reliable anyways
            }
            dragWidth = dragger.width();
            dragHeight = dragger.height();
            dragHelperHeight = dragHelper.height();
            slideWidth = slider.width();
            slideHeight = slider.height();
            slideHelperHeight = slideHelper.height();
            alphaWidth = alphaSlider.width();
            alphaSlideHelperWidth = alphaSlideHelper.width();
            if (!flat) {
                container.css('position', 'absolute');
                if (opts.offset) {
                    container.offset(opts.offset);
                }
                else {
                    container.offset(getOffset(container, offsetElement));
                }
            }
            updateHelperLocations();
            if (opts.showPalette) {
                drawPalette();
            }
            boundElement.trigger('reflow.spectrum');
        }
        function destroy() {
            boundElement.show();
            offsetElement.unbind('click.spectrum touchstart.spectrum');
            container.remove();
            replacer.remove();
            spectrums[spect.id] = null;
        }
        function option(optionName, optionValue) {
            if (optionName === undefined) {
                return $.extend({}, opts);
            }
            if (optionValue === undefined) {
                return opts[optionName];
            }
            opts[optionName] = optionValue;
            if (optionName === 'preferredFormat') {
                currentPreferredFormat = opts.preferredFormat;
            }
            applyOptions();
        }
        function enable() {
            disabled = false;
            boundElement.attr('disabled', false);
            offsetElement.removeClass('sp-disabled');
        }
        function disable() {
            hide();
            disabled = true;
            boundElement.attr('disabled', true);
            offsetElement.addClass('sp-disabled');
        }
        function setOffset(coord) {
            opts.offset = coord;
            reflow();
        }
        initialize();
        var spect = {
            show: show,
            hide: hide,
            toggle: toggle,
            reflow: reflow,
            option: option,
            enable: enable,
            disable: disable,
            offset: setOffset,
            set: function (c) {
                set(c);
                updateOriginalInput();
            },
            get: get,
            destroy: destroy,
            container: container,
        };
        spect.id = spectrums.push(spect) - 1;
        return spect;
    }
    /**
     * checkOffset - get the offset below/above and left/right element depending on screen position
     */
    function getOffset(picker, input) {
        var offsetElm = input[0];
        var pickerEl = picker[0];
        var rootElm = pickerEl.parentElement;
        var inputRect = offsetElm.getBoundingClientRect();
        var pickerW = pickerEl.offsetWidth;
        var pickerH = pickerEl.offsetHeight;
        var offset = {
            top: 0,
            left: 0,
            width: offsetElm.offsetWidth,
            height: offsetElm.offsetHeight,
        };
        while (offsetElm) {
            offset.top += offsetElm.offsetTop - offsetElm.scrollTop;
            offset.left += offsetElm.offsetLeft - offsetElm.scrollLeft;
            // Check if the current element in our root, or if the next offset parent is outside of the root
            if (offsetElm === rootElm || !rootElm.contains(offsetElm.offsetParent)) {
                break;
            }
            offsetElm = offsetElm.offsetParent;
        }
        // Input is to close to the right side of the screen to show picker
        if (inputRect.right + pickerW > window.innerWidth - window.scrollX && inputRect.right - pickerW > 0) {
            // Right align the picker to the input
            offset.left -= pickerW - offset.width;
        }
        // Input is to close to the bottom of the screen to show picker above
        if (inputRect.bottom + pickerH < window.innerHeight - window.scrollY) {
            offset.top += offset.height;
        }
        else {
            offset.top -= pickerH;
        }
        return offset;
    }
    /**
     * noop - do nothing
     */
    function noop() { }
    /**
     * stopPropagation - makes the code only doing this a little easier to read in line
     */
    function stopPropagation(e) {
        e.stopPropagation();
    }
    /**
     * Create a function bound to a given object
     * Thanks to underscore.js
     */
    function bind(func, obj) {
        var slice = Array.prototype.slice;
        var args = slice.call(arguments, 2);
        return function () {
            return func.apply(obj, args.concat(slice.call(arguments)));
        };
    }
    /**
     * Lightweight drag helper.  Handles containment within the element, so that
     * when dragging, the x is within [0,element.width] and y is within [0,element.height]
     */
    function draggable(element, onmove, onstart, onstop) {
        onmove = onmove || function () { };
        onstart = onstart || function () { };
        onstop = onstop || function () { };
        var doc = document;
        var dragging = false;
        var offset = {};
        var maxHeight = 0;
        var maxWidth = 0;
        var hasTouch = 'ontouchstart' in window;
        var duringDragEvents = {};
        duringDragEvents['selectstart'] = prevent;
        duringDragEvents['dragstart'] = prevent;
        duringDragEvents['touchmove mousemove'] = move;
        duringDragEvents['touchend mouseup'] = stop;
        function prevent(e) {
            if (e.stopPropagation) {
                e.stopPropagation();
            }
            if (e.preventDefault) {
                e.preventDefault();
            }
            e.returnValue = false;
        }
        function move(e) {
            if (dragging) {
                // Mouseup happened outside of window
                if (IE && doc.documentMode < 9 && !e.button) {
                    return stop();
                }
                var t0 = e && e.touches && e.touches[0];
                var pageX = (t0 && t0.pageX) || e.pageX;
                var pageY = (t0 && t0.pageY) || e.pageY;
                var dragX = Math.max(0, Math.min(pageX - offset.left, maxWidth));
                var dragY = Math.max(0, Math.min(pageY - offset.top, maxHeight));
                if (hasTouch) {
                    // Stop scrolling in iOS
                    prevent(e);
                }
                onmove.apply(element, [dragX, dragY, e]);
            }
        }
        function start(e) {
            var rightclick = e.which ? e.which == 3 : e.button == 2;
            if (!rightclick && !dragging) {
                if (onstart.apply(element, arguments) !== false) {
                    dragging = true;
                    maxHeight = $(element).height();
                    maxWidth = $(element).width();
                    offset = $(element).offset();
                    $(doc).bind(duringDragEvents);
                    $(doc.body).addClass('sp-dragging');
                    move(e);
                    prevent(e);
                }
            }
        }
        function stop() {
            if (dragging) {
                $(doc).unbind(duringDragEvents);
                $(doc.body).removeClass('sp-dragging');
                // Wait a tick before notifying observers to allow the click event
                // to fire in Chrome.
                setTimeout(function () {
                    onstop.apply(element, arguments);
                }, 0);
            }
            dragging = false;
        }
        $(element).bind('touchstart mousedown', start);
    }
    function throttle(func, wait, debounce) {
        var timeout;
        return function () {
            var context = this, args = arguments;
            var throttler = function () {
                timeout = null;
                func.apply(context, args);
            };
            if (debounce)
                clearTimeout(timeout);
            if (debounce || !timeout)
                timeout = setTimeout(throttler, wait);
        };
    }
    function inputTypeColorSupport() {
        return $.fn.spectrum.inputTypeColorSupport();
    }
    /**
     * Define a jQuery plugin
     */
    var dataID = 'spectrum.id';
    $.fn.spectrum = function (opts, extra) {
        if (typeof opts == 'string') {
            var returnValue = this;
            var args = Array.prototype.slice.call(arguments, 1);
            this.each(function () {
                var spect = spectrums[$(this).data(dataID)];
                if (spect) {
                    var method = spect[opts];
                    if (!method) {
                        throw new Error("Spectrum: no such method: '" + opts + "'");
                    }
                    if (opts == 'get') {
                        returnValue = spect.get();
                    }
                    else if (opts == 'container') {
                        returnValue = spect.container;
                    }
                    else if (opts == 'option') {
                        returnValue = spect.option.apply(spect, args);
                    }
                    else if (opts == 'destroy') {
                        spect.destroy();
                        $(this).removeData(dataID);
                    }
                    else {
                        method.apply(spect, args);
                    }
                }
            });
            return returnValue;
        }
        // Initializing a new instance of spectrum
        return this.spectrum('destroy').each(function () {
            var options = $.extend({}, opts, $(this).data());
            var spect = spectrum(this, options);
            $(this).data(dataID, spect.id);
        });
    };
    $.fn.spectrum.load = true;
    $.fn.spectrum.loadOpts = {};
    $.fn.spectrum.draggable = draggable;
    $.fn.spectrum.defaults = defaultOpts;
    $.fn.spectrum.inputTypeColorSupport = function inputTypeColorSupport() {
        if (typeof inputTypeColorSupport._cachedResult === 'undefined') {
            var colorInput = $("<input type='color'/>")[0]; // if color element is supported, value will default to not null
            inputTypeColorSupport._cachedResult = colorInput.type === 'color' && colorInput.value !== '';
        }
        return inputTypeColorSupport._cachedResult;
    };
    $.spectrum = {};
    $.spectrum.localization = {};
    $.spectrum.palettes = {};
    $.fn.spectrum.processNativeColorInputs = function () {
        var colorInputs = $('input[type=color]');
        if (colorInputs.length && !inputTypeColorSupport()) {
            colorInputs.spectrum({
                preferredFormat: 'hex6',
            });
        }
    };
    // TinyColor v1.1.2
    // https://github.com/bgrins/TinyColor
    // Brian Grinstead, MIT License
    //(function() {
    var trimLeft = /^[\s,#]+/, trimRight = /\s+$/, tinyCounter = 0, math = Math, mathRound = math.round, mathMin = math.min, mathMax = math.max, mathRandom = math.random;
    var tinycolor = function (color, opts) {
        color = color ? color : '';
        opts = opts || {};
        // If input is already a tinycolor, return itself
        if (color instanceof tinycolor) {
            return color;
        }
        // If we are called as a function, call using new instead
        if (!(this instanceof tinycolor)) {
            return new tinycolor(color, opts);
        }
        var rgb = inputToRGB(color);
        (this._originalInput = color),
            (this._r = rgb.r),
            (this._g = rgb.g),
            (this._b = rgb.b),
            (this._a = rgb.a),
            (this._roundA = mathRound(100 * this._a) / 100),
            (this._format = opts.format || rgb.format);
        this._gradientType = opts.gradientType;
        // Don't let the range of [0,255] come back in [0,1].
        // Potentially lose a little bit of precision here, but will fix issues where
        // .5 gets interpreted as half of the total, instead of half of 1
        // If it was supposed to be 128, this was already taken care of by `inputToRgb`
        if (this._r < 1) {
            this._r = mathRound(this._r);
        }
        if (this._g < 1) {
            this._g = mathRound(this._g);
        }
        if (this._b < 1) {
            this._b = mathRound(this._b);
        }
        this._ok = rgb.ok;
        this._tc_id = tinyCounter++;
    };
    tinycolor.prototype = {
        isDark: function () {
            return this.getBrightness() < 128;
        },
        isLight: function () {
            return !this.isDark();
        },
        isValid: function () {
            return this._ok;
        },
        getOriginalInput: function () {
            return this._originalInput;
        },
        getFormat: function () {
            return this._format;
        },
        getAlpha: function () {
            return this._a;
        },
        getBrightness: function () {
            var rgb = this.toRgb();
            return (rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1000;
        },
        setAlpha: function (value) {
            this._a = boundAlpha(value);
            this._roundA = mathRound(100 * this._a) / 100;
            return this;
        },
        toHsv: function () {
            var hsv = rgbToHsv(this._r, this._g, this._b);
            return { h: hsv.h * 360, s: hsv.s, v: hsv.v, a: this._a };
        },
        toHsvString: function () {
            var hsv = rgbToHsv(this._r, this._g, this._b);
            var h = mathRound(hsv.h * 360), s = mathRound(hsv.s * 100), v = mathRound(hsv.v * 100);
            return this._a == 1
                ? 'hsv(' + h + ', ' + s + '%, ' + v + '%)'
                : 'hsva(' + h + ', ' + s + '%, ' + v + '%, ' + this._roundA + ')';
        },
        toHsl: function () {
            var hsl = rgbToHsl(this._r, this._g, this._b);
            return { h: hsl.h * 360, s: hsl.s, l: hsl.l, a: this._a };
        },
        toHslString: function () {
            var hsl = rgbToHsl(this._r, this._g, this._b);
            var h = mathRound(hsl.h * 360), s = mathRound(hsl.s * 100), l = mathRound(hsl.l * 100);
            return this._a == 1
                ? 'hsl(' + h + ', ' + s + '%, ' + l + '%)'
                : 'hsla(' + h + ', ' + s + '%, ' + l + '%, ' + this._roundA + ')';
        },
        toHex: function (allow3Char) {
            return rgbToHex(this._r, this._g, this._b, allow3Char);
        },
        toHexString: function (allow3Char) {
            return '#' + this.toHex(allow3Char);
        },
        toHex8: function () {
            return rgbaToHex(this._r, this._g, this._b, this._a);
        },
        toHex8String: function () {
            return '#' + this.toHex8();
        },
        toRgb: function () {
            return {
                r: mathRound(this._r),
                g: mathRound(this._g),
                b: mathRound(this._b),
                a: this._a,
            };
        },
        toRgbString: function () {
            return this._a == 1
                ? 'rgb(' + mathRound(this._r) + ', ' + mathRound(this._g) + ', ' + mathRound(this._b) + ')'
                : 'rgba(' +
                    mathRound(this._r) +
                    ', ' +
                    mathRound(this._g) +
                    ', ' +
                    mathRound(this._b) +
                    ', ' +
                    this._roundA +
                    ')';
        },
        toPercentageRgb: function () {
            return {
                r: mathRound(bound01(this._r, 255) * 100) + '%',
                g: mathRound(bound01(this._g, 255) * 100) + '%',
                b: mathRound(bound01(this._b, 255) * 100) + '%',
                a: this._a,
            };
        },
        toPercentageRgbString: function () {
            return this._a == 1
                ? 'rgb(' +
                    mathRound(bound01(this._r, 255) * 100) +
                    '%, ' +
                    mathRound(bound01(this._g, 255) * 100) +
                    '%, ' +
                    mathRound(bound01(this._b, 255) * 100) +
                    '%)'
                : 'rgba(' +
                    mathRound(bound01(this._r, 255) * 100) +
                    '%, ' +
                    mathRound(bound01(this._g, 255) * 100) +
                    '%, ' +
                    mathRound(bound01(this._b, 255) * 100) +
                    '%, ' +
                    this._roundA +
                    ')';
        },
        toName: function () {
            if (this._a === 0) {
                return 'transparent';
            }
            if (this._a < 1) {
                return false;
            }
            return hexNames[rgbToHex(this._r, this._g, this._b, true)] || false;
        },
        toFilter: function (secondColor) {
            var hex8String = '#' + rgbaToHex(this._r, this._g, this._b, this._a);
            var secondHex8String = hex8String;
            var gradientType = this._gradientType ? 'GradientType = 1, ' : '';
            if (secondColor) {
                var s = tinycolor(secondColor);
                secondHex8String = s.toHex8String();
            }
            return ('progid:DXImageTransform.Microsoft.gradient(' +
                gradientType +
                'startColorstr=' +
                hex8String +
                ',endColorstr=' +
                secondHex8String +
                ')');
        },
        toString: function (format) {
            var formatSet = !!format;
            format = format || this._format;
            var formattedString = false;
            var hasAlpha = this._a < 1 && this._a >= 0;
            var needsAlphaFormat = !formatSet && hasAlpha && (format === 'hex' || format === 'hex6' || format === 'hex3' || format === 'name');
            if (needsAlphaFormat) {
                // Special case for "transparent", all other non-alpha formats
                // will return rgba when there is transparency.
                if (format === 'name' && this._a === 0) {
                    return this.toName();
                }
                return this.toRgbString();
            }
            if (format === 'rgb') {
                formattedString = this.toRgbString();
            }
            if (format === 'prgb') {
                formattedString = this.toPercentageRgbString();
            }
            if (format === 'hex' || format === 'hex6') {
                formattedString = this.toHexString();
            }
            if (format === 'hex3') {
                formattedString = this.toHexString(true);
            }
            if (format === 'hex8') {
                formattedString = this.toHex8String();
            }
            if (format === 'name') {
                formattedString = this.toName();
            }
            if (format === 'hsl') {
                formattedString = this.toHslString();
            }
            if (format === 'hsv') {
                formattedString = this.toHsvString();
            }
            return formattedString || this.toHexString();
        },
        _applyModification: function (fn, args) {
            var color = fn.apply(null, [this].concat([].slice.call(args)));
            this._r = color._r;
            this._g = color._g;
            this._b = color._b;
            this.setAlpha(color._a);
            return this;
        },
        lighten: function () {
            return this._applyModification(lighten, arguments);
        },
        brighten: function () {
            return this._applyModification(brighten, arguments);
        },
        darken: function () {
            return this._applyModification(darken, arguments);
        },
        desaturate: function () {
            return this._applyModification(desaturate, arguments);
        },
        saturate: function () {
            return this._applyModification(saturate, arguments);
        },
        greyscale: function () {
            return this._applyModification(greyscale, arguments);
        },
        spin: function () {
            return this._applyModification(spin, arguments);
        },
        _applyCombination: function (fn, args) {
            return fn.apply(null, [this].concat([].slice.call(args)));
        },
        analogous: function () {
            return this._applyCombination(analogous, arguments);
        },
        complement: function () {
            return this._applyCombination(complement, arguments);
        },
        monochromatic: function () {
            return this._applyCombination(monochromatic, arguments);
        },
        splitcomplement: function () {
            return this._applyCombination(splitcomplement, arguments);
        },
        triad: function () {
            return this._applyCombination(triad, arguments);
        },
        tetrad: function () {
            return this._applyCombination(tetrad, arguments);
        },
    };
    // If input is an object, force 1 into "1.0" to handle ratios properly
    // String input requires "1.0" as input, so 1 will be treated as 1
    tinycolor.fromRatio = function (color, opts) {
        if (typeof color == 'object') {
            var newColor = {};
            for (var i in color) {
                if (color.hasOwnProperty(i)) {
                    if (i === 'a') {
                        newColor[i] = color[i];
                    }
                    else {
                        newColor[i] = convertToPercentage(color[i]);
                    }
                }
            }
            color = newColor;
        }
        return tinycolor(color, opts);
    };
    // Given a string or object, convert that input to RGB
    // Possible string inputs:
    //
    //     "red"
    //     "#f00" or "f00"
    //     "#ff0000" or "ff0000"
    //     "#ff000000" or "ff000000"
    //     "rgb 255 0 0" or "rgb (255, 0, 0)"
    //     "rgb 1.0 0 0" or "rgb (1, 0, 0)"
    //     "rgba (255, 0, 0, 1)" or "rgba 255, 0, 0, 1"
    //     "rgba (1.0, 0, 0, 1)" or "rgba 1.0, 0, 0, 1"
    //     "hsl(0, 100%, 50%)" or "hsl 0 100% 50%"
    //     "hsla(0, 100%, 50%, 1)" or "hsla 0 100% 50%, 1"
    //     "hsv(0, 100%, 100%)" or "hsv 0 100% 100%"
    //
    function inputToRGB(color) {
        var rgb = { r: 0, g: 0, b: 0 };
        var a = 1;
        var ok = false;
        var format = false;
        if (typeof color == 'string') {
            color = stringInputToObject(color);
        }
        if (typeof color == 'object') {
            if (color.hasOwnProperty('r') && color.hasOwnProperty('g') && color.hasOwnProperty('b')) {
                rgb = rgbToRgb(color.r, color.g, color.b);
                ok = true;
                format = String(color.r).substr(-1) === '%' ? 'prgb' : 'rgb';
            }
            else if (color.hasOwnProperty('h') && color.hasOwnProperty('s') && color.hasOwnProperty('v')) {
                color.s = convertToPercentage(color.s);
                color.v = convertToPercentage(color.v);
                rgb = hsvToRgb(color.h, color.s, color.v);
                ok = true;
                format = 'hsv';
            }
            else if (color.hasOwnProperty('h') && color.hasOwnProperty('s') && color.hasOwnProperty('l')) {
                color.s = convertToPercentage(color.s);
                color.l = convertToPercentage(color.l);
                rgb = hslToRgb(color.h, color.s, color.l);
                ok = true;
                format = 'hsl';
            }
            if (color.hasOwnProperty('a')) {
                a = color.a;
            }
        }
        a = boundAlpha(a);
        return {
            ok: ok,
            format: color.format || format,
            r: mathMin(255, mathMax(rgb.r, 0)),
            g: mathMin(255, mathMax(rgb.g, 0)),
            b: mathMin(255, mathMax(rgb.b, 0)),
            a: a,
        };
    }
    // Conversion Functions
    // --------------------
    // `rgbToHsl`, `rgbToHsv`, `hslToRgb`, `hsvToRgb` modified from:
    // <http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript>
    // `rgbToRgb`
    // Handle bounds / percentage checking to conform to CSS color spec
    // <http://www.w3.org/TR/css3-color/>
    // *Assumes:* r, g, b in [0, 255] or [0, 1]
    // *Returns:* { r, g, b } in [0, 255]
    function rgbToRgb(r, g, b) {
        return {
            r: bound01(r, 255) * 255,
            g: bound01(g, 255) * 255,
            b: bound01(b, 255) * 255,
        };
    }
    // `rgbToHsl`
    // Converts an RGB color value to HSL.
    // *Assumes:* r, g, and b are contained in [0, 255] or [0, 1]
    // *Returns:* { h, s, l } in [0,1]
    function rgbToHsl(r, g, b) {
        r = bound01(r, 255);
        g = bound01(g, 255);
        b = bound01(b, 255);
        var max = mathMax(r, g, b), min = mathMin(r, g, b);
        var h, s, l = (max + min) / 2;
        if (max == min) {
            h = s = 0; // achromatic
        }
        else {
            var d = max - min;
            s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
            switch (max) {
                case r:
                    h = (g - b) / d + (g < b ? 6 : 0);
                    break;
                case g:
                    h = (b - r) / d + 2;
                    break;
                case b:
                    h = (r - g) / d + 4;
                    break;
            }
            h /= 6;
        }
        return { h: h, s: s, l: l };
    }
    // `hslToRgb`
    // Converts an HSL color value to RGB.
    // *Assumes:* h is contained in [0, 1] or [0, 360] and s and l are contained [0, 1] or [0, 100]
    // *Returns:* { r, g, b } in the set [0, 255]
    function hslToRgb(h, s, l) {
        var r, g, b;
        h = bound01(h, 360);
        s = bound01(s, 100);
        l = bound01(l, 100);
        function hue2rgb(p, q, t) {
            if (t < 0)
                t += 1;
            if (t > 1)
                t -= 1;
            if (t < 1 / 6)
                return p + (q - p) * 6 * t;
            if (t < 1 / 2)
                return q;
            if (t < 2 / 3)
                return p + (q - p) * (2 / 3 - t) * 6;
            return p;
        }
        if (s === 0) {
            r = g = b = l; // achromatic
        }
        else {
            var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
            var p = 2 * l - q;
            r = hue2rgb(p, q, h + 1 / 3);
            g = hue2rgb(p, q, h);
            b = hue2rgb(p, q, h - 1 / 3);
        }
        return { r: r * 255, g: g * 255, b: b * 255 };
    }
    // `rgbToHsv`
    // Converts an RGB color value to HSV
    // *Assumes:* r, g, and b are contained in the set [0, 255] or [0, 1]
    // *Returns:* { h, s, v } in [0,1]
    function rgbToHsv(r, g, b) {
        r = bound01(r, 255);
        g = bound01(g, 255);
        b = bound01(b, 255);
        var max = mathMax(r, g, b), min = mathMin(r, g, b);
        var h, s, v = max;
        var d = max - min;
        s = max === 0 ? 0 : d / max;
        if (max == min) {
            h = 0; // achromatic
        }
        else {
            switch (max) {
                case r:
                    h = (g - b) / d + (g < b ? 6 : 0);
                    break;
                case g:
                    h = (b - r) / d + 2;
                    break;
                case b:
                    h = (r - g) / d + 4;
                    break;
            }
            h /= 6;
        }
        return { h: h, s: s, v: v };
    }
    // `hsvToRgb`
    // Converts an HSV color value to RGB.
    // *Assumes:* h is contained in [0, 1] or [0, 360] and s and v are contained in [0, 1] or [0, 100]
    // *Returns:* { r, g, b } in the set [0, 255]
    function hsvToRgb(h, s, v) {
        h = bound01(h, 360) * 6;
        s = bound01(s, 100);
        v = bound01(v, 100);
        var i = math.floor(h), f = h - i, p = v * (1 - s), q = v * (1 - f * s), t = v * (1 - (1 - f) * s), mod = i % 6, r = [v, q, p, p, t, v][mod], g = [t, v, v, q, p, p][mod], b = [p, p, t, v, v, q][mod];
        return { r: r * 255, g: g * 255, b: b * 255 };
    }
    // `rgbToHex`
    // Converts an RGB color to hex
    // Assumes r, g, and b are contained in the set [0, 255]
    // Returns a 3 or 6 character hex
    function rgbToHex(r, g, b, allow3Char) {
        var hex = [pad2(mathRound(r).toString(16)), pad2(mathRound(g).toString(16)), pad2(mathRound(b).toString(16))];
        // Return a 3 character hex if possible
        if (allow3Char &&
            hex[0].charAt(0) == hex[0].charAt(1) &&
            hex[1].charAt(0) == hex[1].charAt(1) &&
            hex[2].charAt(0) == hex[2].charAt(1)) {
            return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0);
        }
        return hex.join('');
    }
    // `rgbaToHex`
    // Converts an RGBA color plus alpha transparency to hex
    // Assumes r, g, b and a are contained in the set [0, 255]
    // Returns an 8 character hex
    function rgbaToHex(r, g, b, a) {
        var hex = [
            pad2(convertDecimalToHex(a)),
            pad2(mathRound(r).toString(16)),
            pad2(mathRound(g).toString(16)),
            pad2(mathRound(b).toString(16)),
        ];
        return hex.join('');
    }
    // `equals`
    // Can be called with any tinycolor input
    tinycolor.equals = function (color1, color2) {
        if (!color1 || !color2) {
            return false;
        }
        return tinycolor(color1).toRgbString() == tinycolor(color2).toRgbString();
    };
    tinycolor.random = function () {
        return tinycolor.fromRatio({
            r: mathRandom(),
            g: mathRandom(),
            b: mathRandom(),
        });
    };
    // Modification Functions
    // ----------------------
    // Thanks to less.js for some of the basics here
    // <https://github.com/cloudhead/less.js/blob/master/lib/less/functions.js>
    function desaturate(color, amount) {
        amount = amount === 0 ? 0 : amount || 10;
        var hsl = tinycolor(color).toHsl();
        hsl.s -= amount / 100;
        hsl.s = clamp01(hsl.s);
        return tinycolor(hsl);
    }
    function saturate(color, amount) {
        amount = amount === 0 ? 0 : amount || 10;
        var hsl = tinycolor(color).toHsl();
        hsl.s += amount / 100;
        hsl.s = clamp01(hsl.s);
        return tinycolor(hsl);
    }
    function greyscale(color) {
        return tinycolor(color).desaturate(100);
    }
    function lighten(color, amount) {
        amount = amount === 0 ? 0 : amount || 10;
        var hsl = tinycolor(color).toHsl();
        hsl.l += amount / 100;
        hsl.l = clamp01(hsl.l);
        return tinycolor(hsl);
    }
    function brighten(color, amount) {
        amount = amount === 0 ? 0 : amount || 10;
        var rgb = tinycolor(color).toRgb();
        rgb.r = mathMax(0, mathMin(255, rgb.r - mathRound(255 * -(amount / 100))));
        rgb.g = mathMax(0, mathMin(255, rgb.g - mathRound(255 * -(amount / 100))));
        rgb.b = mathMax(0, mathMin(255, rgb.b - mathRound(255 * -(amount / 100))));
        return tinycolor(rgb);
    }
    function darken(color, amount) {
        amount = amount === 0 ? 0 : amount || 10;
        var hsl = tinycolor(color).toHsl();
        hsl.l -= amount / 100;
        hsl.l = clamp01(hsl.l);
        return tinycolor(hsl);
    }
    // Spin takes a positive or negative amount within [-360, 360] indicating the change of hue.
    // Values outside of this range will be wrapped into this range.
    function spin(color, amount) {
        var hsl = tinycolor(color).toHsl();
        var hue = (mathRound(hsl.h) + amount) % 360;
        hsl.h = hue < 0 ? 360 + hue : hue;
        return tinycolor(hsl);
    }
    // Combination Functions
    // ---------------------
    // Thanks to jQuery xColor for some of the ideas behind these
    // <https://github.com/infusion/jQuery-xcolor/blob/master/jquery.xcolor.js>
    function complement(color) {
        var hsl = tinycolor(color).toHsl();
        hsl.h = (hsl.h + 180) % 360;
        return tinycolor(hsl);
    }
    function triad(color) {
        var hsl = tinycolor(color).toHsl();
        var h = hsl.h;
        return [
            tinycolor(color),
            tinycolor({ h: (h + 120) % 360, s: hsl.s, l: hsl.l }),
            tinycolor({ h: (h + 240) % 360, s: hsl.s, l: hsl.l }),
        ];
    }
    function tetrad(color) {
        var hsl = tinycolor(color).toHsl();
        var h = hsl.h;
        return [
            tinycolor(color),
            tinycolor({ h: (h + 90) % 360, s: hsl.s, l: hsl.l }),
            tinycolor({ h: (h + 180) % 360, s: hsl.s, l: hsl.l }),
            tinycolor({ h: (h + 270) % 360, s: hsl.s, l: hsl.l }),
        ];
    }
    function splitcomplement(color) {
        var hsl = tinycolor(color).toHsl();
        var h = hsl.h;
        return [
            tinycolor(color),
            tinycolor({ h: (h + 72) % 360, s: hsl.s, l: hsl.l }),
            tinycolor({ h: (h + 216) % 360, s: hsl.s, l: hsl.l }),
        ];
    }
    function analogous(color, results, slices) {
        results = results || 6;
        slices = slices || 30;
        var hsl = tinycolor(color).toHsl();
        var part = 360 / slices;
        var ret = [tinycolor(color)];
        for (hsl.h = (hsl.h - ((part * results) >> 1) + 720) % 360; --results;) {
            hsl.h = (hsl.h + part) % 360;
            ret.push(tinycolor(hsl));
        }
        return ret;
    }
    function monochromatic(color, results) {
        results = results || 6;
        var hsv = tinycolor(color).toHsv();
        var h = hsv.h, s = hsv.s, v = hsv.v;
        var ret = [];
        var modification = 1 / results;
        while (results--) {
            ret.push(tinycolor({ h: h, s: s, v: v }));
            v = (v + modification) % 1;
        }
        return ret;
    }
    // Utility Functions
    // ---------------------
    tinycolor.mix = function (color1, color2, amount) {
        amount = amount === 0 ? 0 : amount || 50;
        var rgb1 = tinycolor(color1).toRgb();
        var rgb2 = tinycolor(color2).toRgb();
        var p = amount / 100;
        var w = p * 2 - 1;
        var a = rgb2.a - rgb1.a;
        var w1;
        if (w * a == -1) {
            w1 = w;
        }
        else {
            w1 = (w + a) / (1 + w * a);
        }
        w1 = (w1 + 1) / 2;
        var w2 = 1 - w1;
        var rgba = {
            r: rgb2.r * w1 + rgb1.r * w2,
            g: rgb2.g * w1 + rgb1.g * w2,
            b: rgb2.b * w1 + rgb1.b * w2,
            a: rgb2.a * p + rgb1.a * (1 - p),
        };
        return tinycolor(rgba);
    };
    // Readability Functions
    // ---------------------
    // <http://www.w3.org/TR/AERT#color-contrast>
    // `readability`
    // Analyze the 2 colors and returns an object with the following properties:
    //    `brightness`: difference in brightness between the two colors
    //    `color`: difference in color/hue between the two colors
    tinycolor.readability = function (color1, color2) {
        var c1 = tinycolor(color1);
        var c2 = tinycolor(color2);
        var rgb1 = c1.toRgb();
        var rgb2 = c2.toRgb();
        var brightnessA = c1.getBrightness();
        var brightnessB = c2.getBrightness();
        var colorDiff = Math.max(rgb1.r, rgb2.r) -
            Math.min(rgb1.r, rgb2.r) +
            Math.max(rgb1.g, rgb2.g) -
            Math.min(rgb1.g, rgb2.g) +
            Math.max(rgb1.b, rgb2.b) -
            Math.min(rgb1.b, rgb2.b);
        return {
            brightness: Math.abs(brightnessA - brightnessB),
            color: colorDiff,
        };
    };
    // `readable`
    // http://www.w3.org/TR/AERT#color-contrast
    // Ensure that foreground and background color combinations provide sufficient contrast.
    // *Example*
    //    tinycolor.isReadable("#000", "#111") => false
    tinycolor.isReadable = function (color1, color2) {
        var readability = tinycolor.readability(color1, color2);
        return readability.brightness > 125 && readability.color > 500;
    };
    // `mostReadable`
    // Given a base color and a list of possible foreground or background
    // colors for that base, returns the most readable color.
    // *Example*
    //    tinycolor.mostReadable("#123", ["#fff", "#000"]) => "#000"
    tinycolor.mostReadable = function (baseColor, colorList) {
        var bestColor = null;
        var bestScore = 0;
        var bestIsReadable = false;
        for (var i = 0; i < colorList.length; i++) {
            // We normalize both around the "acceptable" breaking point,
            // but rank brightness constrast higher than hue.
            var readability = tinycolor.readability(baseColor, colorList[i]);
            var readable = readability.brightness > 125 && readability.color > 500;
            var score = 3 * (readability.brightness / 125) + readability.color / 500;
            if ((readable && !bestIsReadable) ||
                (readable && bestIsReadable && score > bestScore) ||
                (!readable && !bestIsReadable && score > bestScore)) {
                bestIsReadable = readable;
                bestScore = score;
                bestColor = tinycolor(colorList[i]);
            }
        }
        return bestColor;
    };
    // Big List of Colors
    // ------------------
    // <http://www.w3.org/TR/css3-color/#svg-color>
    var names = (tinycolor.names = {
        aliceblue: 'f0f8ff',
        antiquewhite: 'faebd7',
        aqua: '0ff',
        aquamarine: '7fffd4',
        azure: 'f0ffff',
        beige: 'f5f5dc',
        bisque: 'ffe4c4',
        black: '000',
        blanchedalmond: 'ffebcd',
        blue: '00f',
        blueviolet: '8a2be2',
        brown: 'a52a2a',
        burlywood: 'deb887',
        burntsienna: 'ea7e5d',
        cadetblue: '5f9ea0',
        chartreuse: '7fff00',
        chocolate: 'd2691e',
        coral: 'ff7f50',
        cornflowerblue: '6495ed',
        cornsilk: 'fff8dc',
        crimson: 'dc143c',
        cyan: '0ff',
        darkblue: '00008b',
        darkcyan: '008b8b',
        darkgoldenrod: 'b8860b',
        darkgray: 'a9a9a9',
        darkgreen: '006400',
        darkgrey: 'a9a9a9',
        darkkhaki: 'bdb76b',
        darkmagenta: '8b008b',
        darkolivegreen: '556b2f',
        darkorange: 'ff8c00',
        darkorchid: '9932cc',
        darkred: '8b0000',
        darksalmon: 'e9967a',
        darkseagreen: '8fbc8f',
        darkslateblue: '483d8b',
        darkslategray: '2f4f4f',
        darkslategrey: '2f4f4f',
        darkturquoise: '00ced1',
        darkviolet: '9400d3',
        deeppink: 'ff1493',
        deepskyblue: '00bfff',
        dimgray: '696969',
        dimgrey: '696969',
        dodgerblue: '1e90ff',
        firebrick: 'b22222',
        floralwhite: 'fffaf0',
        forestgreen: '228b22',
        fuchsia: 'f0f',
        gainsboro: 'dcdcdc',
        ghostwhite: 'f8f8ff',
        gold: 'ffd700',
        goldenrod: 'daa520',
        gray: '808080',
        green: '008000',
        greenyellow: 'adff2f',
        grey: '808080',
        honeydew: 'f0fff0',
        hotpink: 'ff69b4',
        indianred: 'cd5c5c',
        indigo: '4b0082',
        ivory: 'fffff0',
        khaki: 'f0e68c',
        lavender: 'e6e6fa',
        lavenderblush: 'fff0f5',
        lawngreen: '7cfc00',
        lemonchiffon: 'fffacd',
        lightblue: 'add8e6',
        lightcoral: 'f08080',
        lightcyan: 'e0ffff',
        lightgoldenrodyellow: 'fafad2',
        lightgray: 'd3d3d3',
        lightgreen: '90ee90',
        lightgrey: 'd3d3d3',
        lightpink: 'ffb6c1',
        lightsalmon: 'ffa07a',
        lightseagreen: '20b2aa',
        lightskyblue: '87cefa',
        lightslategray: '789',
        lightslategrey: '789',
        lightsteelblue: 'b0c4de',
        lightyellow: 'ffffe0',
        lime: '0f0',
        limegreen: '32cd32',
        linen: 'faf0e6',
        magenta: 'f0f',
        maroon: '800000',
        mediumaquamarine: '66cdaa',
        mediumblue: '0000cd',
        mediumorchid: 'ba55d3',
        mediumpurple: '9370db',
        mediumseagreen: '3cb371',
        mediumslateblue: '7b68ee',
        mediumspringgreen: '00fa9a',
        mediumturquoise: '48d1cc',
        mediumvioletred: 'c71585',
        midnightblue: '191970',
        mintcream: 'f5fffa',
        mistyrose: 'ffe4e1',
        moccasin: 'ffe4b5',
        navajowhite: 'ffdead',
        navy: '000080',
        oldlace: 'fdf5e6',
        olive: '808000',
        olivedrab: '6b8e23',
        orange: 'ffa500',
        orangered: 'ff4500',
        orchid: 'da70d6',
        palegoldenrod: 'eee8aa',
        palegreen: '98fb98',
        paleturquoise: 'afeeee',
        palevioletred: 'db7093',
        papayawhip: 'ffefd5',
        peachpuff: 'ffdab9',
        peru: 'cd853f',
        pink: 'ffc0cb',
        plum: 'dda0dd',
        powderblue: 'b0e0e6',
        purple: '800080',
        rebeccapurple: '663399',
        red: 'f00',
        rosybrown: 'bc8f8f',
        royalblue: '4169e1',
        saddlebrown: '8b4513',
        salmon: 'fa8072',
        sandybrown: 'f4a460',
        seagreen: '2e8b57',
        seashell: 'fff5ee',
        sienna: 'a0522d',
        silver: 'c0c0c0',
        skyblue: '87ceeb',
        slateblue: '6a5acd',
        slategray: '708090',
        slategrey: '708090',
        snow: 'fffafa',
        springgreen: '00ff7f',
        steelblue: '4682b4',
        tan: 'd2b48c',
        teal: '008080',
        thistle: 'd8bfd8',
        tomato: 'ff6347',
        turquoise: '40e0d0',
        violet: 'ee82ee',
        wheat: 'f5deb3',
        white: 'fff',
        whitesmoke: 'f5f5f5',
        yellow: 'ff0',
        yellowgreen: '9acd32',
    });
    // Make it easy to access colors via `hexNames[hex]`
    var hexNames = (tinycolor.hexNames = flip(names));
    // Utilities
    // ---------
    // `{ 'name1': 'val1' }` becomes `{ 'val1': 'name1' }`
    function flip(o) {
        var flipped = {};
        for (var i in o) {
            if (o.hasOwnProperty(i)) {
                flipped[o[i]] = i;
            }
        }
        return flipped;
    }
    // Return a valid alpha value [0,1] with all invalid values being set to 1
    function boundAlpha(a) {
        a = parseFloat(a);
        if (isNaN(a) || a < 0 || a > 1) {
            a = 1;
        }
        return a;
    }
    // Take input from [0, n] and return it as [0, 1]
    function bound01(n, max) {
        if (isOnePointZero(n)) {
            n = '100%';
        }
        var processPercent = isPercentage(n);
        n = mathMin(max, mathMax(0, parseFloat(n)));
        // Automatically convert percentage into number
        if (processPercent) {
            n = parseInt(n * max, 10) / 100;
        }
        // Handle floating point rounding errors
        if (math.abs(n - max) < 0.000001) {
            return 1;
        }
        // Convert into [0, 1] range if it isn't already
        return (n % max) / parseFloat(max);
    }
    // Force a number between 0 and 1
    function clamp01(val) {
        return mathMin(1, mathMax(0, val));
    }
    // Parse a base-16 hex value into a base-10 integer
    function parseIntFromHex(val) {
        return parseInt(val, 16);
    }
    // Need to handle 1.0 as 100%, since once it is a number, there is no difference between it and 1
    // <http://stackoverflow.com/questions/7422072/javascript-how-to-detect-number-as-a-decimal-including-1-0>
    function isOnePointZero(n) {
        return typeof n == 'string' && n.indexOf('.') != -1 && parseFloat(n) === 1;
    }
    // Check to see if string passed in is a percentage
    function isPercentage(n) {
        return typeof n === 'string' && n.indexOf('%') != -1;
    }
    // Force a hex value to have 2 characters
    function pad2(c) {
        return c.length == 1 ? '0' + c : '' + c;
    }
    // Replace a decimal with it's percentage value
    function convertToPercentage(n) {
        if (n <= 1) {
            n = n * 100 + '%';
        }
        return n;
    }
    // Converts a decimal to a hex value
    function convertDecimalToHex(d) {
        return Math.round(parseFloat(d) * 255).toString(16);
    }
    // Converts a hex value to a decimal
    function convertHexToDecimal(h) {
        return parseIntFromHex(h) / 255;
    }
    var matchers = (function () {
        // <http://www.w3.org/TR/css3-values/#integers>
        var CSS_INTEGER = '[-\\+]?\\d+%?';
        // <http://www.w3.org/TR/css3-values/#number-value>
        var CSS_NUMBER = '[-\\+]?\\d*\\.\\d+%?';
        // Allow positive/negative integer/number.  Don't capture the either/or, just the entire outcome.
        var CSS_UNIT = '(?:' + CSS_NUMBER + ')|(?:' + CSS_INTEGER + ')';
        // Actual matching.
        // Parentheses and commas are optional, but not required.
        // Whitespace can take the place of commas or opening paren
        var PERMISSIVE_MATCH3 = '[\\s|\\(]+(' + CSS_UNIT + ')[,|\\s]+(' + CSS_UNIT + ')[,|\\s]+(' + CSS_UNIT + ')\\s*\\)?';
        var PERMISSIVE_MATCH4 = '[\\s|\\(]+(' +
            CSS_UNIT +
            ')[,|\\s]+(' +
            CSS_UNIT +
            ')[,|\\s]+(' +
            CSS_UNIT +
            ')[,|\\s]+(' +
            CSS_UNIT +
            ')\\s*\\)?';
        return {
            rgb: new RegExp('rgb' + PERMISSIVE_MATCH3),
            rgba: new RegExp('rgba' + PERMISSIVE_MATCH4),
            hsl: new RegExp('hsl' + PERMISSIVE_MATCH3),
            hsla: new RegExp('hsla' + PERMISSIVE_MATCH4),
            hsv: new RegExp('hsv' + PERMISSIVE_MATCH3),
            hsva: new RegExp('hsva' + PERMISSIVE_MATCH4),
            hex3: /^([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,
            hex6: /^([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,
            hex8: /^([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,
        };
    })();
    // `stringInputToObject`
    // Permissive string parsing.  Take in a number of formats, and output an object
    // based on detected format.  Returns `{ r, g, b }` or `{ h, s, l }` or `{ h, s, v}`
    function stringInputToObject(color) {
        color = color.replace(trimLeft, '').replace(trimRight, '').toLowerCase();
        var named = false;
        if (names[color]) {
            color = names[color];
            named = true;
        }
        else if (color == 'transparent') {
            return { r: 0, g: 0, b: 0, a: 0, format: 'name' };
        }
        // Try to match string input using regular expressions.
        // Keep most of the number bounding out of this function - don't worry about [0,1] or [0,100] or [0,360]
        // Just return an object and let the conversion functions handle that.
        // This way the result will be the same whether the tinycolor is initialized with string or object.
        var match;
        if ((match = matchers.rgb.exec(color))) {
            return { r: match[1], g: match[2], b: match[3] };
        }
        if ((match = matchers.rgba.exec(color))) {
            return { r: match[1], g: match[2], b: match[3], a: match[4] };
        }
        if ((match = matchers.hsl.exec(color))) {
            return { h: match[1], s: match[2], l: match[3] };
        }
        if ((match = matchers.hsla.exec(color))) {
            return { h: match[1], s: match[2], l: match[3], a: match[4] };
        }
        if ((match = matchers.hsv.exec(color))) {
            return { h: match[1], s: match[2], v: match[3] };
        }
        if ((match = matchers.hsva.exec(color))) {
            return { h: match[1], s: match[2], v: match[3], a: match[4] };
        }
        if ((match = matchers.hex8.exec(color))) {
            return {
                a: convertHexToDecimal(match[1]),
                r: parseIntFromHex(match[2]),
                g: parseIntFromHex(match[3]),
                b: parseIntFromHex(match[4]),
                format: named ? 'name' : 'hex8',
            };
        }
        if ((match = matchers.hex6.exec(color))) {
            return {
                r: parseIntFromHex(match[1]),
                g: parseIntFromHex(match[2]),
                b: parseIntFromHex(match[3]),
                format: named ? 'name' : 'hex',
            };
        }
        if ((match = matchers.hex3.exec(color))) {
            return {
                r: parseIntFromHex(match[1] + '' + match[1]),
                g: parseIntFromHex(match[2] + '' + match[2]),
                b: parseIntFromHex(match[3] + '' + match[3]),
                format: named ? 'name' : 'hex',
            };
        }
        return false;
    }
    window.tinycolor = tinycolor;
    //})();
    $(function () {
        if ($.fn.spectrum.load) {
            $.fn.spectrum.processNativeColorInputs();
        }
    });
}

;// CONCATENATED MODULE: ./src/domain_abstract/ui/Input.ts
var Input_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();

var Input = /** @class */ (function (_super) {
    Input_extends(Input, _super);
    function Input(opts) {
        if (opts === void 0) { opts = {}; }
        var _this = _super.call(this, opts) || this;
        var ppfx = opts.ppfx || '';
        _this.opts = opts;
        _this.ppfx = ppfx;
        _this.em = opts.target || {};
        !opts.onChange && _this.listenTo(_this.model, 'change:value', _this.handleModelChange);
        return _this;
    }
    Input.prototype.template = function () {
        return "<span class=\"".concat(this.holderClass(), "\"></span>");
    };
    Input.prototype.inputClass = function () {
        return "".concat(this.ppfx, "field");
    };
    Input.prototype.holderClass = function () {
        return "".concat(this.ppfx, "input-holder");
    };
    /**
     * Fired when the element of the property is updated
     */
    Input.prototype.elementUpdated = function () {
        this.model.trigger('el:change');
    };
    /**
     * Set value to the input element
     * @param {string} value
     */
    Input.prototype.setValue = function (value, opts) {
        var model = this.model;
        var val = value || model.get('defaults');
        var input = this.getInputEl();
        input && (input.value = val);
    };
    /**
     * Updates the view when the model is changed
     * */
    Input.prototype.handleModelChange = function (model, value, opts) {
        this.setValue(value, opts);
    };
    /**
     * Handled when the view is changed
     */
    Input.prototype.handleChange = function (e) {
        e.stopPropagation();
        var value = this.getInputEl().value;
        this.__onInputChange(value);
        this.elementUpdated();
    };
    Input.prototype.__onInputChange = function (value) {
        this.model.set({ value: value }, { fromInput: 1 });
    };
    /**
     * Get the input element
     * @return {HTMLElement}
     */
    Input.prototype.getInputEl = function () {
        if (!this.inputEl) {
            var _a = this, model = _a.model, opts = _a.opts;
            var type = opts.type || 'text';
            var plh = model.get('placeholder') || model.get('defaults') || model.get('default') || '';
            this.inputEl = (0,cash_dom["default"])("<input type=\"".concat(type, "\" placeholder=\"").concat(plh, "\">"));
        }
        return this.inputEl.get(0);
    };
    Input.prototype.render = function () {
        this.inputEl = null;
        var el = this.$el;
        el.addClass(this.inputClass());
        el.html(this.template());
        el.find(".".concat(this.holderClass())).append(this.getInputEl());
        return this;
    };
    return Input;
}(common/* View */.G7));
/* harmony default export */ const ui_Input = (Input);
Input.prototype.events = {
    // @ts-ignore
    change: 'handleChange',
};

;// CONCATENATED MODULE: ./src/domain_abstract/ui/InputColor.ts
var InputColor_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var InputColor_assign = (undefined && undefined.__assign) || function () {
    InputColor_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return InputColor_assign.apply(this, arguments);
};




cash_dom["default"] && ColorPicker(cash_dom["default"]);
var getColor = function (color) {
    var name = color.getFormat() === 'name' && color.toName();
    var cl = color.getAlpha() == 1 ? color.toHexString() : color.toRgbString();
    return name || cl.replace(/ /g, '');
};
var InputColor = /** @class */ (function (_super) {
    InputColor_extends(InputColor, _super);
    function InputColor() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    InputColor.prototype.template = function () {
        var ppfx = this.ppfx;
        return "\n      <div class=\"".concat(this.holderClass(), "\"></div>\n      <div class=\"").concat(ppfx, "field-colorp\">\n        <div class=\"").concat(ppfx, "field-colorp-c\" data-colorp-c>\n          <div class=\"").concat(ppfx, "checker-bg\"></div>\n        </div>\n      </div>\n    ");
    };
    InputColor.prototype.inputClass = function () {
        var ppfx = this.ppfx;
        return "".concat(ppfx, "field ").concat(ppfx, "field-color");
    };
    InputColor.prototype.holderClass = function () {
        return "".concat(this.ppfx, "input-holder");
    };
    InputColor.prototype.remove = function () {
        _super.prototype.remove.call(this);
        this.colorEl.spectrum('destroy');
        return this;
    };
    InputColor.prototype.handleChange = function (e) {
        e.stopPropagation();
        var value = e.target.value;
        if ((0,index_all.isUndefined)(value))
            return;
        this.__onInputChange(value);
    };
    InputColor.prototype.__onInputChange = function (val) {
        var _a = this, model = _a.model, opts = _a.opts;
        var onChange = opts.onChange;
        var value = val;
        var colorEl = this.getColorEl();
        // Check the color by using the ColorPicker's parser
        if (colorEl) {
            colorEl.spectrum('set', value);
            var tc = colorEl.spectrum('get');
            var color = value && getColor(tc);
            color && (value = color);
        }
        onChange ? onChange(value) : model.set({ value: value }, { fromInput: 1 });
    };
    /**
     * Set value to the model
     * @param {string} val
     * @param {Object} opts
     */
    InputColor.prototype.setValue = function (val, opts) {
        if (opts === void 0) { opts = {}; }
        var model = this.model;
        var def = !(0,index_all.isUndefined)(opts.def) ? opts.def : model.get('defaults');
        var value = !(0,index_all.isUndefined)(val) ? val : !(0,index_all.isUndefined)(def) ? def : '';
        var inputEl = this.getInputEl();
        var colorEl = this.getColorEl();
        var valueClr = value != 'none' ? value : '';
        inputEl.value = value;
        colorEl.get(0).style.backgroundColor = valueClr;
        // This prevents from adding multiple thumbs in spectrum
        if (opts.fromTarget || (opts.fromInput && !opts.avoidStore)) {
            colorEl.spectrum('set', valueClr);
            this.noneColor = value == 'none';
            this.movedColor = valueClr;
        }
    };
    /**
     * Get the color input element
     * @return {HTMLElement}
     */
    InputColor.prototype.getColorEl = function () {
        var _this = this;
        if (!this.colorEl) {
            var _a = this, em = _a.em, model_1 = _a.model, opts = _a.opts;
            var ppfx = this.ppfx;
            var onChange_1 = opts.onChange;
            var colorEl_1 = (0,cash_dom["default"])("<div class=\"".concat(this.ppfx, "field-color-picker\"></div>"));
            var cpStyle_1 = colorEl_1.get(0).style;
            var colorPickerConfig = (em && em.getConfig && em.getConfig().colorPicker) || {};
            this.movedColor = '';
            var changed_1 = false;
            var previousColor_1;
            this.$el.find('[data-colorp-c]').append(colorEl_1);
            var handleChange_1 = function (value, complete) {
                if (complete === void 0) { complete = true; }
                if (onChange_1) {
                    onChange_1(value, !complete);
                }
                else {
                    complete && model_1.setValueFromInput(0, false); // for UndoManager
                    model_1.setValueFromInput(value, complete);
                }
            };
            // @ts-ignore
            colorEl_1.spectrum(InputColor_assign(InputColor_assign(InputColor_assign({ color: model_1.getValue() || false, containerClassName: "".concat(ppfx, "one-bg ").concat(ppfx, "two-color ").concat(ppfx, "editor-sp"), maxSelectionSize: 8, showPalette: true, showAlpha: true, chooseText: 'Ok', cancelText: '⨯', palette: [] }, colorPickerConfig), (model_1.get('colorPicker') || {})), { move: function (color) {
                    var cl = getColor(color);
                    _this.movedColor = cl;
                    cpStyle_1.backgroundColor = cl;
                    handleChange_1(cl, false);
                }, change: function (color) {
                    changed_1 = true;
                    var cl = getColor(color);
                    cpStyle_1.backgroundColor = cl;
                    handleChange_1(cl);
                    _this.noneColor = false;
                }, show: function (color) {
                    changed_1 = false;
                    _this.movedColor = '';
                    previousColor_1 = onChange_1 ? model_1.getValue({ noDefault: true }) : getColor(color);
                }, hide: function () {
                    if (!changed_1 && (previousColor_1 || onChange_1)) {
                        if (_this.noneColor) {
                            previousColor_1 = '';
                        }
                        cpStyle_1.backgroundColor = previousColor_1;
                        // @ts-ignore
                        colorEl_1.spectrum('set', previousColor_1);
                        handleChange_1(previousColor_1, false);
                    }
                } }));
            if (em && em.on) {
                this.listenTo(em, 'component:selected', function () {
                    _this.movedColor && handleChange_1(_this.movedColor);
                    changed_1 = true;
                    _this.movedColor = '';
                    // @ts-ignore
                    colorEl_1.spectrum('hide');
                });
            }
            this.colorEl = colorEl_1;
        }
        return this.colorEl;
    };
    InputColor.prototype.render = function () {
        ui_Input.prototype.render.call(this);
        // This will make the color input available on render
        this.getColorEl();
        return this;
    };
    return InputColor;
}(ui_Input));
/* harmony default export */ const ui_InputColor = (InputColor);

;// CONCATENATED MODULE: ./src/trait_manager/view/TraitColorView.ts
var TraitColorView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();


var TraitColorView = /** @class */ (function (_super) {
    TraitColorView_extends(TraitColorView, _super);
    function TraitColorView() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    TraitColorView.prototype.templateInput = function () {
        return '';
    };
    /**
     * Returns input element
     * @return {HTMLElement}
     * @private
     */
    TraitColorView.prototype.getInputEl = function () {
        if (!this.input) {
            var model = this.model;
            var value = this.getModelValue();
            var inputColor = new ui_InputColor({
                model: model,
                target: this.config.em,
                contClass: this.ppfx + 'field-color',
                ppfx: this.ppfx,
            });
            var input = inputColor.render();
            input.setValue(value, { fromTarget: 1 });
            this.input = input.el;
        }
        return this.input;
    };
    return TraitColorView;
}(view_TraitView));
/* harmony default export */ const view_TraitColorView = (TraitColorView);

;// CONCATENATED MODULE: ./src/domain_abstract/ui/InputNumber.ts
var InputNumber_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();



var InputNumber = /** @class */ (function (_super) {
    InputNumber_extends(InputNumber, _super);
    function InputNumber(opts) {
        if (opts === void 0) { opts = {}; }
        var _this = _super.call(this, opts) || this;
        (0,index_all.bindAll)(_this, 'moveIncrement', 'upIncrement');
        _this.doc = document;
        _this.listenTo(_this.model, 'change:unit', _this.handleModelChange);
        return _this;
    }
    InputNumber.prototype.template = function () {
        var ppfx = this.ppfx;
        return "\n      <span class=\"".concat(ppfx, "input-holder\"></span>\n      <span class=\"").concat(ppfx, "field-units\"></span>\n      <div class=\"").concat(ppfx, "field-arrows\" data-arrows>\n        <div class=\"").concat(ppfx, "field-arrow-u\" data-arrow-up></div>\n        <div class=\"").concat(ppfx, "field-arrow-d\" data-arrow-down></div>\n      </div>\n    ");
    };
    InputNumber.prototype.inputClass = function () {
        var ppfx = this.ppfx;
        return this.opts.contClass || "".concat(ppfx, "field ").concat(ppfx, "field-integer");
    };
    /**
     * Set value to the model
     * @param {string} value
     * @param {Object} opts
     */
    InputNumber.prototype.setValue = function (value, opts) {
        var opt = opts || {};
        var valid = this.validateInputValue(value, { deepCheck: 1 });
        var validObj = { value: valid.value, unit: '' };
        // If found some unit value
        if (valid.unit || valid.force) {
            validObj.unit = valid.unit;
        }
        this.model.set(validObj, opt);
        // Generally I get silent when I need to reflect data to view without
        // reupdating the target
        if (opt.silent) {
            this.handleModelChange();
        }
    };
    /**
     * Handled when the view is changed
     */
    InputNumber.prototype.handleChange = function (e) {
        e.stopPropagation();
        this.setValue(this.getInputEl().value);
        this.elementUpdated();
    };
    /**
     * Handled when the view is changed
     */
    InputNumber.prototype.handleUnitChange = function (e) {
        e.stopPropagation();
        var value = this.getUnitEl().value;
        this.model.set('unit', value);
        this.elementUpdated();
    };
    /**
     * Handled when user uses keyboard
     */
    InputNumber.prototype.handleKeyDown = function (e) {
        if (e.key === 'ArrowUp') {
            e.preventDefault();
            this.upArrowClick();
        }
        if (e.key === 'ArrowDown') {
            e.preventDefault();
            this.downArrowClick();
        }
    };
    /**
     * Fired when the element of the property is updated
     */
    InputNumber.prototype.elementUpdated = function () {
        this.model.trigger('el:change');
    };
    /**
     * Updates the view when the model is changed
     * */
    InputNumber.prototype.handleModelChange = function () {
        var model = this.model;
        this.getInputEl().value = model.get('value');
        var unitEl = this.getUnitEl();
        unitEl && (unitEl.value = model.get('unit') || '');
    };
    /**
     * Get the unit element
     * @return {HTMLElement}
     */
    InputNumber.prototype.getUnitEl = function () {
        if (!this.unitEl) {
            var model_1 = this.model;
            var units = model_1.get('units') || [];
            if (units.length) {
                var options_1 = ['<option value="" disabled hidden>-</option>'];
                units.forEach(function (unit) {
                    var selected = unit == model_1.get('unit') ? 'selected' : '';
                    options_1.push("<option ".concat(selected, ">").concat(unit, "</option>"));
                });
                var temp = document.createElement('div');
                temp.innerHTML = "<select class=\"".concat(this.ppfx, "input-unit\">").concat(options_1.join(''), "</select>");
                this.unitEl = temp.firstChild;
            }
        }
        return this.unitEl;
    };
    /**
     * Invoked when the up arrow is clicked
     * */
    InputNumber.prototype.upArrowClick = function () {
        var model = this.model;
        var step = model.get('step');
        var value = parseFloat(model.get('value'));
        this.setValue(this.normalizeValue(value + step));
        this.elementUpdated();
    };
    /**
     * Invoked when the down arrow is clicked
     * */
    InputNumber.prototype.downArrowClick = function () {
        var model = this.model;
        var step = model.get('step');
        var value = parseFloat(model.get('value'));
        this.setValue(this.normalizeValue(value - step));
        this.elementUpdated();
    };
    /**
     * Change easily integer input value with click&drag method
     * @param Event
     *
     * @return void
     * */
    InputNumber.prototype.downIncrement = function (e) {
        e.preventDefault();
        this.moved = false;
        var value = this.model.get('value') || 0;
        value = this.normalizeValue(value);
        this.current = { y: e.pageY, val: value };
        (0,dom.on)(this.doc, 'mousemove', this.moveIncrement);
        (0,dom.on)(this.doc, 'mouseup', this.upIncrement);
    };
    /** While the increment is clicked, moving the mouse will update input value
     * @param Object
     *
     * @return bool
     * */
    InputNumber.prototype.moveIncrement = function (ev) {
        this.moved = true;
        var model = this.model;
        var step = model.get('step');
        var data = this.current;
        var pos = this.normalizeValue(data.val + (data.y - ev.pageY) * step);
        var _a = this.validateInputValue(pos), value = _a.value, unit = _a.unit;
        this.prValue = value;
        model.set({ value: value, unit: unit }, { avoidStore: 1 });
        return false;
    };
    /**
     * Stop moveIncrement method
     * */
    InputNumber.prototype.upIncrement = function () {
        var model = this.model;
        var step = model.get('step');
        (0,dom/* off */.S1)(this.doc, 'mouseup', this.upIncrement);
        (0,dom/* off */.S1)(this.doc, 'mousemove', this.moveIncrement);
        if (this.prValue && this.moved) {
            var value = this.prValue - step;
            // @ts-ignore
            model.set('value', value, { avoidStore: 1 }).set('value', value + step);
            this.elementUpdated();
        }
    };
    InputNumber.prototype.normalizeValue = function (value, defValue) {
        if (defValue === void 0) { defValue = 0; }
        var model = this.model;
        var step = model.get('step');
        var stepDecimals = 0;
        if (isNaN(value)) {
            return defValue;
        }
        value = parseFloat(value);
        if (Math.floor(value) !== value) {
            var side = step.toString().split('.')[1];
            stepDecimals = side ? side.length : 0;
        }
        return stepDecimals ? parseFloat(value.toFixed(stepDecimals)) : value;
    };
    /**
     * Validate input value
     * @param {String} value Raw value
     * @param {Object} opts Options
     * @return {Object} Validated string
     */
    InputNumber.prototype.validateInputValue = function (value, opts) {
        if (opts === void 0) { opts = {}; }
        var force = 0;
        var opt = opts || {};
        var model = this.model;
        var defValue = ''; //model.get('defaults');
        var val = !(0,index_all.isUndefined)(value) ? value : defValue;
        var units = opts.units || model.get('units') || [];
        var unit = model.get('unit') || (units.length && units[0]) || '';
        var max = !(0,index_all.isUndefined)(opts.max) ? opts.max : model.get('max');
        var min = !(0,index_all.isUndefined)(opts.min) ? opts.min : model.get('min');
        var limitlessMax = !!model.get('limitlessMax');
        var limitlessMin = !!model.get('limitlessMin');
        if (opt.deepCheck) {
            var fixed = model.get('fixedValues') || [];
            if (val === '')
                unit = '';
            if (val) {
                // If the value is one of the fixed values I leave it as it is
                var regFixed = new RegExp('^' + fixed.join('|'), 'g');
                if (fixed.length && regFixed.test(val)) {
                    val = val.match(regFixed)[0];
                    unit = '';
                    force = 1;
                }
                else {
                    var valCopy = val + '';
                    val += ''; // Make it suitable for replace
                    val = parseFloat(val.replace(',', '.'));
                    val = !isNaN(val) ? val : defValue;
                    var uN = valCopy.replace(val, '');
                    // Check if exists as unit
                    if ((0,index_all.indexOf)(units, uN) >= 0)
                        unit = uN;
                }
            }
        }
        if (!limitlessMax && !(0,index_all.isUndefined)(max) && max !== '')
            val = val > max ? max : val;
        if (!limitlessMin && !(0,index_all.isUndefined)(min) && min !== '')
            val = val < min ? min : val;
        return {
            force: force,
            value: val,
            unit: unit,
        };
    };
    InputNumber.prototype.render = function () {
        ui_Input.prototype.render.call(this);
        this.unitEl = null;
        var unit = this.getUnitEl();
        unit && this.$el.find(".".concat(this.ppfx, "field-units")).get(0).appendChild(unit);
        return this;
    };
    return InputNumber;
}(ui_Input));
/* harmony default export */ const ui_InputNumber = (InputNumber);
InputNumber.prototype.events = {
    // @ts-ignore
    'change input': 'handleChange',
    'change select': 'handleUnitChange',
    'click [data-arrow-up]': 'upArrowClick',
    'click [data-arrow-down]': 'downArrowClick',
    'mousedown [data-arrows]': 'downIncrement',
    keydown: 'handleKeyDown',
};

;// CONCATENATED MODULE: ./src/trait_manager/view/TraitNumberView.ts
var TraitNumberView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();



var TraitNumberView = /** @class */ (function (_super) {
    TraitNumberView_extends(TraitNumberView, _super);
    function TraitNumberView() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    TraitNumberView.prototype.getValueForTarget = function () {
        var model = this.model;
        var _a = model.attributes, value = _a.value, unit = _a.unit;
        return !(0,index_all.isUndefined)(value) && value !== '' ? value + unit : model.get('default');
    };
    /**
     * Returns input element
     * @return {HTMLElement}
     * @private
     */
    TraitNumberView.prototype.getInputEl = function () {
        if (!this.input) {
            var _a = this, ppfx = _a.ppfx, model = _a.model;
            var value = this.getModelValue();
            var inputNumber = new ui_InputNumber({
                contClass: "".concat(ppfx, "field-int"),
                type: 'number',
                model: model,
                ppfx: ppfx,
            });
            inputNumber.render();
            this.$input = inputNumber.inputEl;
            this.$unit = inputNumber.unitEl;
            // @ts-ignore
            model.set('value', value, { fromTarget: true });
            this.$input.val(value);
            this.input = inputNumber.el;
        }
        return this.input;
    };
    return TraitNumberView;
}(view_TraitView));
/* harmony default export */ const view_TraitNumberView = (TraitNumberView);

;// CONCATENATED MODULE: ./src/trait_manager/view/TraitSelectView.ts
var TraitSelectView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();



var TraitSelectView = /** @class */ (function (_super) {
    TraitSelectView_extends(TraitSelectView, _super);
    function TraitSelectView(o) {
        if (o === void 0) { o = {}; }
        var _this = _super.call(this, o) || this;
        _this.listenTo(_this.model, 'change:options', _this.rerender);
        return _this;
    }
    TraitSelectView.prototype.templateInput = function () {
        var _a = this, ppfx = _a.ppfx, clsField = _a.clsField;
        return "<div class=\"".concat(clsField, "\">\n      <div data-input></div>\n      <div class=\"").concat(ppfx, "sel-arrow\">\n        <div class=\"").concat(ppfx, "d-s-arrow\"></div>\n      </div>\n    </div>");
    };
    /**
     * Returns input element
     * @return {HTMLElement}
     * @private
     */
    TraitSelectView.prototype.getInputEl = function () {
        if (!this.$input) {
            var _a = this, model = _a.model, em_1 = _a.em;
            var propName_1 = model.get('name');
            var opts = model.get('options') || [];
            var values_1 = [];
            var input_1 = '<select>';
            opts.forEach(function (el) {
                var attrs = '';
                var name, value, style;
                if ((0,index_all.isString)(el)) {
                    name = el;
                    value = el;
                }
                else {
                    name = el.name || el.label || el.value;
                    value = "".concat((0,index_all.isUndefined)(el.value) ? el.id : el.value).replace(/"/g, '&quot;');
                    style = el.style ? el.style.replace(/"/g, '&quot;') : '';
                    attrs += style ? " style=\"".concat(style, "\"") : '';
                }
                var resultName = em_1.t("traitManager.traits.options.".concat(propName_1, ".").concat(value)) || name;
                input_1 += "<option value=\"".concat(value, "\"").concat(attrs, ">").concat(resultName, "</option>");
                values_1.push(value);
            });
            input_1 += '</select>';
            this.$input = (0,cash_dom["default"])(input_1);
            var val = model.getTargetValue();
            var valResult = values_1.indexOf(val) >= 0 ? val : model.get('default');
            !(0,index_all.isUndefined)(valResult) && this.$input.val(valResult);
        }
        return this.$input.get(0);
    };
    return TraitSelectView;
}(view_TraitView));
/* harmony default export */ const view_TraitSelectView = (TraitSelectView);

// EXTERNAL MODULE: ./src/domain_abstract/view/DomainViews.ts
var DomainViews = __webpack_require__(330);
;// CONCATENATED MODULE: ./src/trait_manager/view/TraitsView.ts
var TraitsView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();




var ATTR_CATEGORIES = 'data-categories';
var ATTR_NO_CATEGORIES = 'data-no-categories';
var TraitsView = /** @class */ (function (_super) {
    TraitsView_extends(TraitsView, _super);
    function TraitsView(props, itemsView) {
        var _this = _super.call(this, props) || this;
        _this.reuseView = true;
        _this.renderedCategories = new Map();
        _this.itemsView = itemsView;
        var config = props.config || {};
        _this.config = config;
        var em = props.editor;
        _this.em = em;
        var ppfx = config.pStylePrefix || '';
        _this.ppfx = ppfx;
        _this.pfx = ppfx + config.stylePrefix || '';
        _this.className = "".concat(_this.pfx, "traits");
        _this.traitContClass = "".concat(ppfx, "traits-c");
        _this.classNoCat = "".concat(ppfx, "traits-empty-c");
        _this.catsClass = "".concat(ppfx, "trait-categories");
        _this.collection = new model_Traits([], { em: em });
        _this.listenTo(em, 'component:toggled', _this.updatedCollection);
        _this.updatedCollection();
        return _this;
    }
    /**
     * Update view collection
     * @private
     */
    TraitsView.prototype.updatedCollection = function () {
        var _a = this, ppfx = _a.ppfx, em = _a.em;
        var comp = em.getSelected();
        this.el.className = "".concat(this.traitContClass, "s ").concat(ppfx, "one-bg ").concat(ppfx, "two-color");
        this.collection = (comp === null || comp === void 0 ? void 0 : comp.traits) || new model_Traits([], { em: em });
        this.render();
    };
    /**
     * Render new model inside the view
     * @param {Model} model
     * @param {Object} fragment Fragment collection
     * @private
     * */
    TraitsView.prototype.add = function (model, fragment) {
        var _a = this, config = _a.config, renderedCategories = _a.renderedCategories;
        var itemView = this.itemView;
        var typeField = model.get(this.itemType);
        if (this.itemsView && this.itemsView[typeField]) {
            itemView = this.itemsView[typeField];
        }
        var view = new itemView({
            config: config,
            model: model,
            attributes: model.get('attributes'),
        });
        var rendered = view.render().el;
        var category = model.parent.initCategory(model);
        if (category) {
            var catId = category.getId();
            var categories = this.getCategoriesEl();
            var catView = renderedCategories.get(catId);
            if (!catView && categories) {
                catView = new ModuleCategoryView({ model: category }, config, 'trait').render();
                renderedCategories.set(catId, catView);
                categories.appendChild(catView.el);
            }
            catView === null || catView === void 0 ? void 0 : catView.append(rendered);
            return;
        }
        fragment ? fragment.appendChild(rendered) : this.append(rendered);
    };
    TraitsView.prototype.getCategoriesEl = function () {
        if (!this.catsEl) {
            this.catsEl = this.el.querySelector("[".concat(ATTR_CATEGORIES, "]"));
        }
        return this.catsEl;
    };
    TraitsView.prototype.getTraitsEl = function () {
        if (!this.traitsEl) {
            this.traitsEl = this.el.querySelector("[".concat(ATTR_NO_CATEGORIES, "]"));
        }
        return this.traitsEl;
    };
    TraitsView.prototype.append = function (el) {
        var traits = this.getTraitsEl();
        traits === null || traits === void 0 ? void 0 : traits.appendChild(el);
    };
    TraitsView.prototype.render = function () {
        var _this = this;
        var _a = this, el = _a.el, ppfx = _a.ppfx, catsClass = _a.catsClass, traitContClass = _a.traitContClass, classNoCat = _a.classNoCat;
        var frag = document.createDocumentFragment();
        delete this.catsEl;
        delete this.traitsEl;
        this.renderedCategories = new Map();
        el.innerHTML = "\n      <div class=\"".concat(catsClass, "\" ").concat(ATTR_CATEGORIES, "></div>\n      <div class=\"").concat(classNoCat, " ").concat(traitContClass, "\" ").concat(ATTR_NO_CATEGORIES, "></div>\n    ");
        this.collection.forEach(function (model) { return _this.add(model, frag); });
        this.append(frag);
        var cls = "".concat(traitContClass, "s ").concat(ppfx, "one-bg ").concat(ppfx, "two-color");
        this.$el.addClass(cls);
        this.rendered = true;
        return this;
    };
    return TraitsView;
}(DomainViews/* default */.Z));
/* harmony default export */ const view_TraitsView = (TraitsView);
TraitsView.prototype.itemView = view_TraitView;

;// CONCATENATED MODULE: ./src/trait_manager/index.ts
/**
 * You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](https://github.com/GrapesJS/grapesjs/blob/master/src/trait_manager/config/config.ts)
 * ```js
 * const editor = grapesjs.init({
 *  traitManager: {
 *    // options
 *  }
 * })
 * ```
 *
 *
 * Once the editor is instantiated you can use the API below and listen to the events. Before using these methods, you should get the module from the instance.
 *
 * ```js
 * // Listen to events
 * editor.on('trait:value', () => { ... });
 *
 * // Use the Trait Manager API
 * const tm = editor.Traits;
 * tm.select(...)
 * ```
 *
 * {REPLACE_EVENTS}
 *
 * [Component]: component.html
 * [Trait]: trait.html
 *
 * @module Traits
 */
var trait_manager_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var trait_manager_spreadArray = (undefined && undefined.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};













var TraitManager = /** @class */ (function (_super) {
    trait_manager_extends(TraitManager, _super);
    /**
     * Get configuration object
     * @name getConfig
     * @function
     * @returns {Object}
     */
    /**
     * Initialize module
     * @private
     */
    function TraitManager(em) {
        var _this = _super.call(this, em, 'TraitManager', trait_manager_config_config) || this;
        _this.TraitsView = view_TraitsView;
        _this.events = TraitsEvents;
        _this.state = new common/* Model */.Hn({ traits: [] });
        _this.types = {
            text: view_TraitView,
            number: view_TraitNumberView,
            select: view_TraitSelectView,
            checkbox: view_TraitCheckboxView,
            color: view_TraitColorView,
            button: view_TraitButtonView,
        };
        var _a = _this, state = _a.state, config = _a.config, events = _a.events;
        var ppfx = config.pStylePrefix;
        ppfx && (config.stylePrefix = "".concat(ppfx).concat(config.stylePrefix));
        (0,index_all.bindAll)(_this, '__onSelect');
        var upAll = (0,index_all.debounce)(function () { return _this.__upSel(); }, 0);
        var update = (0,index_all.debounce)(function () { return _this.__onUp(); }, 0);
        state.listenTo(em, 'component:toggled', upAll);
        state.listenTo(em, events.value, update);
        state.on('change:traits', _this.__onSelect);
        _this.debounced = [upAll, update];
        return _this;
    }
    /**
     * Select traits from a component.
     * @param {[Component]} component
     * @example
     * tm.select(someComponent);
     */
    TraitManager.prototype.select = function (component) {
        var traits = (component === null || component === void 0 ? void 0 : component.getTraits()) || [];
        this.state.set({ component: component, traits: traits });
        this.__trgCustom();
    };
    /**
     * Get trait categories from the currently selected component.
     * @returns {Array<Category>}
     * @example
     * const traitCategories: Category[] = tm.getCategories();
     *
     */
    TraitManager.prototype.getCategories = function () {
        var _a;
        var cmp = this.getComponent();
        var categories = ((_a = cmp === null || cmp === void 0 ? void 0 : cmp.traits.categories) === null || _a === void 0 ? void 0 : _a.models) || [];
        return trait_manager_spreadArray([], categories, true);
    };
    /**
     * Get traits from the currently selected component.
     * @returns {Array<[Trait]>}
     * @example
     * const currentTraits: Trait[] = tm.getTraits();
     */
    TraitManager.prototype.getTraits = function () {
        return this.getCurrent();
    };
    /**
     * Get traits by category from the currently selected component.
     * @example
     * tm.getTraitsByCategory();
     * // Returns an array of items of this type
     * // > { category?: Category; items: Trait[] }
     *
     * // NOTE: The item without category is the one containing traits without category.
     *
     * // You can also get the same output format by passing your own array of Traits
     * const myFilteredTraits: Trait[] = [...];
     * tm.getTraitsByCategory(myFilteredTraits);
     */
    TraitManager.prototype.getTraitsByCategory = function (traits) {
        return getItemsByCategory(traits || this.getTraits());
    };
    /**
     * Get component from the currently selected traits.
     * @example
     * tm.getComponent();
     * // Component {}
     */
    TraitManager.prototype.getComponent = function () {
        return this.state.attributes.component;
    };
    /**
     * Add new trait type.
     * More about it here: [Define new Trait type](https://grapesjs.com/docs/modules/Traits.html#define-new-trait-type).
     * @param {string} name Type name.
     * @param {Object} methods Object representing the trait.
     */
    TraitManager.prototype.addType = function (name, methods) {
        var baseView = this.getType('text');
        //@ts-ignore
        this.types[name] = baseView.extend(methods);
    };
    /**
     * Get trait type
     * @param {string} name Type name
     * @returns {Object}
     * @private
     * const traitView = tm.getType('text');
     */
    TraitManager.prototype.getType = function (name) {
        return this.getTypes()[name];
    };
    /**
     * Get all trait types
     * @returns {Object}
     * @private
     */
    TraitManager.prototype.getTypes = function () {
        return this.types;
    };
    /**
     *
     * Get Traits viewer
     * @private
     */
    TraitManager.prototype.getTraitsViewer = function () {
        return this.view;
    };
    TraitManager.prototype.getCurrent = function () {
        return this.state.get('traits') || [];
    };
    TraitManager.prototype.render = function () {
        var view = this.view;
        var em = this.em;
        view = new view_TraitsView({
            el: view === null || view === void 0 ? void 0 : view.el,
            collection: [],
            editor: em,
            config: this.getConfig(),
        }, this.getTypes());
        this.view = view;
        return view.el;
    };
    TraitManager.prototype.postRender = function () {
        this.__appendTo();
    };
    TraitManager.prototype.__onSelect = function () {
        var _a = this, em = _a.em, events = _a.events, state = _a.state;
        var _b = state.attributes, component = _b.component, traits = _b.traits;
        em.trigger(events.select, { component: component, traits: traits });
    };
    TraitManager.prototype.__trgCustom = function (opts) {
        if (opts === void 0) { opts = {}; }
        var _a = this, em = _a.em, events = _a.events, __ctn = _a.__ctn;
        this.__ctn = __ctn || opts.container;
        em.trigger(events.custom, this.__customData());
    };
    TraitManager.prototype.__customData = function () {
        return { container: this.__ctn };
    };
    TraitManager.prototype.__upSel = function () {
        this.select(this.em.getSelected());
    };
    TraitManager.prototype.__onUp = function () {
        this.select(this.getComponent());
    };
    return TraitManager;
}(abstract_Module));
/* harmony default export */ const trait_manager = (TraitManager);

;// CONCATENATED MODULE: ./src/navigator/config/config.ts
var navigator_config_config_config = {
    stylePrefix: '',
    appendTo: '',
    sortable: true,
    hidable: true,
    hideTextnode: true,
    root: '',
    showWrapper: true,
    showHover: true,
    scrollCanvas: { behavior: 'smooth', block: 'nearest' },
    scrollLayers: { behavior: 'auto', block: 'nearest' },
    highlightHover: true,
    custom: false,
    onInit: function () { },
    onRender: function () { },
    extend: {},
};
/* harmony default export */ const navigator_config_config = (navigator_config_config_config);

;// CONCATENATED MODULE: ./src/navigator/view/ItemsView.ts
var ItemsView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();

var ItemsView = /** @class */ (function (_super) {
    ItemsView_extends(ItemsView, _super);
    function ItemsView(opt) {
        if (opt === void 0) { opt = {}; }
        var _this = _super.call(this, opt) || this;
        _this.items = [];
        _this.opt = opt;
        var config = opt.config || {};
        _this.config = config;
        _this.parentView = opt.parentView;
        var pfx = config.stylePrefix || '';
        var ppfx = config.pStylePrefix || '';
        var coll = _this.collection;
        _this.listenTo(coll, 'add', _this.addTo);
        _this.listenTo(coll, 'reset resetNavigator', _this.render);
        _this.listenTo(coll, 'remove', _this.removeChildren);
        _this.className = "".concat(pfx, "layers");
        var em = config.em;
        if (config.sortable && !_this.opt.sorter) {
            var utils = em.Utils;
            _this.opt.sorter = new utils.Sorter({
                // @ts-ignore
                container: config.sortContainer || _this.el,
                containerSel: ".".concat(_this.className),
                itemSel: ".".concat(pfx, "layer"),
                ignoreViewChildren: 1,
                avoidSelectOnEnd: 1,
                nested: 1,
                ppfx: ppfx,
                pfx: pfx,
                em: em,
            });
        }
        // For the sorter
        _this.$el.data('collection', coll);
        opt.parent && _this.$el.data('model', opt.parent);
        return _this;
    }
    ItemsView.prototype.removeChildren = function (removed) {
        // @ts-ignore
        var view = removed.viewLayer;
        if (!view)
            return;
        view.remove();
        // @ts-ignore
        delete removed.viewLayer;
    };
    /**
     * Add to collection
     * @param Object Model
     *
     * @return Object
     * */
    ItemsView.prototype.addTo = function (model) {
        var i = this.collection.indexOf(model);
        this.addToCollection(model, null, i);
    };
    /**
     * Add new object to collection
     * @param  Object  Model
     * @param  Object   Fragment collection
     * @param  integer  Index of append
     *
     * @return Object Object created
     * */
    ItemsView.prototype.addToCollection = function (model, fragmentEl, index) {
        var _a = this, parentView = _a.parentView, opt = _a.opt, config = _a.config;
        var ItemView = opt.ItemView, opened = opt.opened, module = opt.module, level = opt.level, sorter = opt.sorter;
        var fragment = fragmentEl || null;
        var item = new ItemView({
            ItemView: ItemView,
            level: level,
            model: model,
            parentView: parentView,
            config: config,
            sorter: sorter,
            opened: opened,
            module: module,
        });
        var rendered = item.render().el;
        if (fragment) {
            fragment.appendChild(rendered);
        }
        else {
            if (typeof index !== 'undefined') {
                var method = 'before';
                // If the added model is the last of collection
                // need to change the logic of append
                if (this.$el.children().length == index) {
                    index--;
                    method = 'after';
                }
                // In case the added is new in the collection index will be -1
                if (index < 0) {
                    this.$el.append(rendered);
                }
                else {
                    // @ts-ignore
                    this.$el.children().eq(index)[method](rendered);
                }
            }
            else
                this.$el.append(rendered);
        }
        this.items.push(item);
        return rendered;
    };
    ItemsView.prototype.remove = function () {
        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            args[_i] = arguments[_i];
        }
        common/* View */.G7.prototype.remove.apply(this, args);
        this.items.map(function (i) { return i.remove(); });
        return this;
    };
    ItemsView.prototype.render = function () {
        var _this = this;
        var frag = document.createDocumentFragment();
        var el = this.el;
        el.innerHTML = '';
        this.collection.each(function (model) { return _this.addToCollection(model, frag); });
        el.appendChild(frag);
        el.className = this.className;
        return this;
    };
    return ItemsView;
}(common/* View */.G7));
/* harmony default export */ const view_ItemsView = (ItemsView);

// EXTERNAL MODULE: ./src/commands/view/CommandAbstract.ts
var CommandAbstract = __webpack_require__(790);
;// CONCATENATED MODULE: ./src/commands/config/config.ts
var commands_config_config_config = {
    stylePrefix: 'com-',
    defaults: {},
    strict: true,
};
/* harmony default export */ const commands_config_config = (commands_config_config_config);

// EXTERNAL MODULE: ./src/commands/types.ts
var commands_types = __webpack_require__(713);
;// CONCATENATED MODULE: ./src/commands/index.ts
/**
 * You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](https://github.com/GrapesJS/grapesjs/blob/master/src/commands/config/config.ts)
 * ```js
 * const editor = grapesjs.init({
 *  commands: {
 *    // options
 *  }
 * })
 * ```
 *
 * Once the editor is instantiated you can use its API and listen to its events. Before using these methods, you should get the module from the instance.
 *
 * ```js
 * // Listen to events
 * editor.on('run', () => { ... });
 *
 * // Use the API
 * const commands = editor.Commands;
 * commands.add(...);
 * ```
 *
 * {REPLACE_EVENTS}
 *
 * ## Methods
 * * [add](#add)
 * * [get](#get)
 * * [getAll](#getall)
 * * [extend](#extend)
 * * [has](#has)
 * * [run](#run)
 * * [stop](#stop)
 * * [isActive](#isactive)
 * * [getActive](#getactive)
 *
 * @module Commands
 */
var commands_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var commands_assign = (undefined && undefined.__assign) || function () {
    commands_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return commands_assign.apply(this, arguments);
};
var commands_spreadArray = (undefined && undefined.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};






var commandsDef = [
    ['preview', 'Preview', 'preview'],
    ['resize', 'Resize', 'resize'],
    ['fullscreen', 'Fullscreen', 'fullscreen'],
    ['copy', 'CopyComponent'],
    ['paste', 'PasteComponent'],
    ['canvas-move', 'CanvasMove'],
    ['canvas-clear', 'CanvasClear'],
    ['open-code', 'ExportTemplate', 'export-template'],
    ['open-layers', 'OpenLayers', 'open-layers'],
    ['open-styles', 'OpenStyleManager', 'open-sm'],
    ['open-traits', 'OpenTraitManager', 'open-tm'],
    ['open-blocks', 'OpenBlocks', 'open-blocks'],
    ['open-assets', 'OpenAssets', 'open-assets'],
    ['component-select', 'SelectComponent', 'select-comp'],
    ['component-outline', 'SwitchVisibility', 'sw-visibility'],
    ['component-offset', 'ShowOffset', 'show-offset'],
    ['component-move', 'MoveComponent', 'move-comp'],
    ['component-next', 'ComponentNext'],
    ['component-prev', 'ComponentPrev'],
    ['component-enter', 'ComponentEnter'],
    ['component-exit', 'ComponentExit', 'select-parent'],
    ['component-delete', 'ComponentDelete'],
    ['component-style-clear', 'ComponentStyleClear'],
    ['component-drag', 'ComponentDrag'],
];
var defComOptions = { preserveSelected: 1 };
var getOnComponentDragStart = function (em) { return function (data) { return em.trigger("".concat(eventDrag, ":start"), data); }; };
var getOnComponentDrag = function (em) { return function (data) { return em.trigger(eventDrag, data); }; };
var getOnComponentDragEnd = function (em, targets, opts) {
    if (opts === void 0) { opts = {}; }
    return function (a, b, data) {
        targets.forEach(function (trg) { return trg.set('status', trg.get('selectable') ? 'selected' : ''); });
        em.setSelected(targets);
        targets[0].emitUpdate();
        em.trigger("".concat(eventDrag, ":end"), data);
        // Defer selectComponent in order to prevent canvas "freeze" #2692
        setTimeout(function () { return em.runDefault(defComOptions); });
        // Dirty patch to prevent parent selection on drop
        (opts.altMode || data.cancelled) && em.set('_cmpDrag', 1);
    };
};
var CommandsModule = /** @class */ (function (_super) {
    commands_extends(CommandsModule, _super);
    /**
     * @private
     */
    function CommandsModule(em) {
        var _this = _super.call(this, em, 'Commands', commands_config_config) || this;
        _this.CommandAbstract = CommandAbstract["default"];
        _this.defaultCommands = {};
        _this.commands = {};
        _this.active = {};
        _this.events = commands_types/* default */.Z;
        var config = _this.config;
        var ppfx = config.pStylePrefix;
        var defaultCommands = _this.defaultCommands;
        if (ppfx) {
            config.stylePrefix = ppfx + config.stylePrefix;
        }
        // Load commands passed via configuration
        Object.keys(config.defaults).forEach(function (k) {
            var obj = config.defaults[k];
            if (obj.id)
                _this.add(obj.id, obj);
        });
        defaultCommands['tlb-delete'] = {
            run: function (ed) {
                return ed.runCommand('core:component-delete');
            },
        };
        defaultCommands['tlb-clone'] = {
            run: function (ed) {
                ed.runCommand('core:copy');
                ed.runCommand('core:paste', { action: 'clone-component' });
            },
        };
        defaultCommands['tlb-move'] = {
            run: function (ed, s, opts) {
                var _a;
                if (opts === void 0) { opts = {}; }
                var dragger;
                var em = ed.getModel();
                var event = opts.event;
                var trg = opts.target;
                var trgs = trg ? [trg] : commands_spreadArray([], ed.getSelectedAll(), true);
                var targets = trgs.map(function (trg) { var _a, _b; return ((_b = (_a = trg.delegate) === null || _a === void 0 ? void 0 : _a.move) === null || _b === void 0 ? void 0 : _b.call(_a, trg)) || trg; }).filter(Boolean);
                var target = targets[0];
                var nativeDrag = (event === null || event === void 0 ? void 0 : event.type) === 'dragstart';
                var modes = ['absolute', 'translate'];
                if (!(target === null || target === void 0 ? void 0 : target.get('draggable'))) {
                    return em.logWarning('The element is not draggable');
                }
                var mode = target.get('dmode') || em.get('dmode');
                var hideTlb = function () { return em.stopDefault(defComOptions); };
                var altMode = (0,index_all.includes)(modes, mode);
                targets.forEach(function (trg) { return trg.trigger('disable', { fromMove: true }); });
                // Without setTimeout the ghost image disappears
                nativeDrag ? setTimeout(hideTlb, 0) : hideTlb();
                var onStart = getOnComponentDragStart(em);
                var onDrag = getOnComponentDrag(em);
                var onEnd = getOnComponentDragEnd(em, targets, { altMode: altMode });
                if (altMode) {
                    // TODO move grabbing func in editor/canvas from the Sorter
                    dragger = ed.runCommand('core:component-drag', {
                        guidesInfo: 1,
                        mode: mode,
                        target: target,
                        onStart: onStart,
                        onDrag: onDrag,
                        onEnd: onEnd,
                        event: event,
                    });
                }
                else {
                    if (nativeDrag) {
                        event.dataTransfer.setDragImage((_a = target.view) === null || _a === void 0 ? void 0 : _a.el, 0, 0);
                        //sel.set('status', 'freezed');
                    }
                    var cmdMove = ed.Commands.get('move-comp');
                    cmdMove.onStart = onStart;
                    cmdMove.onDrag = onDrag;
                    cmdMove.onEndMoveFromModel = onEnd;
                    // @ts-ignore
                    cmdMove.initSorterFromModels(targets);
                }
                targets.filter(function (sel) { return sel.get('selectable'); }).forEach(function (sel) { return sel.set('status', 'freezed-selected'); });
            },
        };
        // Core commands
        defaultCommands['core:undo'] = function (e) { return e.UndoManager.undo(); };
        defaultCommands['core:redo'] = function (e) { return e.UndoManager.redo(); };
        commandsDef.forEach(function (item) {
            var oldCmd = item[2];
            var cmd = __webpack_require__(828)("./".concat(item[1])).default;
            var cmdName = "core:".concat(item[0]);
            defaultCommands[cmdName] = cmd;
            if (oldCmd) {
                defaultCommands[oldCmd] = cmd;
                // Propogate old commands (can be removed once we stop to call old commands)
                ['run', 'stop'].forEach(function (name) {
                    em.on("".concat(name, ":").concat(oldCmd), function () {
                        var args = [];
                        for (var _i = 0; _i < arguments.length; _i++) {
                            args[_i] = arguments[_i];
                        }
                        return em.trigger.apply(em, commands_spreadArray(["".concat(name, ":").concat(cmdName)], args, false));
                    });
                });
            }
        });
        // @ts-ignore TODO check where it's used
        config.model = em.Canvas;
        for (var id in defaultCommands) {
            _this.add(id, defaultCommands[id]);
        }
        return _this;
    }
    /**
     * Add new command to the collection
     * @param	{string} id Command's ID
     * @param	{Object|Function} command Object representing your command,
     *  By passing just a function it's intended as a stateless command
     *  (just like passing an object with only `run` method).
     * @return {this}
     * @example
     * commands.add('myCommand', {
     * 	run(editor, sender) {
     * 		alert('Hello world!');
     * 	},
     * 	stop(editor, sender) {
     * 	},
     * });
     * // As a function
     * commands.add('myCommand2', editor => { ... });
     * */
    CommandsModule.prototype.add = function (id, command) {
        var result = (0,index_all.isFunction)(command) ? { run: command } : command;
        if (!result.stop) {
            result.noStop = true;
        }
        delete result.initialize;
        result.id = id;
        this.commands[id] = CommandAbstract["default"].extend(result);
        return this;
    };
    /**
     * Get command by ID
     * @param	{string}	id Command's ID
     * @return {Object} Object representing the command
     * @example
     * var myCommand = commands.get('myCommand');
     * myCommand.run();
     * */
    CommandsModule.prototype.get = function (id) {
        var command = this.commands[id];
        if ((0,index_all.isFunction)(command)) {
            command = new command(this.config);
            this.commands[id] = command;
        }
        else if (!command) {
            this.em.logWarning("'".concat(id, "' command not found"));
        }
        return command;
    };
    /**
     * Extend the command. The command to extend should be defined as an object
     * @param	{string}	id Command's ID
     * @param {Object} Object with the new command functions
     * @returns {this}
     * @example
     * commands.extend('old-command', {
     *  someInnerFunction() {
     *  // ...
     *  }
     * });
     * */
    CommandsModule.prototype.extend = function (id, cmd) {
        if (cmd === void 0) { cmd = {}; }
        var command = this.get(id);
        if (command) {
            var cmdObj = commands_assign(commands_assign({}, command.constructor.prototype), cmd);
            this.add(id, cmdObj);
            // Extend also old name commands if exist
            var oldCmd = commandsDef.filter(function (cmd) { return "core:".concat(cmd[0]) === id && cmd[2]; })[0];
            oldCmd && this.add(oldCmd[2], cmdObj);
        }
        return this;
    };
    /**
     * Check if command exists
     * @param	{string}	id Command's ID
     * @return {Boolean}
     * */
    CommandsModule.prototype.has = function (id) {
        return !!this.commands[id];
    };
    /**
     * Get an object containing all the commands
     * @return {Object}
     */
    CommandsModule.prototype.getAll = function () {
        return this.commands;
    };
    /**
     * Execute the command
     * @param {String} id Command ID
     * @param {Object} [options={}] Options
     * @return {*} The return is defined by the command
     * @example
     * commands.run('myCommand', { someOption: 1 });
     */
    CommandsModule.prototype.run = function (id, options) {
        if (options === void 0) { options = {}; }
        return this.runCommand(this.get(id), options);
    };
    /**
     * Stop the command
     * @param {String} id Command ID
     * @param {Object} [options={}] Options
     * @return {*} The return is defined by the command
     * @example
     * commands.stop('myCommand', { someOption: 1 });
     */
    CommandsModule.prototype.stop = function (id, options) {
        if (options === void 0) { options = {}; }
        return this.stopCommand(this.get(id), options);
    };
    /**
     * Check if the command is active. You activate commands with `run`
     * and disable them with `stop`. If the command was created without `stop`
     * method it can't be registered as active
     * @param  {String}  id Command id
     * @return {Boolean}
     * @example
     * const cId = 'some-command';
     * commands.run(cId);
     * commands.isActive(cId);
     * // -> true
     * commands.stop(cId);
     * commands.isActive(cId);
     * // -> false
     */
    CommandsModule.prototype.isActive = function (id) {
        return this.getActive().hasOwnProperty(id);
    };
    /**
     * Get all active commands
     * @return {Object}
     * @example
     * console.log(commands.getActive());
     * // -> { someCommand: itsLastReturn, anotherOne: ... };
     */
    CommandsModule.prototype.getActive = function () {
        return this.active;
    };
    /**
     * Run command via its object
     * @param  {Object} command
     * @param {Object} options
     * @return {*} Result of the command
     * @private
     */
    CommandsModule.prototype.runCommand = function (command, options) {
        if (options === void 0) { options = {}; }
        var result;
        if (command && command.run) {
            var _a = this, em = _a.em, config = _a.config;
            var id = command.id;
            var editor = em.Editor;
            if (!this.isActive(id) || options.force || !config.strict) {
                // @ts-ignore
                result = editor && command.callRun(editor, options);
                if (id && command.stop && !command.noStop && !options.abort) {
                    this.active[id] = result;
                }
            }
        }
        return result;
    };
    /**
     * Stop the command
     * @param  {Object} command
     * @param {Object} options
     * @return {*} Result of the command
     * @private
     */
    CommandsModule.prototype.stopCommand = function (command, options) {
        if (options === void 0) { options = {}; }
        var result;
        if (command && command.run) {
            var _a = this, em = _a.em, config = _a.config;
            var id = command.id;
            var editor = em.Editor;
            if (this.isActive(id) || options.force || !config.strict) {
                if (id)
                    delete this.active[id];
                // @ts-ignore
                result = command.callStop(editor, options);
            }
        }
        return result;
    };
    /**
     * Create anonymous Command instance
     * @param {Object} command Command object
     * @return {Command}
     * @private
     * */
    CommandsModule.prototype.create = function (command) {
        if (!command.stop)
            command.noStop = true;
        var cmd = CommandAbstract["default"].extend(command);
        return new cmd(this.config);
    };
    CommandsModule.prototype.__onRun = function (id, clb) {
        var _a = this, em = _a.em, events = _a.events;
        em.on("".concat(events.runCommand).concat(id), clb);
    };
    CommandsModule.prototype.__onStop = function (id, clb) {
        var _a = this, em = _a.em, events = _a.events;
        em.on("".concat(events.stopCommand).concat(id), clb);
    };
    CommandsModule.prototype.destroy = function () {
        this.defaultCommands = {};
        this.commands = {};
        this.active = {};
    };
    return CommandsModule;
}(abstract_Module));
/* harmony default export */ const commands = (CommandsModule);

;// CONCATENATED MODULE: ./src/navigator/view/ItemView.ts
var ItemView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();






var ItemView_inputProp = 'contentEditable';
var ItemView = /** @class */ (function (_super) {
    ItemView_extends(ItemView, _super);
    function ItemView(opt) {
        var _this = _super.call(this, opt) || this;
        (0,index_all.bindAll)(_this, '__render');
        _this.opt = opt;
        _this.module = opt.module;
        _this.config = opt.config || {};
        _this.sorter = opt.sorter || '';
        _this.parentView = opt.parentView;
        var _a = _this, model = _a.model, pfx = _a.pfx, ppfx = _a.ppfx;
        var type = model.get('type') || 'default';
        _this.className = "".concat(pfx, "layer ").concat(pfx, "layer__t-").concat(type, " no-select ").concat(ppfx, "two-color");
        _this.inputNameCls = "".concat(ppfx, "layer-name");
        _this.clsTitleC = "".concat(pfx, "layer-title-c");
        _this.clsTitle = "".concat(pfx, "layer-title");
        _this.clsCaret = "".concat(pfx, "layer-caret");
        _this.clsCount = "".concat(pfx, "layer-count");
        _this.clsMove = "".concat(pfx, "layer-move");
        _this.clsChildren = "".concat(pfx, "layer-children");
        _this.clsNoChild = "".concat(pfx, "layer-no-chld");
        _this.clsEdit = "".concat(_this.inputNameCls, "--edit");
        _this.clsNoEdit = "".concat(_this.inputNameCls, "--no-edit");
        _this.initComponent();
        return _this;
    }
    ItemView.prototype.events = function () {
        return {
            'mousedown [data-toggle-move]': 'startSort',
            'touchstart [data-toggle-move]': 'startSort',
            'click [data-toggle-visible]': 'toggleVisibility',
            'click [data-toggle-open]': 'toggleOpening',
            'click [data-toggle-select]': 'handleSelect',
            'mouseover [data-toggle-select]': 'handleHover',
            'mouseout [data-toggle-select]': 'handleHoverOut',
            'dblclick [data-name]': 'handleEdit',
            'keydown [data-name]': 'handleEditKey',
            'focusout [data-name]': 'handleEditEnd',
        };
    };
    ItemView.prototype.template = function (model) {
        var _a = this, pfx = _a.pfx, ppfx = _a.ppfx, config = _a.config, clsNoEdit = _a.clsNoEdit, module = _a.module, opt = _a.opt, em = _a.em;
        var hidable = config.hidable;
        var count = module.getComponents(model).length;
        var addClass = !count ? this.clsNoChild : '';
        var clsTitle = "".concat(this.clsTitle, " ").concat(addClass);
        var clsTitleC = "".concat(this.clsTitleC);
        var clsInput = "".concat(this.inputNameCls, " ").concat(clsNoEdit, " ").concat(ppfx, "no-app");
        var level = opt.level || 0;
        var gut = "".concat(level * 10, "px");
        var name = model.getName();
        var icon = model.getIcon();
        var clsBase = "".concat(pfx, "layer");
        var icons = (em === null || em === void 0 ? void 0 : em.getConfig()).icons;
        var _b = icons, move = _b.move, eye = _b.eye, eyeOff = _b.eyeOff, chevron = _b.chevron;
        return "\n      <div class=\"".concat(pfx, "layer-item ").concat(ppfx, "one-bg\" data-toggle-select>\n        <div class=\"").concat(pfx, "layer-item-left\">\n          ").concat(hidable
            ? "<i class=\"".concat(pfx, "layer-vis\" data-toggle-visible>\n                <i class=\"").concat(pfx, "layer-vis-on\">").concat(eye, "</i>\n                <i class=\"").concat(pfx, "layer-vis-off\">").concat(eyeOff, "</i>\n              </i>")
            : '', "\n          <div class=\"").concat(clsTitleC, "\">\n            <div class=\"").concat(clsTitle, "\" style=\"padding-left: ").concat(gut, "\">\n              <div class=\"").concat(pfx, "layer-title-inn\" title=\"").concat(name, "\">\n                <i class=\"").concat(this.clsCaret, "\" data-toggle-open>").concat(chevron, "</i>\n                  ").concat(icon ? "<span class=\"".concat(clsBase, "__icon\">").concat(icon, "</span>") : '', "\n                <span class=\"").concat(clsInput, "\" data-name>").concat(name, "</span>\n              </div>\n            </div>\n          </div>\n        </div>\n        <div class=\"").concat(pfx, "layer-item-right\">\n          <div class=\"").concat(this.clsCount, "\" data-count>").concat(count || '', "</div>\n          <div class=\"").concat(this.clsMove, "\" data-toggle-move>").concat(move || '', "</div>\n        </div>\n      </div>\n      <div class=\"").concat(this.clsChildren, "\"></div>\n    ");
    };
    Object.defineProperty(ItemView.prototype, "em", {
        get: function () {
            return this.module.em;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ItemView.prototype, "ppfx", {
        get: function () {
            return this.em.getConfig().stylePrefix;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ItemView.prototype, "pfx", {
        get: function () {
            return this.config.stylePrefix;
        },
        enumerable: false,
        configurable: true
    });
    ItemView.prototype.initComponent = function () {
        var _this = this;
        var _a = this, model = _a.model, config = _a.config;
        var onInit = config.onInit;
        var components = model.components();
        this.listenTo(components, 'remove add reset', this.checkChildren);
        [
            ['change:status', this.updateStatus],
            ['change:open', this.updateOpening],
            ['change:layerable', this.updateLayerable],
            ['change:style:display', this.updateVisibility],
            ['rerender:layer', this.render],
            ['change:name change:custom-name', this.updateName],
            // @ts-ignore
        ].forEach(function (item) { return _this.listenTo(model, item[0], item[1]); });
        this.$el.data('model', model);
        this.$el.data('collection', components);
        // @ts-ignore
        model.viewLayer = this;
        onInit.bind(this)({
            component: model,
            render: this.__render,
            listenTo: this.listenTo,
        });
    };
    ItemView.prototype.updateName = function () {
        this.getInputName().innerText = this.model.getName();
    };
    ItemView.prototype.getVisibilityEl = function () {
        return this.getItemContainer().find('[data-toggle-visible]');
    };
    ItemView.prototype.updateVisibility = function () {
        var _a = this, pfx = _a.pfx, model = _a.model, module = _a.module;
        var hClass = "".concat(pfx, "layer-hidden");
        var hidden = !module.isVisible(model);
        var method = hidden ? 'addClass' : 'removeClass';
        this.$el[method](hClass);
        this.getVisibilityEl()[method]("".concat(pfx, "layer-off"));
    };
    /**
     * Toggle visibility
     * @param	Event
     *
     * @return 	void
     * */
    ItemView.prototype.toggleVisibility = function (ev) {
        ev === null || ev === void 0 ? void 0 : ev.stopImmediatePropagation();
        var _a = this, module = _a.module, model = _a.model;
        module.setVisible(model, !module.isVisible(model));
    };
    /**
     * Handle the edit of the component name
     */
    ItemView.prototype.handleEdit = function (ev) {
        ev === null || ev === void 0 ? void 0 : ev.stopPropagation();
        var _a = this, em = _a.em, $el = _a.$el, clsNoEdit = _a.clsNoEdit, clsEdit = _a.clsEdit;
        var inputEl = this.getInputName();
        inputEl[ItemView_inputProp] = 'true';
        inputEl.focus();
        document.execCommand('selectAll', false);
        em.setEditing(true);
        $el.find(".".concat(this.inputNameCls)).removeClass(clsNoEdit).addClass(clsEdit);
    };
    ItemView.prototype.handleEditKey = function (ev) {
        ev.stopPropagation();
        ((0,dom/* isEscKey */.kl)(ev) || (0,dom/* isEnterKey */.r$)(ev)) && this.handleEditEnd(ev);
    };
    /**
     * Handle with the end of editing of the component name
     */
    ItemView.prototype.handleEditEnd = function (ev) {
        ev === null || ev === void 0 ? void 0 : ev.stopPropagation();
        var _a = this, em = _a.em, $el = _a.$el, clsNoEdit = _a.clsNoEdit, clsEdit = _a.clsEdit;
        var inputEl = this.getInputName();
        var name = inputEl.textContent;
        inputEl.scrollLeft = 0;
        inputEl[ItemView_inputProp] = 'false';
        this.setName(name, { component: this.model, propName: 'custom-name' });
        em.setEditing(false);
        $el.find(".".concat(this.inputNameCls)).addClass(clsNoEdit).removeClass(clsEdit);
        // Ensure to always update the layer name #4544
        this.updateName();
    };
    ItemView.prototype.setName = function (name, _a) {
        var propName = _a.propName;
        this.model.set(propName, name);
    };
    /**
     * Get the input containing the name of the component
     * @return {HTMLElement}
     */
    ItemView.prototype.getInputName = function () {
        if (!this.inputName) {
            this.inputName = this.el.querySelector(".".concat(this.inputNameCls));
        }
        return this.inputName;
    };
    /**
     * Update item opening
     *
     * @return void
     * */
    ItemView.prototype.updateOpening = function () {
        var _a = this, $el = _a.$el, model = _a.model, pfx = _a.pfx;
        var clsOpen = 'open';
        var clsChvOpen = "".concat(pfx, "layer-open");
        var caret = this.getCaret();
        if (this.module.isOpen(model)) {
            $el.addClass(clsOpen);
            caret.addClass(clsChvOpen);
        }
        else {
            $el.removeClass(clsOpen);
            caret.removeClass(clsChvOpen);
        }
    };
    /**
     * Toggle item opening
     * @param {Object}	e
     *
     * @return void
     * */
    ItemView.prototype.toggleOpening = function (ev) {
        var _a = this, model = _a.model, module = _a.module;
        ev === null || ev === void 0 ? void 0 : ev.stopImmediatePropagation();
        if (!model.get('components').length)
            return;
        module.setOpen(model, !module.isOpen(model));
    };
    /**
     * Handle component selection
     */
    ItemView.prototype.handleSelect = function (event) {
        event === null || event === void 0 ? void 0 : event.stopPropagation();
        var _a = this, module = _a.module, model = _a.model;
        module.setLayerData(model, { selected: true }, { event: event });
    };
    /**
     * Handle component selection
     */
    ItemView.prototype.handleHover = function (ev) {
        ev === null || ev === void 0 ? void 0 : ev.stopPropagation();
        var _a = this, module = _a.module, model = _a.model;
        module.setLayerData(model, { hovered: true });
    };
    ItemView.prototype.handleHoverOut = function (ev) {
        ev === null || ev === void 0 ? void 0 : ev.stopPropagation();
        var _a = this, module = _a.module, model = _a.model;
        module.setLayerData(model, { hovered: false });
    };
    /**
     * Delegate to sorter
     * @param	Event
     * */
    ItemView.prototype.startSort = function (ev) {
        var _a, _b, _c;
        ev.stopPropagation();
        var _d = this, em = _d.em, sorter = _d.sorter, model = _d.model;
        // Right or middel click
        if (ev.button && ev.button !== 0)
            return;
        if (sorter) {
            var toMove = ((_b = (_a = model.delegate) === null || _a === void 0 ? void 0 : _a.move) === null || _b === void 0 ? void 0 : _b.call(_a, model)) || model;
            sorter.onStart = getOnComponentDragStart(em);
            sorter.onMoveClb = getOnComponentDrag(em);
            sorter.onEndMove = getOnComponentDragEnd(em, [toMove]);
            var itemEl = ((_c = toMove.viewLayer) === null || _c === void 0 ? void 0 : _c.el) || ev.target;
            sorter.startSort(itemEl);
        }
    };
    /**
     * Update item on status change
     * @param	Event
     * */
    ItemView.prototype.updateStatus = function () {
        // @ts-ignore
        view_ComponentView.prototype.updateStatus.apply(this, [
            {
                avoidHover: !this.config.highlightHover,
                noExtHl: true,
            },
        ]);
    };
    ItemView.prototype.getItemContainer = function () {
        return this.$el.children('[data-toggle-select]');
    };
    /**
     * Update item aspect after children changes
     *
     * @return void
     * */
    ItemView.prototype.checkChildren = function () {
        var _a = this, model = _a.model, clsNoChild = _a.clsNoChild, module = _a.module;
        var count = module.getComponents(model).length;
        var itemEl = this.getItemContainer();
        var title = itemEl.find(".".concat(this.clsTitle));
        var countEl = itemEl.find('[data-count]');
        title[count ? 'removeClass' : 'addClass'](clsNoChild);
        countEl.html("".concat(count || ''));
        !count && module.setOpen(model, false);
    };
    ItemView.prototype.getCaret = function () {
        if (!this.caret || !this.caret.length) {
            this.caret = this.getItemContainer().find(".".concat(this.clsCaret));
        }
        return this.caret;
    };
    ItemView.prototype.setRoot = function (cmp) {
        var _a;
        var model = (0,index_all.isString)(cmp) ? (_a = this.em.getWrapper()) === null || _a === void 0 ? void 0 : _a.find(cmp)[0] : cmp;
        if (!model)
            return;
        this.stopListening();
        this.model = model;
        this.initComponent();
        this._rendered && this.render();
    };
    ItemView.prototype.updateLayerable = function () {
        var parentView = this.parentView;
        var toRerender = parentView || this;
        toRerender.render();
    };
    ItemView.prototype.__clearItems = function () {
        var _a;
        (_a = this.items) === null || _a === void 0 ? void 0 : _a.remove();
    };
    ItemView.prototype.remove = function () {
        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            args[_i] = arguments[_i];
        }
        common/* View */.G7.prototype.remove.apply(this, args);
        this.__clearItems();
        return this;
    };
    ItemView.prototype.render = function () {
        var _a = this, model = _a.model, config = _a.config, pfx = _a.pfx, ppfx = _a.ppfx, opt = _a.opt, sorter = _a.sorter;
        this.__clearItems();
        var opened = opt.opened, module = opt.module, ItemView = opt.ItemView;
        var hidden = !module.__isLayerable(model);
        var el = this.$el.empty();
        var level = opt.level + 1;
        delete this.inputName;
        this.items = new view_ItemsView({
            ItemView: ItemView,
            collection: model.get('components'),
            config: config,
            sorter: sorter,
            opened: opened,
            parentView: this,
            parent: model,
            level: level,
            module: module,
        });
        var children = this.items.render().$el;
        if (!config.showWrapper && level === 1) {
            el.append(children);
        }
        else {
            el.html(this.template(model));
            el.find(".".concat(this.clsChildren)).append(children);
        }
        if (!model.get('draggable') || !config.sortable) {
            el.children(".".concat(this.clsMove)).remove();
        }
        !module.isVisible(model) && (this.className += " ".concat(pfx, "hide"));
        hidden && (this.className += " ".concat(ppfx, "hidden"));
        el.attr('class', this.className);
        this.updateStatus();
        this.updateOpening();
        this.updateVisibility();
        this.__render();
        this._rendered = true;
        return this;
    };
    ItemView.prototype.__render = function () {
        var _a = this, model = _a.model, config = _a.config, el = _a.el;
        var onRender = config.onRender;
        var opt = { component: model, el: el };
        onRender.bind(this)(opt);
        this.em.trigger('layer:render', opt);
    };
    return ItemView;
}(common/* View */.G7));
/* harmony default export */ const view_ItemView = (ItemView);

;// CONCATENATED MODULE: ./src/navigator/index.ts
/**
 * You can customize the initial state of the module from the editor initialization
 * ```js
 * const editor = grapesjs.init({
 *  // ...
 *  layerManager: {
 *    // ...
 *  },
 * })
 * ```
 *
 * Once the editor is instantiated you can use its API. Before using these methods you should get the module from the instance
 *
 * ```js
 * const layers = editor.Layers;
 * ```
 *
 * ## Available Events
 * * `layer:root` - Root layer changed. The new root component is passed as an argument to the callback.
 * * `layer:component` - Component layer is updated. The updated component is passed as an argument to the callback.
 *
 * ## Methods
 * * [setRoot](#setroot)
 * * [getRoot](#getroot)
 * * [getComponents](#getcomponents)
 * * [setOpen](#setopen)
 * * [isOpen](#isopen)
 * * [setVisible](#setvisible)
 * * [isVisible](#isvisible)
 * * [setlocked](#setlocked)
 * * [isLocked](#islocked)
 * * [setName](#setname)
 * * [getName](#getname)
 * * [getLayerData](#getlayerdata)
 *
 * [Page]: page.html
 * [Component]: component.html
 *
 * @module Layers
 */
var navigator_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var navigator_assign = (undefined && undefined.__assign) || function () {
    navigator_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return navigator_assign.apply(this, arguments);
};






var navigator_evAll = 'layer';
var navigator_evPfx = "".concat(navigator_evAll, ":");
var evRoot = "".concat(navigator_evPfx, "root");
var evComponent = "".concat(navigator_evPfx, "component");
var navigator_evCustom = "".concat(navigator_evPfx, "custom");
var events = {
    all: navigator_evAll,
    root: evRoot,
    component: evComponent,
    custom: navigator_evCustom,
};
var styleOpts = { mediaText: '' };
var propsToListen = ['open', 'status', 'locked', 'custom-name', 'components', 'classes']
    .map(function (p) { return "component:update:".concat(p); })
    .join(' ');
var isStyleHidden = function (style) {
    if (style === void 0) { style = {}; }
    return (style.display || '').trim().indexOf('none') === 0;
};
var LayerManager = /** @class */ (function (_super) {
    navigator_extends(LayerManager, _super);
    function LayerManager(em) {
        var _this = _super.call(this, em, 'LayerManager', navigator_config_config) || this;
        _this.events = events;
        (0,index_all.bindAll)(_this, 'componentChanged', '__onRootChange', '__onComponent');
        _this.model = new ModuleModel/* default */.Z(_this, { opened: {} });
        // @ts-ignore
        _this.config.stylePrefix = _this.config.pStylePrefix;
        return _this;
    }
    LayerManager.prototype.onLoad = function () {
        var _this = this;
        var _a = this, em = _a.em, config = _a.config, model = _a.model;
        model.listenTo(em, 'component:selected', this.componentChanged);
        model.on('change:root', this.__onRootChange);
        model.listenTo(em, propsToListen, this.__onComponent);
        this.componentChanged();
        model.listenToOnce(em, 'load', function () {
            _this.setRoot(config.root);
            _this.__appendTo();
        });
    };
    /**
     * Update the root layer with another component.
     * @param {[Component]|String} component Component to be set as root
     * @return {[Component]}
     * @example
     * const component = editor.getSelected();
     * layers.setRoot(component);
     */
    LayerManager.prototype.setRoot = function (component) {
        var wrapper = this.em.getWrapper();
        var root = (0,mixins.isComponent)(component) ? component : wrapper;
        if (component && (0,index_all.isString)(component) && (0,mixins.hasWin)()) {
            root = wrapper.find(component)[0] || wrapper;
        }
        this.model.set('root', root);
        return root;
    };
    /**
     * Get the current root layer.
     * @return {[Component]}
     * @example
     * const layerRoot = layers.getRoot();
     */
    LayerManager.prototype.getRoot = function () {
        return this.model.get('root'); // || this.em.getWrapper();
    };
    /**
     * Get valid layer child components (eg. excludes non layerable components).
     * @param {[Component]} component Component from which you want to get child components
     * @returns {Array<[Component]>}
     * @example
     * const component = editor.getSelected();
     * const components = layers.getComponents(component);
     * console.log(components);
     */
    LayerManager.prototype.getComponents = function (component) {
        var _this = this;
        return component.components().filter(function (cmp) { return _this.__isLayerable(cmp); });
    };
    /**
     * Update the layer open state of the component.
     * @param {[Component]} component Component to update
     * @param {Boolean} value
     */
    LayerManager.prototype.setOpen = function (component, value) {
        component.set('open', value);
    };
    /**
     * Check the layer open state of the component.
     * @param {[Component]} component
     * @returns {Boolean}
     */
    LayerManager.prototype.isOpen = function (component) {
        return !!component.get('open');
    };
    /**
     * Update the layer visibility state of the component.
     * @param {[Component]} component Component to update
     * @param {Boolean} value
     */
    LayerManager.prototype.setVisible = function (component, value) {
        var prevDspKey = '__prev-display';
        var style = component.getStyle(styleOpts);
        var display = style.display;
        if (value) {
            var prevDisplay = component.get(prevDspKey);
            delete style.display;
            if (prevDisplay) {
                style.display = prevDisplay;
                component.unset(prevDspKey);
            }
        }
        else {
            display && component.set(prevDspKey, display);
            style.display = 'none';
        }
        component.setStyle(style, styleOpts);
        this.updateLayer(component);
        this.em.trigger('component:toggled'); // Updates Style Manager #2938
    };
    /**
     * Check the layer visibility state of the component.
     * @param {[Component]} component
     * @returns {Boolean}
     */
    LayerManager.prototype.isVisible = function (component) {
        return !isStyleHidden(component.getStyle(styleOpts));
    };
    /**
     * Update the layer locked state of the component.
     * @param {[Component]} component Component to update
     * @param {Boolean} value
     */
    LayerManager.prototype.setLocked = function (component, value) {
        component.set('locked', value);
    };
    /**
     * Check the layer locked state of the component.
     * @param {[Component]} component
     * @returns {Boolean}
     */
    LayerManager.prototype.isLocked = function (component) {
        return !!component.get('locked');
    };
    /**
     * Update the layer name of the component.
     * @param {[Component]} component Component to update
     * @param {String} value New name
     */
    LayerManager.prototype.setName = function (component, value) {
        component.set('custom-name', value);
    };
    /**
     * Get the layer name of the component.
     * @param {[Component]} component
     * @returns {String} Component layer name
     */
    LayerManager.prototype.getName = function (component) {
        return component.getName();
    };
    /**
     * Get layer data from a component.
     * @param {[Component]} component Component from which you want to read layer data.
     * @returns {Object} Object containing the layer data.
     * @example
     * const component = editor.getSelected();
     * const layerData = layers.getLayerData(component);
     * console.log(layerData);
     */
    LayerManager.prototype.getLayerData = function (component) {
        var status = component.get('status');
        return {
            name: component.getName(),
            open: this.isOpen(component),
            selected: status === 'selected',
            hovered: status === 'hovered',
            visible: this.isVisible(component),
            locked: this.isLocked(component),
            components: this.getComponents(component),
        };
    };
    LayerManager.prototype.setLayerData = function (component, data, opts) {
        var _a;
        if (opts === void 0) { opts = {}; }
        var _b = this, em = _b.em, config = _b.config;
        var open = data.open, selected = data.selected, hovered = data.hovered, visible = data.visible, locked = data.locked, name = data.name;
        var cmpOpts = navigator_assign({ fromLayers: true }, opts);
        if ((0,mixins.isDef)(open)) {
            this.setOpen(component, open);
        }
        if ((0,mixins.isDef)(selected)) {
            if (selected) {
                em.setSelected(component, cmpOpts);
                var scroll_1 = config.scrollCanvas;
                scroll_1 && ((_a = component.views) === null || _a === void 0 ? void 0 : _a.forEach(function (view) { return view.scrollIntoView(scroll_1); }));
            }
            else {
                em.removeSelected(component, cmpOpts);
            }
        }
        if ((0,mixins.isDef)(hovered) && config.showHover) {
            hovered ? em.setHovered(component, cmpOpts) : em.setHovered(null, cmpOpts);
        }
        if ((0,mixins.isDef)(visible)) {
            visible !== this.isVisible(component) && this.setVisible(component, visible);
        }
        if ((0,mixins.isDef)(locked)) {
            this.setLocked(component, locked);
        }
        if ((0,mixins.isDef)(name)) {
            this.setName(component, name);
        }
    };
    /**
     * Triggered when the selected component is changed
     * @private
     */
    LayerManager.prototype.componentChanged = function (sel, opts) {
        var _a;
        if (opts === void 0) { opts = {}; }
        // @ts-ignore
        if (opts.fromLayers)
            return;
        var _b = this, em = _b.em, config = _b.config;
        var scrollLayers = config.scrollLayers;
        var opened = this.model.get('opened');
        var selected = em.getSelected();
        var parent = selected === null || selected === void 0 ? void 0 : selected.parent();
        for (var cid in opened) {
            opened[cid].set('open', false);
            delete opened[cid];
        }
        while (parent) {
            parent.set('open', true);
            opened[parent.cid] = parent;
            parent = parent.parent();
        }
        if (selected && scrollLayers) {
            // @ts-ignore
            var el = (_a = selected.viewLayer) === null || _a === void 0 ? void 0 : _a.el;
            el === null || el === void 0 ? void 0 : el.scrollIntoView(scrollLayers);
        }
    };
    LayerManager.prototype.getAll = function () {
        return this.view;
    };
    LayerManager.prototype.render = function () {
        var _a, _b;
        var _c = this, config = _c.config, model = _c.model;
        var ItemView = view_ItemView.extend(config.extend);
        this.view = new ItemView({
            el: (_a = this.view) === null || _a === void 0 ? void 0 : _a.el,
            ItemView: ItemView,
            level: 0,
            config: config,
            opened: model.get('opened'),
            model: this.getRoot(),
            module: this,
        });
        return (_b = this.view) === null || _b === void 0 ? void 0 : _b.render().el;
    };
    LayerManager.prototype.destroy = function () {
        var _a;
        (_a = this.view) === null || _a === void 0 ? void 0 : _a.remove();
    };
    LayerManager.prototype.__onRootChange = function () {
        var _a;
        var root = this.getRoot();
        (_a = this.view) === null || _a === void 0 ? void 0 : _a.setRoot(root);
        this.em.trigger(evRoot, root);
        this.__trgCustom();
    };
    LayerManager.prototype.__onComponent = function (component) {
        this.updateLayer(component);
    };
    LayerManager.prototype.__isLayerable = function (cmp) {
        var tag = cmp.get('tagName');
        var hideText = this.config.hideTextnode;
        var isValid = !hideText || (!cmp.isInstanceOf('textnode') && tag !== 'br');
        return isValid && cmp.get('layerable');
    };
    LayerManager.prototype.__trgCustom = function (opts) {
        var _a = this, __ctn = _a.__ctn, em = _a.em, events = _a.events;
        this.__ctn = __ctn || (opts === null || opts === void 0 ? void 0 : opts.container);
        em.trigger(events.custom, {
            container: this.__ctn,
            root: this.getRoot(),
        });
    };
    LayerManager.prototype.updateLayer = function (component, opts) {
        this.em.trigger(evComponent, component, opts);
    };
    return LayerManager;
}(abstract_Module));
/* harmony default export */ const src_navigator = (LayerManager);

;// CONCATENATED MODULE: ./src/asset_manager/config/config.ts
var asset_manager_config_config_config = {
    assets: [],
    noAssets: '',
    stylePrefix: 'am-',
    upload: '',
    uploadName: 'files',
    headers: {},
    params: {},
    credentials: 'include',
    multiUpload: true,
    multiUploadSuffix: '[]',
    autoAdd: true,
    customFetch: undefined,
    uploadFile: undefined,
    embedAsBase64: true,
    handleAdd: undefined,
    beforeUpload: undefined,
    showUrlInput: true,
    custom: false,
    dropzone: false,
    openAssetsOnDrop: true,
    dropzoneContent: '',
};
/* harmony default export */ const asset_manager_config_config = (asset_manager_config_config_config);

;// CONCATENATED MODULE: ./src/asset_manager/model/Asset.ts
var Asset_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();


/**
 * @property {String} type Asset type, eg. `'image'`.
 * @property {String} src Asset URL, eg. `'https://.../image.png'`.
 *
 * @module docsjs.Asset
 */
var Asset = /** @class */ (function (_super) {
    Asset_extends(Asset, _super);
    function Asset() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Asset.getDefaults = function () {
        return (0,index_all.result)(this.prototype, 'defaults');
    };
    Asset.prototype.defaults = function () {
        return {
            type: '',
            src: '',
        };
    };
    /**
     * Get asset type.
     * @returns {String}
     * @example
     * // Asset: { src: 'https://.../image.png', type: 'image' }
     * asset.getType(); // -> 'image'
     * */
    Asset.prototype.getType = function () {
        return this.get('type');
    };
    /**
     * Get asset URL.
     * @returns {String}
     * @example
     * // Asset: { src: 'https://.../image.png'  }
     * asset.getSrc(); // -> 'https://.../image.png'
     * */
    Asset.prototype.getSrc = function () {
        return this.get('src');
    };
    /**
     * Get filename of the asset (based on `src`).
     * @returns {String}
     * @example
     * // Asset: { src: 'https://.../image.png' }
     * asset.getFilename(); // -> 'image.png'
     * // Asset: { src: 'https://.../image' }
     * asset.getFilename(); // -> 'image'
     * */
    Asset.prototype.getFilename = function () {
        return this.get('src').split('/').pop().split('?').shift();
    };
    /**
     * Get extension of the asset (based on `src`).
     * @returns {String}
     * @example
     * // Asset: { src: 'https://.../image.png' }
     * asset.getExtension(); // -> 'png'
     * // Asset: { src: 'https://.../image' }
     * asset.getExtension(); // -> ''
     * */
    Asset.prototype.getExtension = function () {
        return this.getFilename().split('.').pop();
    };
    return Asset;
}(common/* Model */.Hn));
/* harmony default export */ const model_Asset = (Asset);
Asset.prototype.idAttribute = 'src';

;// CONCATENATED MODULE: ./src/asset_manager/model/AssetImage.ts
var AssetImage_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var AssetImage_assign = (undefined && undefined.__assign) || function () {
    AssetImage_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return AssetImage_assign.apply(this, arguments);
};

var AssetImage = /** @class */ (function (_super) {
    AssetImage_extends(AssetImage, _super);
    function AssetImage() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    AssetImage.prototype.defaults = function () {
        return AssetImage_assign(AssetImage_assign({}, model_Asset.getDefaults()), { type: 'image', unitDim: 'px', height: 0, width: 0 });
    };
    return AssetImage;
}(model_Asset));
/* harmony default export */ const model_AssetImage = (AssetImage);

;// CONCATENATED MODULE: ./src/asset_manager/view/AssetView.ts
var AssetView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();


var AssetView = /** @class */ (function (_super) {
    AssetView_extends(AssetView, _super);
    function AssetView(opt) {
        var _this = _super.call(this, opt) || this;
        _this.options = opt;
        _this.collection = opt.collection;
        var config = opt.config || {};
        _this.config = config;
        _this.pfx = config.stylePrefix || '';
        // @ts-ignore
        _this.ppfx = config.pStylePrefix || '';
        // @ts-ignore
        _this.em = config.em;
        _this.className = _this.pfx + 'asset';
        _this.listenTo(_this.model, 'destroy remove', _this.remove);
        // @ts-ignore
        _this.model.view = _this;
        var init = _this.init && _this.init.bind(_this);
        init && init(opt);
        return _this;
    }
    AssetView.prototype.__getBhv = function () {
        var em = this.em;
        var am = em === null || em === void 0 ? void 0 : em.Assets;
        return (am === null || am === void 0 ? void 0 : am.__getBehaviour()) || {};
    };
    AssetView.prototype.template = function (view, asset) {
        var pfx = this.pfx;
        return "\n      <div class=\"".concat(pfx, "preview-cont\">\n        ").concat(this.getPreview(), "\n      </div>\n      <div class=\"").concat(pfx, "meta\">\n        ").concat(this.getInfo(), "\n      </div>\n      <div class=\"").concat(pfx, "close\" data-toggle=\"asset-remove\">\n        &Cross;\n      </div>\n    ");
    };
    /**
     * Update target if exists
     * @param {Model} target
     * @private
     * */
    AssetView.prototype.updateTarget = function (target) {
        if (target && target.set) {
            target.set('attributes', (0,index_all.clone)(target.get('attributes')));
            target.set('src', this.model.get('src'));
        }
    };
    AssetView.prototype.getPreview = function () {
        return '';
    };
    AssetView.prototype.getInfo = function () {
        return '';
    };
    AssetView.prototype.render = function () {
        var el = this.el;
        el.innerHTML = this.template(this, this.model);
        el.className = this.className;
        return this;
    };
    return AssetView;
}(common/* View */.G7));
/* harmony default export */ const view_AssetView = (AssetView);

;// CONCATENATED MODULE: ./src/asset_manager/view/AssetImageView.ts
var AssetImageView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var AssetImageView_makeTemplateObject = (undefined && undefined.__makeTemplateObject) || function (cooked, raw) {
    if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
    return cooked;
};



var AssetImageView = /** @class */ (function (_super) {
    AssetImageView_extends(AssetImageView, _super);
    function AssetImageView() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    AssetImageView.prototype.getPreview = function () {
        var _a = this, pfx = _a.pfx, ppfx = _a.ppfx, model = _a.model;
        var src = model.get('src');
        return html(AssetImageView_templateObject_1 || (AssetImageView_templateObject_1 = AssetImageView_makeTemplateObject(["\n      <div class=\"", "preview\" style=\"background-image: url('", "');\"></div>\n      <div class=\"", "preview-bg ", "checker-bg\"></div>\n    "], ["\n      <div class=\"", "preview\" style=\"background-image: url('", "');\"></div>\n      <div class=\"", "preview-bg ", "checker-bg\"></div>\n    "])), pfx, src, pfx, ppfx);
    };
    AssetImageView.prototype.getInfo = function () {
        var _a = this, pfx = _a.pfx, model = _a.model;
        var name = model.get('name');
        var width = model.get('width');
        var height = model.get('height');
        var unit = model.get('unitDim');
        var dim = width && height ? "".concat(width, "x").concat(height).concat(unit) : '';
        name = name || model.getFilename();
        return html(AssetImageView_templateObject_2 || (AssetImageView_templateObject_2 = AssetImageView_makeTemplateObject(["\n      <div class=\"", "name\">", "</div>\n      <div class=\"", "dimensions\">", "</div>\n    "], ["\n      <div class=\"", "name\">", "</div>\n      <div class=\"", "dimensions\">", "</div>\n    "])), pfx, name, pfx, dim);
    };
    // @ts-ignore
    AssetImageView.prototype.init = function (o) {
        var pfx = this.pfx;
        this.className += " ".concat(pfx, "asset-image");
    };
    /**
     * Triggered when the asset is clicked
     * @private
     * */
    AssetImageView.prototype.onClick = function () {
        var _a = this, model = _a.model, pfx = _a.pfx;
        var select = this.__getBhv().select;
        // @ts-ignore
        var onClick = this.config.onClick;
        var coll = this.collection;
        coll.trigger('deselectAll');
        this.$el.addClass(pfx + 'highlight');
        if ((0,index_all.isFunction)(select)) {
            select(model, false);
        }
        else if ((0,index_all.isFunction)(onClick)) {
            onClick(model);
        }
        else {
            // @ts-ignore
            this.updateTarget(coll.target);
        }
    };
    /**
     * Triggered when the asset is double clicked
     * @private
     * */
    AssetImageView.prototype.onDblClick = function () {
        var _a = this, em = _a.em, model = _a.model;
        var select = this.__getBhv().select;
        // @ts-ignore
        var onDblClick = this.config.onDblClick;
        // @ts-ignore
        var _b = this.collection, target = _b.target, onSelect = _b.onSelect;
        if ((0,index_all.isFunction)(select)) {
            select(model, true);
        }
        else if ((0,index_all.isFunction)(onDblClick)) {
            onDblClick(model);
        }
        else {
            this.updateTarget(target);
            em === null || em === void 0 ? void 0 : em.Modal.close();
        }
        (0,index_all.isFunction)(onSelect) && onSelect(model);
    };
    /**
     * Remove asset from collection
     * @private
     * */
    AssetImageView.prototype.onRemove = function (e) {
        e.stopImmediatePropagation();
        this.model.collection.remove(this.model);
    };
    return AssetImageView;
}(view_AssetView));
/* harmony default export */ const view_AssetImageView = (AssetImageView);
AssetImageView.prototype.events = {
    // @ts-ignore
    'click [data-toggle=asset-remove]': 'onRemove',
    click: 'onClick',
    dblclick: 'onDblClick',
};
var AssetImageView_templateObject_1, AssetImageView_templateObject_2;

;// CONCATENATED MODULE: ./src/domain_abstract/model/TypeableCollection.ts
var TypeableCollection_assign = (undefined && undefined.__assign) || function () {
    TypeableCollection_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return TypeableCollection_assign.apply(this, arguments);
};
// @ts-nocheck TODO extend View


var TypeableCollection = {
    types: [],
    initialize: function (models, opts) {
        var _this = this;
        if (opts === void 0) { opts = {}; }
        var em = opts.em;
        this.em = em;
        this.opts = opts;
        this.model = function (attrs, options) {
            if (attrs === void 0) { attrs = {}; }
            if (options === void 0) { options = {}; }
            var Model, View, type;
            if (attrs && attrs.type) {
                var baseType = _this.getBaseType();
                type = _this.getType(attrs.type);
                Model = type ? type.model : baseType.model;
                View = type ? type.view : baseType.view;
            }
            else {
                var typeFound = _this.recognizeType(attrs);
                type = typeFound.type;
                Model = type.model;
                View = type.view;
                attrs = typeFound.attributes;
            }
            var model = new Model(attrs, TypeableCollection_assign(TypeableCollection_assign({}, options), { em: em }));
            model.typeView = View;
            return model;
        };
        var init = this.init && this.init.bind(this);
        init && init();
    },
    /**
     * Recognize type by any value
     * @param  {mixed} value
     * @return {Object} Found type
     */
    recognizeType: function (value) {
        var types = this.getTypes();
        for (var i = 0; i < types.length; i++) {
            var type = types[i];
            var typeFound = type.isType(value);
            typeFound = typeof typeFound == 'boolean' && typeFound ? { type: type.id } : typeFound;
            if (typeFound) {
                return {
                    type: type,
                    attributes: typeFound,
                };
            }
        }
        // If, for any reason, the type is not found it'll return the base one
        return {
            type: this.getBaseType(),
            attributes: value,
        };
    },
    /**
     * Returns the base type (last object in the stack)
     * @return {Object}
     */
    getBaseType: function () {
        var types = this.getTypes();
        return types[types.length - 1];
    },
    /**
     * Get types
     * @return {Array}
     */
    getTypes: function () {
        return this.types;
    },
    /**
     * Get type
     * @param {string} id Type ID
     * @return {Object} Type definition
     */
    getType: function (id) {
        var types = this.getTypes();
        for (var i = 0; i < types.length; i++) {
            var type = types[i];
            if (type.id === id) {
                return type;
            }
        }
    },
    /**
     * Add new type
     * @param {string} id Type ID
     * @param {Object} definition Definition of the type. Each definition contains
     *                            `model` (business logic), `view` (presentation logic)
     *                            and `isType` function which recognize the type of the
     *                            passed entity
     * addType('my-type', {
     *  model: {},
     *  view: {},
     *  isType: (value) => {},
     * })
     */
    addType: function (id, definition) {
        var type = this.getType(id);
        var baseType = this.getBaseType();
        var ModelInst = type ? type.model : baseType.model;
        var ViewInst = type ? type.view : baseType.view;
        var model = definition.model, view = definition.view, isType = definition.isType;
        model = model instanceof common/* Model */.Hn || (0,index_all.isFunction)(model) ? model : ModelInst.extend(model || {});
        view = view instanceof common/* View */.G7 || (0,index_all.isFunction)(view) ? view : ViewInst.extend(view || {});
        // New API
        if (this.extendViewApi && !definition.model && !definition.view) {
            view = view.extend(definition);
        }
        if (type) {
            type.model = model;
            type.view = view;
            type.isType = isType || type.isType;
        }
        else {
            definition.id = id;
            definition.model = model;
            definition.view = view;
            definition.isType =
                isType ||
                    function (value) {
                        if (value && value.type == id) {
                            return true;
                        }
                    };
            this.getTypes().unshift(definition);
        }
    },
};
/* harmony default export */ const model_TypeableCollection = (TypeableCollection);

;// CONCATENATED MODULE: ./src/asset_manager/model/Assets.ts
var Assets_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();




var TypeableCollectionExt = common/* Collection */.FE.extend(model_TypeableCollection);
var Assets = /** @class */ (function (_super) {
    Assets_extends(Assets, _super);
    function Assets() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    return Assets;
}(TypeableCollectionExt));
/* harmony default export */ const model_Assets = (Assets);
Assets.prototype.types = [
    {
        id: 'image',
        model: model_AssetImage,
        view: view_AssetImageView,
        isType: function (value) {
            if (typeof value == 'string') {
                return {
                    type: 'image',
                    src: value,
                };
            }
            return value;
        },
    },
];

;// CONCATENATED MODULE: ./src/asset_manager/types.ts
/**{START_EVENTS}*/
var AssetsEvents;
(function (AssetsEvents) {
    /**
     * @event `asset:add` New asset added to the collection. The [Asset] is passed as an argument to the callback.
     * @example
     * editor.on('asset:add', (asset) => { ... });
     */
    AssetsEvents["add"] = "asset:add";
    /**
     * @event `asset:remove` Asset removed from the collection. The [Asset] is passed as an argument to the callback.
     * @example
     * editor.on('asset:remove', (asset) => { ... });
     */
    AssetsEvents["remove"] = "asset:remove";
    AssetsEvents["removeBefore"] = "asset:remove:before";
    /**
     * @event `asset:update` Asset updated. The [Asset] and the object containing changes are passed as arguments to the callback.
     * @example
     * editor.on('asset:update', (asset, updatedProps) => { ... });
     */
    AssetsEvents["update"] = "asset:update";
    /**
     * @event `asset:open` Asset Manager opened.
     * @example
     * editor.on('asset:open', () => { ... });
     */
    AssetsEvents["open"] = "asset:open";
    /**
     * @event `asset:close` Asset Manager closed.
     * @example
     * editor.on('asset:close', () => { ... });
     */
    AssetsEvents["close"] = "asset:close";
    /**
     * @event `asset:upload:start` Asset upload start.
     * @example
     * editor.on('asset:upload:start', () => { ... });
     */
    AssetsEvents["uploadStart"] = "asset:upload:start";
    /**
     * @event `asset:upload:end` Asset upload end.
     * @example
     * editor.on('asset:upload:end', (result) => { ... });
     */
    AssetsEvents["uploadEnd"] = "asset:upload:end";
    /**
     * @event `asset:upload:error` Asset upload error.
     * @example
     * editor.on('asset:upload:error', (error) => { ... });
     */
    AssetsEvents["uploadError"] = "asset:upload:error";
    /**
     * @event `asset:upload:response` Asset upload response.
     * @example
     * editor.on('asset:upload:response', (res) => { ... });
     */
    AssetsEvents["uploadResponse"] = "asset:upload:response";
    /**
     * @event `asset:custom` Event to use in case of [custom Asset Manager UI](https://grapesjs.com/docs/modules/Assets.html#customization).
     * @example
     * editor.on('asset:custom', ({ container, assets, ... }) => { ... });
     */
    AssetsEvents["custom"] = "asset:custom";
    /**
     * @event `asset` Catch-all event for all the events mentioned above. An object containing all the available data about the triggered event is passed as an argument to the callback.
     * @example
     * editor.on('asset', ({ event, model, ... }) => { ... });
     */
    AssetsEvents["all"] = "asset";
})(AssetsEvents || (AssetsEvents = {}));
/**{END_EVENTS}*/
// need this to avoid the TS documentation generator to break
/* harmony default export */ const asset_manager_types = (AssetsEvents);

;// CONCATENATED MODULE: ./src/asset_manager/view/AssetsView.ts
var AssetsView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();

var AssetsView = /** @class */ (function (_super) {
    AssetsView_extends(AssetsView, _super);
    function AssetsView(o) {
        if (o === void 0) { o = {}; }
        var _this = _super.call(this, o) || this;
        _this.options = o;
        _this.config = o.config;
        _this.pfx = _this.config.stylePrefix || '';
        // @ts-ignore
        _this.ppfx = _this.config.pStylePrefix || '';
        // @ts-ignore
        _this.em = _this.config.em;
        var coll = _this.collection;
        _this.listenTo(coll, 'reset', _this.renderAssets);
        _this.listenTo(coll, 'add', _this.addToAsset);
        _this.listenTo(coll, 'remove', _this.removedAsset);
        _this.listenTo(coll, 'deselectAll', _this.deselectAll);
        return _this;
    }
    AssetsView.prototype.template = function (_a) {
        var pfx = _a.pfx, ppfx = _a.ppfx, em = _a.em;
        var form = '';
        if (this.config.showUrlInput) {
            form = "\n          <form class=\"".concat(pfx, "add-asset\">\n            <div class=\"").concat(ppfx, "field ").concat(pfx, "add-field\">\n              <input placeholder=\"").concat(em === null || em === void 0 ? void 0 : em.t('assetManager.inputPlh'), "\"/>\n            </div>\n            <button class=\"").concat(ppfx, "btn-prim\">").concat(em === null || em === void 0 ? void 0 : em.t('assetManager.addButton'), "</button>\n            <div style=\"clear:both\"></div>\n          </form>\n      ");
        }
        return "\n    <div class=\"".concat(pfx, "assets-cont\">\n      <div class=\"").concat(pfx, "assets-header\">\n        ").concat(form, "\n      </div>\n      <div class=\"").concat(pfx, "assets\" data-el=\"assets\"></div>\n      <div style=\"clear:both\"></div>\n    </div>\n    ");
    };
    /**
     * Add new asset to the collection via string
     * @param {Event} e Event object
     * @return {this}
     * @private
     */
    AssetsView.prototype.handleSubmit = function (ev) {
        ev.preventDefault();
        var input = this.getAddInput();
        var url = input && input.value.trim();
        var handleAdd = this.config.handleAdd;
        if (!url) {
            return;
        }
        input.value = '';
        var assetsEl = this.getAssetsEl();
        if (assetsEl) {
            assetsEl.scrollTop = 0;
        }
        if (handleAdd) {
            handleAdd.bind(this)(url);
        }
        else {
            this.options.globalCollection.add(url, { at: 0 });
        }
    };
    /**
     * Returns assets element
     * @return {HTMLElement}
     * @private
     */
    AssetsView.prototype.getAssetsEl = function () {
        //if(!this.assets) // Not able to cache as after the rerender it losses the ref
        return this.el.querySelector(".".concat(this.pfx, "assets"));
    };
    /**
     * Returns input url element
     * @return {HTMLElement}
     * @private
     */
    AssetsView.prototype.getAddInput = function () {
        if (!this.inputUrl || !this.inputUrl.value) {
            this.inputUrl = this.el.querySelector(".".concat(this.pfx, "add-asset input"));
        }
        return this.inputUrl;
    };
    /**
     * Triggered when an asset is removed
     * @param {Asset} model Removed asset
     * @private
     */
    AssetsView.prototype.removedAsset = function (model) {
        if (!this.collection.length) {
            this.toggleNoAssets();
        }
    };
    /**
     * Add asset to collection
     * @private
     * */
    AssetsView.prototype.addToAsset = function (model) {
        if (this.collection.length == 1) {
            this.toggleNoAssets(true);
        }
        this.addAsset(model);
    };
    /**
     * Add new asset to collection
     * @param Object Model
     * @param Object Fragment collection
     * @return Object Object created
     * @private
     * */
    AssetsView.prototype.addAsset = function (model, fragmentEl) {
        if (fragmentEl === void 0) { fragmentEl = null; }
        var fragment = fragmentEl;
        var collection = this.collection;
        var config = this.config;
        // @ts-ignore
        var rendered = new model.typeView({
            model: model,
            collection: collection,
            config: config,
        }).render().el;
        if (fragment) {
            fragment.appendChild(rendered);
        }
        else {
            var assetsEl = this.getAssetsEl();
            if (assetsEl) {
                assetsEl.insertBefore(rendered, assetsEl.firstChild);
            }
        }
        return rendered;
    };
    /**
     * Checks if to show noAssets
     * @param {Boolean} hide
     * @private
     */
    AssetsView.prototype.toggleNoAssets = function (hide) {
        if (hide === void 0) { hide = false; }
        var assetsEl = this.$el.find(".".concat(this.pfx, "assets"));
        if (hide) {
            assetsEl.empty();
        }
        else {
            var noAssets = this.config.noAssets;
            noAssets && assetsEl.append(noAssets);
        }
    };
    /**
     * Deselect all assets
     * @private
     * */
    AssetsView.prototype.deselectAll = function () {
        var pfx = this.pfx;
        this.$el.find(".".concat(pfx, "highlight")).removeClass("".concat(pfx, "highlight"));
    };
    AssetsView.prototype.renderAssets = function () {
        var _this = this;
        var fragment = document.createDocumentFragment();
        var assets = this.$el.find(".".concat(this.pfx, "assets"));
        assets.empty();
        this.toggleNoAssets(!!this.collection.length);
        this.collection.each(function (model) { return _this.addAsset(model, fragment); });
        assets.append(fragment);
    };
    AssetsView.prototype.render = function () {
        var fuRendered = this.options.fu.render().el;
        this.$el.empty();
        this.$el.append(fuRendered).append(this.template(this));
        this.el.className = "".concat(this.ppfx, "asset-manager");
        this.renderAssets();
        return this;
    };
    return AssetsView;
}(common/* View */.G7));
/* harmony default export */ const view_AssetsView = (AssetsView);
AssetsView.prototype.events = {
    // @ts-ignore
    submit: 'handleSubmit',
};

;// CONCATENATED MODULE: ./src/asset_manager/view/FileUploader.ts
var FileUploader_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var FileUploader_makeTemplateObject = (undefined && undefined.__makeTemplateObject) || function (cooked, raw) {
    if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
    return cooked;
};



var FileUploaderView = /** @class */ (function (_super) {
    FileUploader_extends(FileUploaderView, _super);
    function FileUploaderView(opts) {
        if (opts === void 0) { opts = {}; }
        var _this = _super.call(this, opts) || this;
        _this.options = opts;
        var c = opts.config || {};
        _this.module = opts.module;
        _this.config = c;
        // @ts-ignore
        _this.em = _this.config.em;
        _this.pfx = c.stylePrefix || '';
        _this.ppfx = c.pStylePrefix || '';
        _this.target = _this.options.globalCollection || {};
        _this.uploadId = _this.pfx + 'uploadFile';
        _this.disabled = c.disableUpload !== undefined ? c.disableUpload : !c.upload && !c.embedAsBase64;
        _this.multiUpload = c.multiUpload !== undefined ? c.multiUpload : true;
        var uploadFile = c.uploadFile;
        if (uploadFile) {
            _this.uploadFile = uploadFile.bind(_this);
        }
        else if (!c.upload && c.embedAsBase64) {
            _this.uploadFile = FileUploaderView.embedAsBase64;
        }
        _this.delegateEvents();
        return _this;
    }
    FileUploaderView.prototype.template = function (_a) {
        var pfx = _a.pfx, title = _a.title, uploadId = _a.uploadId, disabled = _a.disabled, multiUpload = _a.multiUpload;
        return html(FileUploader_templateObject_1 || (FileUploader_templateObject_1 = FileUploader_makeTemplateObject(["\n      <form>\n        <div id=\"", "title\">", "</div>\n        <input\n          data-input\n          type=\"file\"\n          id=\"", "\"\n          name=\"file\"\n          accept=\"*/*\"\n          ", "\n          ", "\n        />\n        <div style=\"clear:both;\"></div>\n      </form>\n    "], ["\n      <form>\n        <div id=\"", "title\">", "</div>\n        <input\n          data-input\n          type=\"file\"\n          id=\"", "\"\n          name=\"file\"\n          accept=\"*/*\"\n          ", "\n          ", "\n        />\n        <div style=\"clear:both;\"></div>\n      </form>\n    "])), pfx, title, uploadId, disabled ? 'disabled' : '', multiUpload ? 'multiple' : '');
    };
    FileUploaderView.prototype.events = function () {
        return {
            'change [data-input]': 'uploadFile',
        };
    };
    /**
     * Triggered before the upload is started
     * @private
     */
    FileUploaderView.prototype.onUploadStart = function () {
        var module = this.module;
        module === null || module === void 0 ? void 0 : module.__propEv(module.events.uploadStart);
    };
    /**
     * Triggered after the upload is ended
     * @param  {Object|string} res End result
     * @private
     */
    FileUploaderView.prototype.onUploadEnd = function (res) {
        var _a = this, $el = _a.$el, module = _a.module;
        module === null || module === void 0 ? void 0 : module.__propEv(module.events.uploadEnd, res);
        var input = $el.find('input');
        input && input.val('');
    };
    /**
     * Triggered on upload error
     * @param  {Object} err Error
     * @private
     */
    FileUploaderView.prototype.onUploadError = function (err) {
        var module = this.module;
        console.error(err);
        this.onUploadEnd(err);
        module === null || module === void 0 ? void 0 : module.__propEv(module.events.uploadError, err);
    };
    /**
     * Triggered on upload response
     * @param  {string} text Response text
     * @private
     */
    FileUploaderView.prototype.onUploadResponse = function (text, clb) {
        var _a = this, module = _a.module, config = _a.config, target = _a.target;
        var json;
        try {
            json = typeof text === 'string' ? JSON.parse(text) : text;
        }
        catch (e) {
            json = text;
        }
        module === null || module === void 0 ? void 0 : module.__propEv(module.events.uploadResponse, json);
        if (config.autoAdd && target) {
            target.add(json.data, { at: 0 });
        }
        this.onUploadEnd(text);
        clb === null || clb === void 0 ? void 0 : clb(json);
    };
    /**
     * Upload files
     * @param  {Object}  e Event
     * @return {Promise}
     * @private
     * */
    FileUploaderView.prototype.uploadFile = function (e, clb) {
        var _this = this;
        // @ts-ignore
        var files = e.dataTransfer ? e.dataTransfer.files : e.target.files;
        var config = this.config;
        var beforeUpload = config.beforeUpload;
        var beforeUploadResponse = beforeUpload && beforeUpload(files);
        if (beforeUploadResponse === false)
            return;
        var body = new FormData();
        var params = config.params, customFetch = config.customFetch, fetchOptions = config.fetchOptions;
        for (var param in params) {
            body.append(param, params[param]);
        }
        if (this.multiUpload) {
            for (var i = 0; i < files.length; i++) {
                body.append("".concat(config.uploadName).concat(config.multiUploadSuffix), files[i]);
            }
        }
        else if (files.length) {
            body.append(config.uploadName, files[0]);
        }
        var url = config.upload;
        var headers = config.headers;
        var reqHead = 'X-Requested-With';
        if (typeof headers[reqHead] == 'undefined') {
            headers[reqHead] = 'XMLHttpRequest';
        }
        if (url) {
            this.onUploadStart();
            var fetchOpts = {
                method: 'post',
                credentials: config.credentials || 'include',
                headers: headers,
                body: body,
            };
            var fetchOptsResult = (fetchOptions === null || fetchOptions === void 0 ? void 0 : fetchOptions(fetchOpts)) || fetchOpts;
            var fetchResult = customFetch
                ? customFetch(url, fetchOptsResult)
                : utils_fetch(url, fetchOptsResult).then(function (res) {
                    return ((res.status / 200) | 0) == 1 ? res.text() : res.text().then(function (text) { return Promise.reject(text); });
                });
            return fetchResult
                .then(function (text) { return _this.onUploadResponse(text, clb); })
                .catch(function (err) { return _this.onUploadError(err); });
        }
    };
    /**
     * Make input file droppable
     * @private
     * */
    FileUploaderView.prototype.initDrop = function () {
        var that = this;
        if (!this.uploadForm) {
            this.uploadForm = this.$el.find('form').get(0);
            var formEl_1 = this.uploadForm;
            if ('draggable' in formEl_1) {
                this.uploadForm.ondragover = function () {
                    formEl_1.className = that.pfx + 'hover';
                    return false;
                };
                this.uploadForm.ondragleave = function () {
                    formEl_1.className = '';
                    return false;
                };
                this.uploadForm.ondrop = function (ev) {
                    formEl_1.className = '';
                    ev.preventDefault();
                    that.uploadFile(ev);
                    return;
                };
            }
        }
    };
    FileUploaderView.prototype.initDropzone = function (ev) {
        var _this = this;
        var addedCls = 0;
        var c = this.config;
        var em = ev.model;
        var edEl = ev.el;
        var editor = em.Editor;
        var frameEl = em.Canvas.getBody();
        var ppfx = this.ppfx;
        var updatedCls = "".concat(ppfx, "dropzone-active");
        var dropzoneCls = "".concat(ppfx, "dropzone");
        var cleanEditorElCls = function () {
            edEl.className = edEl.className.replace(updatedCls, '').trim();
            addedCls = 0;
        };
        var onDragOver = function () {
            if (!addedCls) {
                edEl.className += " ".concat(updatedCls);
                addedCls = 1;
            }
            return false;
        };
        var onDragLeave = function () {
            cleanEditorElCls();
            return false;
        };
        var onDrop = function (e) {
            cleanEditorElCls();
            e.preventDefault();
            e.stopPropagation();
            _this.uploadFile(e);
            if (c.openAssetsOnDrop && editor) {
                var target = editor.getSelected();
                editor.runCommand('open-assets', {
                    target: target,
                    onSelect: function () {
                        editor.Modal.close();
                        editor.AssetManager.setTarget(null);
                    },
                });
            }
            return false;
        };
        ev.$el.append("<div class=\"".concat(dropzoneCls, "\">").concat(c.dropzoneContent, "</div>"));
        cleanEditorElCls();
        if ('draggable' in edEl) {
            [edEl, frameEl].forEach(function (item) {
                item.ondragover = onDragOver;
                item.ondragleave = onDragLeave;
                item.ondrop = onDrop;
            });
        }
    };
    FileUploaderView.prototype.render = function () {
        var _a = this, $el = _a.$el, pfx = _a.pfx, em = _a.em;
        $el.html(this.template({
            title: em && em.t('assetManager.uploadTitle'),
            uploadId: this.uploadId,
            disabled: this.disabled,
            multiUpload: this.multiUpload,
            pfx: pfx,
        }));
        this.initDrop();
        $el.attr('class', pfx + 'file-uploader');
        return this;
    };
    FileUploaderView.embedAsBase64 = function (e, clb) {
        var _this = this;
        // List files dropped
        // @ts-ignore
        var files = e.dataTransfer ? e.dataTransfer.files : e.target.files;
        var response = { data: [] };
        // Unlikely, widely supported now
        if (!FileReader) {
            // @ts-ignore
            this.onUploadError(new Error('Unsupported platform, FileReader is not defined'));
            return;
        }
        var promises = [];
        var mimeTypeMatcher = /^(.+)\/(.+)$/;
        var _loop_1 = function (file) {
            // For each file a reader (to read the base64 URL)
            // and a promise (to track and merge results and errors)
            var promise = new Promise(function (resolve, reject) {
                var reader = new FileReader();
                reader.addEventListener('load', function (event) {
                    var type;
                    var name = file.name;
                    // Try to find the MIME type of the file.
                    var match = mimeTypeMatcher.exec(file.type);
                    if (match) {
                        type = match[1]; // The first part in the MIME, "image" in image/png
                    }
                    else {
                        type = file.type;
                    }
                    /*
                  // Show local video files, http://jsfiddle.net/dsbonev/cCCZ2/embedded/result,js,html,css/
                  var URL = window.URL || window.webkitURL
                  var file = this.files[0]
                  var type = file.type
                  var videoNode = document.createElement('video');
                  var canPlay = videoNode.canPlayType(type) // can use also for 'audio' types
                  if (canPlay === '') canPlay = 'no'
                  var message = 'Can play type "' + type + '": ' + canPlay
                  var isError = canPlay === 'no'
                  displayMessage(message, isError)
          
                  if (isError) {
                    return
                  }
          
                  var fileURL = URL.createObjectURL(file)
                  videoNode.src = fileURL
                   */
                    // If it's an image, try to find its size
                    if (type === 'image') {
                        var data_1 = {
                            src: reader.result,
                            name: name,
                            type: type,
                            height: 0,
                            width: 0,
                        };
                        var image_1 = new Image();
                        image_1.addEventListener('error', function (error) {
                            reject(error);
                        });
                        image_1.addEventListener('load', function () {
                            data_1.height = image_1.height;
                            data_1.width = image_1.width;
                            resolve(data_1);
                        });
                        // @ts-ignore
                        image_1.src = data_1.src;
                    }
                    else if (type) {
                        // Not an image, but has a type
                        resolve({
                            src: reader.result,
                            name: name,
                            type: type,
                        });
                    }
                    else {
                        // No type found, resolve with the URL only
                        resolve(reader.result);
                    }
                });
                reader.addEventListener('error', function (error) {
                    reject(error);
                });
                reader.addEventListener('abort', function (error) {
                    reject('Aborted');
                });
                reader.readAsDataURL(file);
            });
            promises.push(promise);
        };
        for (var _i = 0, files_1 = files; _i < files_1.length; _i++) {
            var file = files_1[_i];
            _loop_1(file);
        }
        return Promise.all(promises).then(function (data) {
            response.data = data;
            // @ts-ignore
            _this.onUploadResponse(response, clb);
        }, function (error) {
            // @ts-ignore
            _this.onUploadError(error);
        });
    };
    return FileUploaderView;
}(common/* View */.G7));
/* harmony default export */ const FileUploader = (FileUploaderView);
var FileUploader_templateObject_1;

;// CONCATENATED MODULE: ./src/asset_manager/index.ts
/**
 * You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](https://github.com/GrapesJS/grapesjs/blob/master/src/asset_manager/config/config.ts)
 * ```js
 * const editor = grapesjs.init({
 *  assetManager: {
 *    // options
 *  }
 * })
 * ```
 *
 * Once the editor is instantiated you can use its API. Before using these methods you should get the module from the instance
 *
 * ```js
 * const assetManager = editor.AssetManager;
 * ```
 *
 * {REPLACE_EVENTS}
 *
 * ## Methods
 * * [open](#open)
 * * [close](#close)
 * * [isOpen](#isopen)
 * * [add](#add)
 * * [get](#get)
 * * [getAll](#getall)
 * * [getAllVisible](#getallvisible)
 * * [remove](#remove)
 * * [getContainer](#getcontainer)
 *
 * [Asset]: asset.html
 *
 * @module Assets
 */
var asset_manager_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var asset_manager_assign = (undefined && undefined.__assign) || function () {
    asset_manager_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return asset_manager_assign.apply(this, arguments);
};
var asset_manager_spreadArray = (undefined && undefined.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};








var assetCmd = 'open-assets';
var AssetManager = /** @class */ (function (_super) {
    asset_manager_extends(AssetManager, _super);
    /**
     * Initialize module
     * @param {Object} config Configurations
     * @private
     */
    function AssetManager(em) {
        var _this = 
        // @ts-ignore
        _super.call(this, em, 'AssetManager', new model_Assets([], em), asset_manager_types, asset_manager_config_config) || this;
        _this.storageKey = 'assets';
        _this.Asset = model_Asset;
        _this.Assets = model_Assets;
        _this.events = asset_manager_types;
        var _a = _this, all = _a.all, config = _a.config;
        // @ts-ignore
        _this.assetsVis = new model_Assets([]);
        var ppfx = config.pStylePrefix;
        if (ppfx) {
            config.stylePrefix = "".concat(ppfx).concat(config.stylePrefix);
        }
        // Setup the sync between the global and public collections
        all.on('add', function (model) { return _this.getAllVisible().add(model); });
        all.on('remove', function (model) { return _this.getAllVisible().remove(model); });
        _this.__onAllEvent = (0,index_all.debounce)(function () { return _this.__trgCustom(); }, 0);
        return _this;
    }
    /**
     * Open the asset manager.
     * @param {Object} [options] Options for the asset manager.
     * @param {Array<String>} [options.types=['image']] Types of assets to show.
     * @param {Function} [options.select] Type of operation to perform on asset selection. If not specified, nothing will happen.
     * @example
     * assetManager.open({
     *  select(asset, complete) {
     *    const selected = editor.getSelected();
     *    if (selected && selected.is('image')) {
     *      selected.addAttributes({ src: asset.getSrc() });
     *      // The default AssetManager UI will trigger `select(asset, false)` on asset click
     *      // and `select(asset, true)` on double-click
     *      complete && assetManager.close();
     *    }
     *  }
     * });
     * // with your custom types (you should have assets with those types declared)
     * assetManager.open({ types: ['doc'], ... });
     */
    AssetManager.prototype.open = function (options) {
        if (options === void 0) { options = {}; }
        var cmd = this.em.Commands;
        cmd.run(assetCmd, asset_manager_assign({ types: ['image'], select: function () { } }, options));
    };
    /**
     * Close the asset manager.
     * @example
     * assetManager.close();
     */
    AssetManager.prototype.close = function () {
        var cmd = this.em.Commands;
        cmd.stop(assetCmd);
    };
    /**
     * Checks if the asset manager is open
     * @returns {Boolean}
     * @example
     * assetManager.isOpen(); // true | false
     */
    AssetManager.prototype.isOpen = function () {
        var cmd = this.em.Commands;
        return !!(cmd === null || cmd === void 0 ? void 0 : cmd.isActive(assetCmd));
    };
    /**
     * Add new asset/s to the collection. URLs are supposed to be unique
     * @param {String|Object|Array<String>|Array<Object>} asset URL strings or an objects representing the resource.
     * @param {Object} [opts] Options
     * @returns {[Asset]}
     * @example
     * // As strings
     * assetManager.add('http://img.jpg');
     * assetManager.add(['http://img.jpg', './path/to/img.png']);
     *
     * // Using objects you can indicate the type and other meta informations
     * assetManager.add({
     *  // type: 'image',	// image is default
     * 	src: 'http://img.jpg',
     * 	height: 300,
     *	width: 200,
     * });
     * assetManager.add([{ src: 'img2.jpg' }, { src: 'img2.png' }]);
     */
    AssetManager.prototype.add = function (asset, opts) {
        if (opts === void 0) { opts = {}; }
        // Put the model at the beginning
        if (typeof opts.at == 'undefined') {
            opts.at = 0;
        }
        return this.all.add(asset, opts);
    };
    /**
     * Return asset by URL
     * @param  {String} src URL of the asset
     * @returns {[Asset]|null}
     * @example
     * const asset = assetManager.get('http://img.jpg');
     */
    AssetManager.prototype.get = function (src) {
        return this.all.where({ src: src })[0] || null;
    };
    /**
     * Return the global collection, containing all the assets
     * @returns {Collection<[Asset]>}
     */
    AssetManager.prototype.getAll = function () {
        return this.all;
    };
    /**
     * Return the visible collection, which contains assets actually rendered
     * @returns {Collection<[Asset]>}
     */
    AssetManager.prototype.getAllVisible = function () {
        return this.assetsVis;
    };
    /**
     * Remove asset
     * @param {String|[Asset]} asset Asset or asset URL
     * @returns {[Asset]} Removed asset
     * @example
     * const removed = assetManager.remove('http://img.jpg');
     * // or by passing the Asset
     * const asset = assetManager.get('http://img.jpg');
     * assetManager.remove(asset);
     */
    AssetManager.prototype.remove = function (asset, opts) {
        return this.__remove(asset, opts);
    };
    AssetManager.prototype.store = function () {
        return this.getProjectData();
    };
    AssetManager.prototype.load = function (data) {
        return this.loadProjectData(data);
    };
    /**
     * Return the Asset Manager Container
     * @returns {HTMLElement}
     */
    AssetManager.prototype.getContainer = function () {
        var _a;
        var bhv = this.__getBehaviour();
        return bhv.container || ((_a = this.am) === null || _a === void 0 ? void 0 : _a.el);
    };
    /**
     *  Get assets element container
     * @returns {HTMLElement}
     * @private
     */
    AssetManager.prototype.getAssetsEl = function () {
        var _a;
        return (_a = this.am) === null || _a === void 0 ? void 0 : _a.el.querySelector('[data-el=assets]');
    };
    /**
     * Render assets
     * @param  {array} assets Assets to render, without the argument will render all global assets
     * @returns {HTMLElement}
     * @private
     * @example
     * // Render all assets
     * assetManager.render();
     *
     * // Render some of the assets
     * const assets = assetManager.getAll();
     * assetManager.render(assets.filter(
     *  asset => asset.get('category') == 'cats'
     * ));
     */
    AssetManager.prototype.render = function (assts) {
        if (this.getConfig().custom)
            return;
        var toRender = assts || this.getAll().models;
        if (!this.am) {
            var obj = this.__viewParams();
            obj.fu = this.FileUploader();
            this.am = new view_AssetsView(asset_manager_assign({}, obj));
            this.am.render();
        }
        this.assetsVis.reset(toRender);
        return this.getContainer();
    };
    AssetManager.prototype.__viewParams = function () {
        return {
            collection: this.assetsVis,
            globalCollection: this.all,
            config: this.config,
            module: this,
            fu: undefined,
        };
    };
    /**
     * Add new type. If you want to get more about type definition we suggest to read the [module's page](/modules/Assets.html)
     * @param {string} id Type ID
     * @param {Object} definition Definition of the type. Each definition contains
     *                            `model` (business logic), `view` (presentation logic)
     *                            and `isType` function which recognize the type of the
     *                            passed entity
     * @private
     * @example
     * assetManager.addType('my-type', {
     *  model: {},
     *  view: {},
     *  isType: (value) => {},
     * })
     */
    AssetManager.prototype.addType = function (id, definition) {
        this.getAll().addType(id, definition);
    };
    /**
     * Get type
     * @param {string} id Type ID
     * @returns {Object} Type definition
     * @private
     */
    AssetManager.prototype.getType = function (id) {
        return this.getAll().getType(id);
    };
    /**
     * Get types
     * @returns {Array}
     * @private
     */
    AssetManager.prototype.getTypes = function () {
        return this.getAll().getTypes();
    };
    //-------
    AssetManager.prototype.AssetsView = function () {
        return this.am;
    };
    AssetManager.prototype.FileUploader = function () {
        if (!this.fu) {
            this.fu = new FileUploader(this.__viewParams());
        }
        return this.fu;
    };
    AssetManager.prototype.onLoad = function () {
        var _this = this;
        this.getAll().reset(this.config.assets);
        var _a = this, em = _a.em, events = _a.events;
        em.Commands.__onRun(assetCmd, function () { return _this.__propEv(events.open); });
        em.Commands.__onStop(assetCmd, function () { return _this.__propEv(events.close); });
    };
    AssetManager.prototype.postRender = function (editorView) {
        var _a;
        this.config.dropzone && ((_a = this.fu) === null || _a === void 0 ? void 0 : _a.initDropzone(editorView));
    };
    /**
     * Set new target
     * @param	{Object}	m Model
     * @private
     * */
    AssetManager.prototype.setTarget = function (m) {
        this.assetsVis.target = m;
    };
    /**
     * Set callback after asset was selected
     * @param	{Object}	f Callback function
     * @private
     * */
    AssetManager.prototype.onSelect = function (f) {
        this.assetsVis.onSelect = f;
    };
    /**
     * Set callback to fire when the asset is clicked
     * @param {function} func
     * @private
     */
    AssetManager.prototype.onClick = function (func) {
        // @ts-ignore
        this.config.onClick = func;
    };
    /**
     * Set callback to fire when the asset is double clicked
     * @param {function} func
     * @private
     */
    AssetManager.prototype.onDblClick = function (func) {
        // @ts-ignore
        this.config.onDblClick = func;
    };
    AssetManager.prototype.__propEv = function (ev) {
        var _a, _b;
        var data = [];
        for (var _i = 1; _i < arguments.length; _i++) {
            data[_i - 1] = arguments[_i];
        }
        (_a = this.em).trigger.apply(_a, asset_manager_spreadArray([ev], data, false));
        (_b = this.getAll()).trigger.apply(_b, asset_manager_spreadArray([ev], data, false));
    };
    AssetManager.prototype.__trgCustom = function () {
        var bhv = this.__getBehaviour();
        var custom = this.getConfig().custom;
        if (!bhv.container && !custom.open) {
            return;
        }
        this.em.trigger(this.events.custom, this.__customData());
    };
    AssetManager.prototype.__customData = function () {
        var _this = this;
        var bhv = this.__getBehaviour();
        return {
            am: this,
            open: this.isOpen(),
            assets: this.getAll().models,
            types: bhv.types || [],
            container: bhv.container,
            close: function () { return _this.close(); },
            remove: function (asset, opts) { return _this.remove(asset, opts); },
            select: function (asset, complete) {
                var res = _this.add(asset);
                (0,index_all.isFunction)(bhv.select) && bhv.select(res, complete);
            },
            // extra
            options: bhv.options || {},
        };
    };
    AssetManager.prototype.__behaviour = function (opts) {
        if (opts === void 0) { opts = {}; }
        return (this._bhv = asset_manager_assign(asset_manager_assign({}, (this._bhv || {})), opts));
    };
    AssetManager.prototype.__getBehaviour = function (opts) {
        if (opts === void 0) { opts = {}; }
        return this._bhv || {};
    };
    AssetManager.prototype.destroy = function () {
        var _a, _b;
        this.all.stopListening();
        this.all.reset();
        this.assetsVis.stopListening();
        this.assetsVis.reset();
        (_a = this.fu) === null || _a === void 0 ? void 0 : _a.remove();
        (_b = this.am) === null || _b === void 0 ? void 0 : _b.remove();
        this._bhv = {};
    };
    return AssetManager;
}(ItemManagerModule));
/* harmony default export */ const asset_manager = (AssetManager);

;// CONCATENATED MODULE: ./src/pages/model/Page.ts
var Page_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();



var Page = /** @class */ (function (_super) {
    Page_extends(Page, _super);
    function Page(props, opts) {
        if (opts === void 0) { opts = {}; }
        var _this = _super.call(this, props, opts) || this;
        var em = opts.em;
        var defFrame = {};
        _this.em = em;
        if (!props.frames) {
            defFrame.component = props.component;
            defFrame.styles = props.styles;
            ['component', 'styles'].map(function (i) { return _this.unset(i); });
        }
        var frms = props.frames || [defFrame];
        var frames = new model_Frames(em.Canvas, frms);
        frames.page = _this;
        _this.set('frames', frames);
        !_this.getId() && _this.set('id', em === null || em === void 0 ? void 0 : em.Pages._createId());
        em === null || em === void 0 ? void 0 : em.UndoManager.add(frames);
        return _this;
    }
    Page.prototype.defaults = function () {
        return {
            name: '',
            frames: [],
            _undo: true,
        };
    };
    Page.prototype.onRemove = function () {
        this.getFrames().reset();
    };
    Page.prototype.getFrames = function () {
        return this.get('frames');
    };
    /**
     * Get page id
     * @returns {String}
     */
    Page.prototype.getId = function () {
        return this.id;
    };
    /**
     * Get page name
     * @returns {String}
     */
    Page.prototype.getName = function () {
        return this.get('name');
    };
    /**
     * Update page name
     * @param {String} name New page name
     * @example
     * page.setName('New name');
     */
    Page.prototype.setName = function (name) {
        return this.set({ name: name });
    };
    /**
     * Get all frames
     * @returns {Array<Frame>}
     * @example
     * const arrayOfFrames = page.getAllFrames();
     */
    Page.prototype.getAllFrames = function () {
        return this.getFrames().models || [];
    };
    /**
     * Get the first frame of the page (identified always as the main one)
     * @returns {Frame}
     * @example
     * const mainFrame = page.getMainFrame();
     */
    Page.prototype.getMainFrame = function () {
        return this.getFrames().at(0);
    };
    /**
     * Get the root component (usually is the `wrapper` component) from the main frame
     * @returns {Component}
     * @example
     * const rootComponent = page.getMainComponent();
     * console.log(rootComponent.toHTML());
     */
    Page.prototype.getMainComponent = function () {
        var frame = this.getMainFrame();
        return frame === null || frame === void 0 ? void 0 : frame.getComponent();
    };
    Page.prototype.toJSON = function (opts) {
        if (opts === void 0) { opts = {}; }
        var obj = common/* Model */.Hn.prototype.toJSON.call(this, opts);
        var defaults = (0,index_all.result)(this, 'defaults');
        // Remove private keys
        (0,index_all.forEach)(obj, function (value, key) {
            key.indexOf('_') === 0 && delete obj[key];
        });
        (0,index_all.forEach)(defaults, function (value, key) {
            if (obj[key] === value)
                delete obj[key];
        });
        return obj;
    };
    return Page;
}(common/* Model */.Hn));
/* harmony default export */ const model_Page = (Page);

;// CONCATENATED MODULE: ./src/pages/model/Pages.ts
var Pages_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var Pages_assign = (undefined && undefined.__assign) || function () {
    Pages_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return Pages_assign.apply(this, arguments);
};


var Pages = /** @class */ (function (_super) {
    Pages_extends(Pages, _super);
    function Pages(models, em) {
        var _this = _super.call(this, models) || this;
        _this.on('reset', _this.onReset);
        _this.on('remove', _this.onRemove);
        // @ts-ignore We need to inject `em` for pages created on reset from the Storage load
        _this.model = function (props, opts) {
            if (opts === void 0) { opts = {}; }
            return new model_Page(props, Pages_assign(Pages_assign({}, opts), { em: em }));
        };
        return _this;
    }
    Pages.prototype.onReset = function (m, opts) {
        var _this = this;
        var _a;
        (_a = opts === null || opts === void 0 ? void 0 : opts.previousModels) === null || _a === void 0 ? void 0 : _a.map(function (p) { return _this.onRemove(p); });
    };
    Pages.prototype.onRemove = function (removed) {
        removed === null || removed === void 0 ? void 0 : removed.onRemove();
    };
    return Pages;
}(common/* Collection */.FE));
/* harmony default export */ const model_Pages = (Pages);

;// CONCATENATED MODULE: ./src/pages/index.ts
/**
 * You can customize the initial state of the module from the editor initialization
 * ```js
 * const editor = grapesjs.init({
 *  ....
 *  pageManager: {
 *    pages: [
 *      {
 *        id: 'page-id',
 *        styles: `.my-class { color: red }`, // or a JSON of styles
 *        component: '<div class="my-class">My element</div>', // or a JSON of components
 *      }
 *   ]
 *  },
 * })
 * ```
 *
 * Once the editor is instantiated you can use its API. Before using these methods you should get the module from the instance
 *
 * ```js
 * const pageManager = editor.Pages;
 * ```
 *
 * {REPLACE_EVENTS}
 *
 * [Page]: page.html
 * [Component]: component.html
 *
 * @module Pages
 */
var pages_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var pages_spreadArray = (undefined && undefined.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};







var pages_chnSel = 'change:selected';
var typeMain = 'main';
var PageManager = /** @class */ (function (_super) {
    pages_extends(PageManager, _super);
    /**
     * Get all pages
     * @name getAll
     * @function
     * @returns {Array<[Page]>}
     * @example
     * const arrayOfPages = pageManager.getAll();
     */
    /**
     * Initialize module
     * @hideconstructor
     * @param {Object} config Configurations
     */
    function PageManager(em) {
        var _this = _super.call(this, em, 'PageManager', new model_Pages([], em), types) || this;
        _this.events = types;
        _this.storageKey = 'pages';
        (0,index_all.bindAll)(_this, '_onPageChange');
        var model = new ModuleModel/* default */.Z({ _undo: true });
        _this.model = model;
        _this.pages.on('reset', function (coll) { return coll.at(0) && _this.select(coll.at(0)); });
        _this.pages.on('all', _this.__onChange, _this);
        model.on(pages_chnSel, _this._onPageChange);
        return _this;
    }
    Object.defineProperty(PageManager.prototype, "pages", {
        get: function () {
            return this.all;
        },
        enumerable: false,
        configurable: true
    });
    PageManager.prototype.getAll = function () {
        // this avoids issues during the TS build (some getAll are inconsistent)
        return pages_spreadArray([], this.all.models, true);
    };
    PageManager.prototype.__onChange = function (event, page, coll, opts) {
        var _a = this, em = _a.em, events = _a.events;
        var options = opts || coll;
        em.trigger(events.all, { event: event, page: page, options: options });
    };
    PageManager.prototype.onLoad = function () {
        var _a;
        var _b = this, pages = _b.pages, config = _b.config, em = _b.em;
        var opt = { silent: true };
        var configPages = ((_a = config.pages) === null || _a === void 0 ? void 0 : _a.map(function (page) { return new model_Page(page, { em: em, config: config }); })) || [];
        pages.add(configPages, opt);
        var mainPage = !pages.length ? this.add({ type: typeMain }, opt) : this._initPage();
        mainPage && this.select(mainPage, opt);
    };
    PageManager.prototype._onPageChange = function (m, page, opts) {
        var _a = this, em = _a.em, events = _a.events;
        var lm = em.Layers;
        var mainComp = page.getMainComponent();
        lm && mainComp && lm.setRoot(mainComp);
        em.trigger(events.select, page, m.previous('selected'));
        this.__onChange(pages_chnSel, page, opts);
    };
    PageManager.prototype.postLoad = function () {
        var _a = this, em = _a.em, model = _a.model, pages = _a.pages;
        var um = em.UndoManager;
        um.add(model);
        um.add(pages);
        pages.on('add remove reset change', function (m, c, o) { return em.changesUp(o || c); });
    };
    /**
     * Add new page
     * @param {Object} props Page properties
     * @param {Object} [opts] Options
     * @returns {[Page]}
     * @example
     * const newPage = pageManager.add({
     *  id: 'new-page-id', // without an explicit ID, a random one will be created
     *  styles: `.my-class { color: red }`, // or a JSON of styles
     *  component: '<div class="my-class">My element</div>', // or a JSON of components
     * });
     */
    PageManager.prototype.add = function (props, opts) {
        var _this = this;
        if (opts === void 0) { opts = {}; }
        var _a = this, em = _a.em, events = _a.events;
        props.id = props.id || this._createId();
        var add = function () {
            var page = _this.pages.add(new model_Page(props, { em: _this.em, config: _this.config }), opts);
            opts.select && _this.select(page);
            return page;
        };
        !opts.silent && em.trigger(events.addBefore, props, add, opts);
        return !opts.abort ? add() : undefined;
    };
    /**
     * Remove page
     * @param {String|[Page]} page Page or page id
     * @returns {[Page]} Removed Page
     * @example
     * const removedPage = pageManager.remove('page-id');
     * // or by passing the page
     * const somePage = pageManager.get('page-id');
     * pageManager.remove(somePage);
     */
    PageManager.prototype.remove = function (page, opts) {
        var _this = this;
        if (opts === void 0) { opts = {}; }
        var _a = this, em = _a.em, events = _a.events;
        var pg = (0,index_all.isString)(page) ? this.get(page) : page;
        var rm = function () {
            pg && _this.pages.remove(pg, opts);
            return pg;
        };
        !opts.silent && em.trigger(events.removeBefore, pg, rm, opts);
        return !opts.abort && rm();
    };
    /**
     * Get page by id
     * @param {String} id Page id
     * @returns {[Page]}
     * @example
     * const somePage = pageManager.get('page-id');
     */
    PageManager.prototype.get = function (id) {
        return this.pages.filter(function (p) { return p.get(p.idAttribute) === id; })[0];
    };
    /**
     * Get main page (the first one available)
     * @returns {[Page]}
     * @example
     * const mainPage = pageManager.getMain();
     */
    PageManager.prototype.getMain = function () {
        var pages = this.pages;
        return pages.filter(function (p) { return p.get('type') === typeMain; })[0] || pages.at(0);
    };
    /**
     * Get wrapper components (aka body) from all pages and frames.
     * @returns {Array<[Component]>}
     * @example
     * const wrappers = pageManager.getAllWrappers();
     * // Get all `image` components from the project
     * const allImages = wrappers.map(wrp => wrp.findType('image')).flat();
     */
    PageManager.prototype.getAllWrappers = function () {
        var pages = this.getAll();
        return (0,index_all.unique)((0,index_all.flatten)(pages.map(function (page) { return page.getAllFrames().map(function (frame) { return frame.getComponent(); }); })));
    };
    /**
     * Change the selected page. This will switch the page rendered in canvas
     * @param {String|[Page]} page Page or page id
     * @returns {this}
     * @example
     * pageManager.select('page-id');
     * // or by passing the page
     * const somePage = pageManager.get('page-id');
     * pageManager.select(somePage);
     */
    PageManager.prototype.select = function (page, opts) {
        if (opts === void 0) { opts = {}; }
        var _a = this, em = _a.em, model = _a.model, events = _a.events;
        var pg = (0,index_all.isString)(page) ? this.get(page) : page;
        if (pg) {
            em.trigger(events.selectBefore, pg, opts);
            model.set('selected', pg, opts);
        }
        return this;
    };
    /**
     * Get the selected page
     * @returns {[Page]}
     * @example
     * const selectedPage = pageManager.getSelected();
     */
    PageManager.prototype.getSelected = function () {
        return this.model.get('selected');
    };
    PageManager.prototype.destroy = function () {
        var _this = this;
        this.pages.off().reset();
        this.model.stopListening();
        this.model.clear({ silent: true });
        //@ts-ignore
        ['selected', 'model'].map(function (i) { return (_this[i] = 0); });
    };
    PageManager.prototype.store = function () {
        return this.getProjectData();
    };
    PageManager.prototype.load = function (data) {
        var result = this.loadProjectData(data, { all: this.pages, reset: true });
        this.pages.forEach(function (page) { return page.getFrames().initRefs(); });
        return result;
    };
    PageManager.prototype._initPage = function () {
        return this.get(this.config.selected) || this.getMain();
    };
    PageManager.prototype._createId = function () {
        var pages = this.getAll();
        var len = pages.length + 16;
        var pagesMap = this.getAllMap();
        var id;
        do {
            id = (0,mixins.createId)(len);
        } while (pagesMap[id]);
        return id;
    };
    return PageManager;
}(ItemManagerModule));
/* harmony default export */ const pages = (PageManager);

;// CONCATENATED MODULE: ./src/i18n/locale/en.js
var traitInputAttr = {
  placeholder: 'eg. Text here'
};
/* harmony default export */ const en = ({
  assetManager: {
    addButton: 'Add image',
    inputPlh: 'http://path/to/the/image.jpg',
    modalTitle: 'Select Image',
    uploadTitle: 'Drop files here or click to upload'
  },
  // Here just as a reference, GrapesJS core doesn't contain any block,
  // so this should be omitted from other local files
  blockManager: {
    labels: {
      // 'block-id': 'Block Label',
    },
    categories: {
      // 'category-id': 'Category Label',
    }
  },
  domComponents: {
    names: {
      '': 'Box',
      wrapper: 'Body',
      text: 'Text',
      comment: 'Comment',
      image: 'Image',
      video: 'Video',
      label: 'Label',
      link: 'Link',
      map: 'Map',
      tfoot: 'Table foot',
      tbody: 'Table body',
      thead: 'Table head',
      table: 'Table',
      row: 'Table row',
      cell: 'Table cell'
    }
  },
  deviceManager: {
    device: 'Device',
    devices: {
      desktop: 'Desktop',
      tablet: 'Tablet',
      mobileLandscape: 'Mobile Landscape',
      mobilePortrait: 'Mobile Portrait'
    }
  },
  panels: {
    buttons: {
      titles: {
        preview: 'Preview',
        fullscreen: 'Fullscreen',
        'sw-visibility': 'View components',
        'export-template': 'View code',
        'open-sm': 'Open Style Manager',
        'open-tm': 'Settings',
        'open-layers': 'Open Layer Manager',
        'open-blocks': 'Open Blocks'
      }
    }
  },
  selectorManager: {
    label: 'Classes',
    selected: 'Selected',
    emptyState: '- State -',
    states: {
      hover: 'Hover',
      active: 'Click',
      'nth-of-type(2n)': 'Even/Odd'
    }
  },
  styleManager: {
    empty: 'Select an element before using Style Manager',
    layer: 'Layer',
    fileButton: 'Images',
    sectors: {
      general: 'General',
      layout: 'Layout',
      typography: 'Typography',
      decorations: 'Decorations',
      extra: 'Extra',
      flex: 'Flex',
      dimension: 'Dimension'
    },
    // Default names for sub properties in Composite and Stack types.
    // Other labels are generated directly from their property names (eg. 'font-size' will be 'Font size').
    properties: {
      'text-shadow-h': 'X',
      'text-shadow-v': 'Y',
      'text-shadow-blur': 'Blur',
      'text-shadow-color': 'Color',
      'box-shadow-h': 'X',
      'box-shadow-v': 'Y',
      'box-shadow-blur': 'Blur',
      'box-shadow-spread': 'Spread',
      'box-shadow-color': 'Color',
      'box-shadow-type': 'Type',
      'margin-top-sub': 'Top',
      'margin-right-sub': 'Right',
      'margin-bottom-sub': 'Bottom',
      'margin-left-sub': 'Left',
      'padding-top-sub': 'Top',
      'padding-right-sub': 'Right',
      'padding-bottom-sub': 'Bottom',
      'padding-left-sub': 'Left',
      'border-width-sub': 'Width',
      'border-style-sub': 'Style',
      'border-color-sub': 'Color',
      'border-top-left-radius-sub': 'Top Left',
      'border-top-right-radius-sub': 'Top Right',
      'border-bottom-right-radius-sub': 'Bottom Right',
      'border-bottom-left-radius-sub': 'Bottom Left',
      'transform-rotate-x': 'Rotate X',
      'transform-rotate-y': 'Rotate Y',
      'transform-rotate-z': 'Rotate Z',
      'transform-scale-x': 'Scale X',
      'transform-scale-y': 'Scale Y',
      'transform-scale-z': 'Scale Z',
      'transition-property-sub': 'Property',
      'transition-duration-sub': 'Duration',
      'transition-timing-function-sub': 'Timing',
      'background-image-sub': 'Image',
      'background-repeat-sub': 'Repeat',
      'background-position-sub': 'Position',
      'background-attachment-sub': 'Attachment',
      'background-size-sub': 'Size'
    }
    // Translate options in style properties
    // options: {
    //   float: { // Id of the property
    //     ...
    //     left: 'Left', // {option id}: {Option label}
    //   }
    // }
  },

  traitManager: {
    empty: 'Select an element before using Trait Manager',
    label: 'Component settings',
    categories: {
      // categoryId: 'Category label',
    },
    traits: {
      // The core library generates the name by their `name` property
      labels: {
        // id: 'Id',
        // alt: 'Alt',
        // title: 'Title',
        // href: 'Href',
      },
      // In a simple trait, like text input, these are used on input attributes
      attributes: {
        id: traitInputAttr,
        alt: traitInputAttr,
        title: traitInputAttr,
        href: {
          placeholder: 'eg. https://google.com'
        }
      },
      // In a trait like select, these are used to translate option names
      options: {
        target: {
          false: 'This window',
          _blank: 'New window'
        }
      }
    }
  },
  storageManager: {
    recover: 'Do you want to recover unsaved changes?'
  }
});
;// CONCATENATED MODULE: ./src/i18n/config.ts

var i18n_config_config = {
    locale: 'en',
    localeFallback: 'en',
    detectLocale: true,
    debug: false,
    messages: { en: en },
    messagesAdd: undefined,
};
/* harmony default export */ const i18n_config = (i18n_config_config);

;// CONCATENATED MODULE: ./src/i18n/types.ts
/**{START_EVENTS}*/
var I18nEvents;
(function (I18nEvents) {
    /**
     * @event `i18n:add` New set of messages is added.
     * @example
     * editor.on('i18n:add', (messages) => { ... });
     */
    I18nEvents["add"] = "i18n:add";
    /**
     * @event `i18n:update` The set of messages is updated.
     * @example
     * editor.on('i18n:update', (messages) => { ... });
     */
    I18nEvents["update"] = "i18n:update";
    /**
     * @event `i18n:locale` Locale changed.
     * @example
     * editor.on('i18n:locale', ({ value, valuePrev }) => { ... });
     */
    I18nEvents["locale"] = "i18n:locale";
})(I18nEvents || (I18nEvents = {}));
/**{END_EVENTS}*/
// need this to avoid the TS documentation generator to break
/* harmony default export */ const i18n_types = (I18nEvents);

;// CONCATENATED MODULE: ./src/i18n/index.ts
var i18n_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
/**
 * You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](https://github.com/GrapesJS/grapesjs/blob/master/src/i18n/config.ts)
 * ```js
 * const editor = grapesjs.init({
 *  i18n: {
 *    locale: 'en',
 *    localeFallback: 'en',
 *    messages: {
 *      it: { hello: 'Ciao', ... },
 *      ...
 *    }
 *  }
 * })
 * ```
 *
 * Once the editor is instantiated you can use its API. Before using these methods you should get the module from the instance
 *
 * ```js
 * const i18n = editor.I18n;
 * ```
 *
 * {REPLACE_EVENTS}
 *
 * @module I18n
 */





var I18nModule = /** @class */ (function (_super) {
    i18n_extends(I18nModule, _super);
    /**
     * Initialize module
     * @param {Object} config Configurations
     * @private
     */
    function I18nModule(em) {
        var _this = _super.call(this, em, 'I18n', i18n_config) || this;
        _this.events = i18n_types;
        var add = _this.config.messagesAdd;
        add && _this.addMessages(add);
        if (_this.config.detectLocale) {
            _this.config.locale = _this._localLang();
        }
        return _this;
    }
    /**
     * Get configuration object
     * @name getConfig
     * @function
     * @return {Object}
     */
    /**
     * Update current locale
     * @param {String} locale Locale value
     * @returns {this}
     * @example
     * i18n.setLocale('it');
     */
    I18nModule.prototype.setLocale = function (locale) {
        var _a = this, em = _a.em, config = _a.config, events = _a.events;
        em.trigger(events.locale, { value: locale, valuePrev: config.locale });
        config.locale = locale;
        return this;
    };
    /**
     * Get current locale
     * @returns {String} Current locale value
     */
    I18nModule.prototype.getLocale = function () {
        return this.config.locale;
    };
    /**
     * Get all messages
     * @param {String} [lang] Specify the language of messages to return
     * @param {Object} [opts] Options
     * @param {Boolean} [opts.debug] Show warnings in case of missing language
     * @returns {Object}
     * @example
     * i18n.getMessages();
     * // -> { en: { hello: '...' }, ... }
     * i18n.getMessages('en');
     * // -> { hello: '...' }
     */
    I18nModule.prototype.getMessages = function (lang, opts) {
        if (opts === void 0) { opts = {}; }
        var messages = this.config.messages;
        lang && !messages[lang] && this._debug("'".concat(lang, "' i18n lang not found"), opts);
        return lang ? messages[lang] : messages;
    };
    /**
     * Set new set of messages
     * @param {Object} msg Set of messages
     * @returns {this}
     * @example
     * i18n.getMessages();
     * // -> { en: { msg1: 'Msg 1', msg2: 'Msg 2', } }
     * i18n.setMessages({ en: { msg2: 'Msg 2 up', msg3: 'Msg 3', } });
     * // Set replaced
     * i18n.getMessages();
     * // -> { en: { msg2: 'Msg 2 up', msg3: 'Msg 3', } }
     */
    I18nModule.prototype.setMessages = function (msg) {
        var _a = this, em = _a.em, config = _a.config, events = _a.events;
        config.messages = msg;
        em.trigger(events.update, msg);
        return this;
    };
    /**
     * Update messages
     * @param {Object} msg Set of messages to add
     * @returns {this}
     * @example
     * i18n.getMessages();
     * // -> { en: { msg1: 'Msg 1', msg2: 'Msg 2', } }
     * i18n.addMessages({ en: { msg2: 'Msg 2 up', msg3: 'Msg 3', } });
     * // Set updated
     * i18n.getMessages();
     * // -> { en: { msg1: 'Msg 1', msg2: 'Msg 2 up', msg3: 'Msg 3', } }
     */
    I18nModule.prototype.addMessages = function (msg) {
        var _a = this, em = _a.em, events = _a.events, config = _a.config;
        var messages = config.messages;
        em.trigger(events.add, msg);
        this.setMessages((0,mixins.deepMerge)(messages, msg));
        return this;
    };
    /**
     * Translate the locale message
     * @param {String} key Label to translate
     * @param {Object} [opts] Options for the translation
     * @param {Object} [opts.params] Params for the translation
     * @param {Boolean} [opts.debug] Show warnings in case of missing resources
     * @returns {String}
     * @example
     * obj.setMessages({
     *  en: { msg: 'Msg', msg2: 'Msg {test}'},
     *  it: { msg2: 'Msg {test} it'},
     * });
     * obj.t('msg');
     * // -> outputs `Msg`
     * obj.t('msg2', { params: { test: 'hello' } });  // use params
     * // -> outputs `Msg hello`
     * obj.t('msg2', { l: 'it', params: { test: 'hello' } });  // custom local
     * // -> outputs `Msg hello it`
     */
    I18nModule.prototype.t = function (key, opts) {
        if (opts === void 0) { opts = {}; }
        var config = this.config;
        var param = opts.params || {};
        var locale = opts.l || this.getLocale();
        var localeFlb = opts.lFlb || config.localeFallback;
        var result = this._getMsg(key, locale, opts);
        // Try with fallback
        if (!result)
            result = this._getMsg(key, localeFlb, opts);
        !result && this._debug("'".concat(key, "' i18n key not found in '").concat(locale, "' lang"), opts);
        result = result && (0,index_all.isString)(result) ? this._addParams(result, param) : result;
        return result;
    };
    I18nModule.prototype._localLang = function () {
        var nav = ((0,mixins.hasWin)() && window.navigator) || {};
        // @ts-ignore
        var lang = nav.language || nav.userLanguage;
        return lang ? lang.split('-')[0] : 'en';
    };
    I18nModule.prototype._addParams = function (str, params) {
        var reg = new RegExp('{([\\w\\d-]*)}', 'g');
        return str.replace(reg, function (m, val) { return params[val] || ''; }).trim();
    };
    I18nModule.prototype._getMsg = function (key, locale, opts) {
        if (opts === void 0) { opts = {}; }
        var msgSet = this.getMessages(locale, opts);
        // Lang set is missing
        if (!msgSet)
            return;
        var result = msgSet[key];
        // Check for nested getter
        if (!result && key.indexOf('.') > 0) {
            result = key.split('.').reduce(function (lang, key) {
                if ((0,index_all.isUndefined)(lang))
                    return;
                return lang[key];
            }, msgSet);
        }
        return result;
    };
    I18nModule.prototype._debug = function (str, opts) {
        if (opts === void 0) { opts = {}; }
        var _a = this, em = _a.em, config = _a.config;
        (opts.debug || config.debug) && em && em.logWarning(str);
    };
    I18nModule.prototype.destroy = function () { };
    return I18nModule;
}(abstract_Module));
/* harmony default export */ const i18n = (I18nModule);

;// CONCATENATED MODULE: ./src/utils/Sorter.ts
var Sorter_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var Sorter_assign = (undefined && undefined.__assign) || function () {
    Sorter_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return Sorter_assign.apply(this, arguments);
};





var Sorter_noop = function () { };
var targetSpotType = CanvasSpot/* CanvasSpotBuiltInTypes */.q.Target;
var spotTarget = {
    id: 'sorter-target',
    type: targetSpotType,
};
var Sorter = /** @class */ (function (_super) {
    Sorter_extends(Sorter, _super);
    function Sorter() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    /** @ts-ignore */
    Sorter.prototype.initialize = function (opt) {
        if (opt === void 0) { opt = {}; }
        this.opt = opt || {};
        (0,index_all.bindAll)(this, 'startSort', 'onMove', 'endMove', 'rollback', 'updateOffset', 'moveDragHelper');
        var o = opt || {};
        this.elT = 0;
        this.elL = 0;
        this.borderOffset = o.borderOffset || 10;
        var el = o.container;
        this.el = typeof el === 'string' ? document.querySelector(el) : el;
        this.$el = (0,cash_dom["default"])(this.el); // TODO check if necessary
        this.containerSel = o.containerSel || 'div';
        this.itemSel = o.itemSel || 'div';
        this.draggable = o.draggable || true;
        this.nested = !!o.nested;
        this.pfx = o.pfx || '';
        this.ppfx = o.ppfx || '';
        this.freezeClass = o.freezeClass || this.pfx + 'freezed';
        this.onStart = o.onStart || Sorter_noop;
        this.onEndMove = o.onEndMove;
        this.customTarget = o.customTarget;
        this.onEnd = o.onEnd;
        this.direction = o.direction || 'v'; // v (vertical), h (horizontal), a (auto)
        this.onMoveClb = o.onMove;
        this.relative = o.relative || false;
        this.ignoreViewChildren = !!o.ignoreViewChildren;
        this.plh = o.placer;
        // Frame offset
        this.wmargin = o.wmargin || 0;
        this.offTop = o.offsetTop || 0;
        this.offLeft = o.offsetLeft || 0;
        this.document = o.document || document;
        this.em = o.em;
        this.canvasRelative = !!o.canvasRelative;
        this.selectOnEnd = !o.avoidSelectOnEnd;
        this.scale = o.scale;
        var em = this.em;
        if (em === null || em === void 0 ? void 0 : em.on) {
            em.on(em.Canvas.events.refresh, this.updateOffset);
            this.updateOffset();
        }
    };
    Sorter.prototype.getScale = function () {
        return (0,index_all.result)(this, 'scale') || 1;
    };
    Sorter.prototype.getContainerEl = function (elem) {
        if (elem)
            this.el = elem;
        if (!this.el) {
            var el = this.opt.container;
            this.el = typeof el === 'string' ? document.querySelector(el) : el;
            this.$el = (0,cash_dom["default"])(this.el); // TODO check if necessary
        }
        return this.el;
    };
    Sorter.prototype.getDocuments = function (el) {
        var em = this.em;
        var elDoc = el ? el.ownerDocument : em === null || em === void 0 ? void 0 : em.Canvas.getBody().ownerDocument;
        var docs = [document];
        elDoc && docs.push(elDoc);
        return docs;
    };
    /**
     * Triggered when the offset of the editro is changed
     */
    Sorter.prototype.updateOffset = function () {
        var _a;
        var offset = ((_a = this.em) === null || _a === void 0 ? void 0 : _a.get('canvasOffset')) || {};
        this.offTop = offset.top;
        this.offLeft = offset.left;
    };
    /**
     * Set content to drop
     * @param {String|Object} content
     */
    Sorter.prototype.setDropContent = function (content) {
        delete this.dropModel;
        this.dropContent = content;
    };
    Sorter.prototype.updateTextViewCursorPosition = function (e) {
        var em = this.em;
        if (!em)
            return;
        var Canvas = em.Canvas;
        var targetDoc = Canvas.getDocument();
        var range = null;
        if (targetDoc.caretRangeFromPoint) {
            // Chrome
            var poiner = (0,dom/* getPointerEvent */.VB)(e);
            range = targetDoc.caretRangeFromPoint(poiner.clientX, poiner.clientY);
        }
        else if (e.rangeParent) {
            // Firefox
            range = targetDoc.createRange();
            range.setStart(e.rangeParent, e.rangeOffset);
        }
        var sel = Canvas.getWindow().getSelection();
        Canvas.getFrameEl().focus();
        sel === null || sel === void 0 ? void 0 : sel.removeAllRanges();
        range && (sel === null || sel === void 0 ? void 0 : sel.addRange(range));
        this.setContentEditable(this.activeTextModel, true);
    };
    Sorter.prototype.setContentEditable = function (model, mode) {
        if (model) {
            // @ts-ignore
            var el = model.getEl();
            if (el.contentEditable != mode)
                el.contentEditable = mode;
        }
    };
    /**
     * Toggle cursor while sorting
     * @param {Boolean} active
     */
    Sorter.prototype.toggleSortCursor = function (active) {
        var em = this.em;
        var cv = em === null || em === void 0 ? void 0 : em.Canvas;
        // Avoid updating body className as it causes a huge repaint
        // Noticeable with "fast" drag of blocks
        cv && (active ? cv.startAutoscroll() : cv.stopAutoscroll());
    };
    /**
     * Set drag helper
     * @param {HTMLElement} el
     * @param {Event} event
     */
    Sorter.prototype.setDragHelper = function (el, event) {
        var ev = event || '';
        var clonedEl = el.cloneNode(true);
        var rect = el.getBoundingClientRect();
        var computed = getComputedStyle(el);
        var style = '';
        for (var i = 0; i < computed.length; i++) {
            var prop = computed[i];
            style += "".concat(prop, ":").concat(computed.getPropertyValue(prop), ";");
        }
        document.body.appendChild(clonedEl);
        clonedEl.className += " ".concat(this.pfx, "bdrag");
        clonedEl.setAttribute('style', style);
        this.dragHelper = clonedEl;
        clonedEl.style.width = "".concat(rect.width, "px");
        clonedEl.style.height = "".concat(rect.height, "px");
        ev && this.moveDragHelper(ev);
        // Listen mouse move events
        if (this.em) {
            var $doc = (0,cash_dom["default"])(this.em.Canvas.getBody().ownerDocument);
            $doc.off('mousemove', this.moveDragHelper).on('mousemove', this.moveDragHelper);
        }
        (0,cash_dom["default"])(document).off('mousemove', this.moveDragHelper).on('mousemove', this.moveDragHelper);
    };
    /**
     * Update the position of the helper
     * @param  {Event} e
     */
    Sorter.prototype.moveDragHelper = function (e) {
        var doc = e.target.ownerDocument;
        if (!this.dragHelper || !doc) {
            return;
        }
        var posY = e.pageY;
        var posX = e.pageX;
        var addTop = 0;
        var addLeft = 0;
        // @ts-ignore
        var window = doc.defaultView || doc.parentWindow;
        var frame = window.frameElement;
        var dragHelperStyle = this.dragHelper.style;
        // If frame is present that means mouse has moved over the editor's canvas,
        // which is rendered inside the iframe and the mouse move event comes from
        // the iframe, not the parent window. Mouse position relative to the frame's
        // parent window needs to account for the frame's position relative to the
        // parent window.
        if (frame) {
            var frameRect = frame.getBoundingClientRect();
            addTop = frameRect.top + document.documentElement.scrollTop;
            addLeft = frameRect.left + document.documentElement.scrollLeft;
            posY = e.clientY;
            posX = e.clientX;
        }
        dragHelperStyle.top = posY + addTop + 'px';
        dragHelperStyle.left = posX + addLeft + 'px';
    };
    /**
     * Returns true if the element matches with selector
     * @param {Element} el
     * @param {String} selector
     * @return {Boolean}
     */
    Sorter.prototype.matches = function (el, selector) {
        return mixins.matches.call(el, selector);
    };
    /**
     * Closest parent
     * @param {Element} el
     * @param {String} selector
     * @return {Element|null}
     */
    Sorter.prototype.closest = function (el, selector) {
        if (!el)
            return;
        var elem = el.parentNode;
        while (elem && elem.nodeType === 1) {
            if (this.matches(elem, selector))
                return elem;
            elem = elem.parentNode;
        }
    };
    /**
     * Get the offset of the element
     * @param  {HTMLElement} el
     * @return {Object}
     */
    Sorter.prototype.offset = function (el) {
        var rect = el.getBoundingClientRect();
        return {
            top: rect.top + document.body.scrollTop,
            left: rect.left + document.body.scrollLeft,
        };
    };
    /**
     * Create placeholder
     * @return {HTMLElement}
     */
    Sorter.prototype.createPlaceholder = function () {
        var pfx = this.pfx;
        var el = document.createElement('div');
        var ins = document.createElement('div');
        el.className = pfx + 'placeholder';
        el.style.display = 'none';
        el.style.pointerEvents = 'none';
        ins.className = pfx + 'placeholder-int';
        el.appendChild(ins);
        return el;
    };
    /**
     * Picking component to move
     * @param {HTMLElement} src
     * */
    Sorter.prototype.startSort = function (src, opts) {
        var _a, _b;
        if (opts === void 0) { opts = {}; }
        var _c = this, em = _c.em, itemSel = _c.itemSel, containerSel = _c.containerSel, plh = _c.plh;
        var container = this.getContainerEl(opts.container);
        var docs = this.getDocuments(src);
        var srcModel;
        delete this.dropModel;
        delete this.target;
        delete this.prevTarget;
        this.moved = false;
        // Check if the start element is a valid one, if not, try the closest valid one
        if (src && !this.matches(src, "".concat(itemSel, ", ").concat(containerSel))) {
            src = this.closest(src, itemSel);
        }
        this.sourceEl = src;
        // Create placeholder if doesn't exist yet
        if (!plh) {
            this.plh = this.createPlaceholder();
            container.appendChild(this.plh);
        }
        if (src) {
            srcModel = this.getSourceModel(src);
            (srcModel === null || srcModel === void 0 ? void 0 : srcModel.set) && srcModel.set('status', 'freezed');
            this.srcModel = srcModel;
        }
        (0,dom.on)(container, 'mousemove dragover', this.onMove);
        (0,dom.on)(docs, 'mouseup dragend touchend', this.endMove);
        (0,dom.on)(docs, 'keydown', this.rollback);
        this.onStart({
            sorter: this,
            target: srcModel,
            // @ts-ignore
            parent: srcModel && ((_a = srcModel.parent) === null || _a === void 0 ? void 0 : _a.call(srcModel)),
            // @ts-ignore
            index: srcModel && ((_b = srcModel.index) === null || _b === void 0 ? void 0 : _b.call(srcModel)),
        });
        // Avoid strange effects on dragging
        em === null || em === void 0 ? void 0 : em.clearSelection();
        this.toggleSortCursor(true);
        em === null || em === void 0 ? void 0 : em.trigger('sorter:drag:start', src, srcModel);
    };
    /**
     * Get the model from HTMLElement target
     * @return {Model|null}
     */
    Sorter.prototype.getTargetModel = function (el) {
        var elem = el || this.target;
        return (0,cash_dom["default"])(elem).data('model');
    };
    /**
     * Get the model of the current source element (element to drag)
     * @return {Model}
     */
    Sorter.prototype.getSourceModel = function (source, _a) {
        var _this = this;
        var _b = _a === void 0 ? {} : _a, target = _b.target, _c = _b.avoidChildren, avoidChildren = _c === void 0 ? 1 : _c;
        var _d = this, em = _d.em, sourceEl = _d.sourceEl;
        var src = source || sourceEl;
        var _e = this, dropModel = _e.dropModel, dropContent = _e.dropContent;
        var isTextable = function (src) {
            return src && target && src.opt && src.opt.avoidChildren && _this.isTextableActive(src, target);
        };
        if (dropContent && em) {
            if (isTextable(dropModel)) {
                dropModel = undefined;
            }
            if (!dropModel) {
                var comps = em.Components.getComponents();
                var opts = {
                    avoidChildren: avoidChildren,
                    avoidStore: 1,
                    avoidUpdateStyle: 1,
                };
                var tempModel = comps.add(dropContent, Sorter_assign(Sorter_assign({}, opts), { temporary: true }));
                // @ts-ignore
                dropModel = comps.remove(tempModel, opts);
                dropModel = dropModel instanceof Array ? dropModel[0] : dropModel;
                this.dropModel = dropModel;
                if (isTextable(dropModel)) {
                    return this.getSourceModel(src, { target: target, avoidChildren: 0 });
                }
            }
            return dropModel;
        }
        return src && (0,cash_dom["default"])(src).data('model');
    };
    /**
     * Highlight target
     * @param  {Model|null} model
     */
    Sorter.prototype.selectTargetModel = function (model, source) {
        if (model instanceof common/* Collection */.FE) {
            return;
        }
        // Prevents loops in Firefox
        // https://github.com/GrapesJS/grapesjs/issues/2911
        if (source && source === model)
            return;
        var targetModel = this.targetModel;
        // Reset the previous model but not if it's the same as the source
        // https://github.com/GrapesJS/grapesjs/issues/2478#issuecomment-570314736
        if (targetModel && targetModel !== this.srcModel) {
            targetModel.set('status', '');
        }
        if (model === null || model === void 0 ? void 0 : model.set) {
            var cv_1 = this.em.Canvas;
            var Select = CanvasSpot/* CanvasSpotBuiltInTypes */.q.Select, Hover = CanvasSpot/* CanvasSpotBuiltInTypes */.q.Hover, Spacing = CanvasSpot/* CanvasSpotBuiltInTypes */.q.Spacing;
            [Select, Hover, Spacing].forEach(function (type) { return cv_1.removeSpots({ type: type }); });
            cv_1.addSpot(Sorter_assign(Sorter_assign({}, spotTarget), { component: model }));
            model.set('status', 'selected-parent');
            this.targetModel = model;
        }
    };
    /**
     * During move
     * @param {Event} e
     * */
    Sorter.prototype.onMove = function (e) {
        var ev = e;
        var _a = this, em = _a.em, onMoveClb = _a.onMoveClb, plh = _a.plh, customTarget = _a.customTarget;
        this.moved = true;
        // Turn placeholder visibile
        var dsp = plh.style.display;
        if (!dsp || dsp === 'none')
            plh.style.display = 'block';
        // Cache all necessary positions
        var eO = this.offset(this.el);
        this.elT = this.wmargin ? Math.abs(eO.top) : eO.top;
        this.elL = this.wmargin ? Math.abs(eO.left) : eO.left;
        var rY = e.pageY - this.elT + this.el.scrollTop;
        var rX = e.pageX - this.elL + this.el.scrollLeft;
        if (this.canvasRelative && em) {
            var mousePos = em.Canvas.getMouseRelativeCanvas(e, { noScroll: 1 });
            rX = mousePos.x;
            rY = mousePos.y;
        }
        this.rX = rX;
        this.rY = rY;
        this.eventMove = e;
        //var targetNew = this.getTargetFromEl(e.target);
        var sourceModel = this.getSourceModel();
        var targetEl = customTarget ? customTarget({ sorter: this, event: e }) : e.target;
        var dims = this.dimsFromTarget(targetEl, rX, rY);
        var target = this.target;
        var targetModel = target && this.getTargetModel(target);
        this.selectTargetModel(targetModel, sourceModel);
        if (!targetModel)
            plh.style.display = 'none';
        if (!target)
            return;
        this.lastDims = dims;
        var pos = this.findPosition(dims, rX, rY);
        if (this.isTextableActive(sourceModel, targetModel)) {
            this.activeTextModel = targetModel;
            plh.style.display = 'none';
            this.lastPos = pos;
            this.updateTextViewCursorPosition(ev);
        }
        else {
            this.disableTextable();
            delete this.activeTextModel;
            // If there is a significant changes with the pointer
            if (!this.lastPos || this.lastPos.index != pos.index || this.lastPos.method != pos.method) {
                this.movePlaceholder(this.plh, dims, pos, this.prevTargetDim);
                if (!this.$plh)
                    this.$plh = (0,cash_dom["default"])(this.plh);
                // With canvasRelative the offset is calculated automatically for
                // each element
                if (!this.canvasRelative) {
                    if (this.offTop)
                        this.$plh.css('top', '+=' + this.offTop + 'px');
                    if (this.offLeft)
                        this.$plh.css('left', '+=' + this.offLeft + 'px');
                }
                this.lastPos = pos;
            }
        }
        (0,index_all.isFunction)(onMoveClb) &&
            onMoveClb({
                event: e,
                target: sourceModel,
                parent: targetModel,
                index: pos.index + (pos.method == 'after' ? 1 : 0),
            });
        em &&
            em.trigger('sorter:drag', {
                target: target,
                targetModel: targetModel,
                sourceModel: sourceModel,
                dims: dims,
                pos: pos,
                x: rX,
                y: rY,
            });
    };
    Sorter.prototype.isTextableActive = function (src, trg) {
        var _a;
        return ((_a = src === null || src === void 0 ? void 0 : src.get) === null || _a === void 0 ? void 0 : _a.call(src, 'textable')) && (trg === null || trg === void 0 ? void 0 : trg.isInstanceOf('text'));
    };
    Sorter.prototype.disableTextable = function () {
        var activeTextModel = this.activeTextModel;
        // @ts-ignore
        activeTextModel === null || activeTextModel === void 0 ? void 0 : activeTextModel.getView().disableEditing();
        this.setContentEditable(activeTextModel, false);
    };
    /**
     * Returns true if the elements is in flow, so is not in flow where
     * for example the component is with float:left
     * @param  {HTMLElement} el
     * @param  {HTMLElement} parent
     * @return {Boolean}
     * @private
     * */
    Sorter.prototype.isInFlow = function (el, parent) {
        if (!el)
            return false;
        parent = parent || document.body;
        var ch = -1, h;
        var elem = el;
        h = elem.offsetHeight;
        if ( /*h < ch || */!this.styleInFlow(elem, parent))
            return false;
        else
            return true;
    };
    /**
     * Check if el has style to be in flow
     * @param  {HTMLElement} el
     * @param  {HTMLElement} parent
     * @return {Boolean}
     * @private
     */
    Sorter.prototype.styleInFlow = function (el, parent) {
        if ((0,dom/* isTextNode */.BM)(el))
            return;
        var style = el.style || {};
        var $el = (0,cash_dom["default"])(el);
        var $parent = parent && (0,cash_dom["default"])(parent);
        if (style.overflow && style.overflow !== 'visible')
            return;
        var propFloat = $el.css('float');
        if (propFloat && propFloat !== 'none')
            return;
        if ($parent && $parent.css('display') == 'flex' && $parent.css('flex-direction') !== 'column')
            return;
        switch (style.position) {
            case 'static':
            case 'relative':
            case '':
                break;
            default:
                return;
        }
        switch (el.tagName) {
            case 'TR':
            case 'TBODY':
            case 'THEAD':
            case 'TFOOT':
                return true;
        }
        switch ($el.css('display')) {
            case 'block':
            case 'list-item':
            case 'table':
            case 'flex':
            case 'grid':
                return true;
        }
        return;
    };
    /**
     * Check if the target is valid with the actual source
     * @param  {HTMLElement} trg
     * @return {Boolean}
     */
    Sorter.prototype.validTarget = function (trg, src) {
        var trgModel = this.getTargetModel(trg);
        var srcModel = this.getSourceModel(src, { target: trgModel });
        // @ts-ignore
        src = srcModel && srcModel.view && srcModel.view.el;
        trg = trgModel && trgModel.view && trgModel.view.el;
        var result = {
            valid: true,
            src: src,
            srcModel: srcModel,
            trg: trg,
            trgModel: trgModel,
            draggable: false,
            droppable: false,
            dragInfo: '',
            dropInfo: '',
        };
        if (!src || !trg) {
            result.valid = false;
            return result;
        }
        // Check if the source is draggable in target
        var draggable = srcModel.get('draggable');
        if ((0,index_all.isFunction)(draggable)) {
            var res = draggable(srcModel, trgModel);
            result.dragInfo = res;
            result.draggable = res;
            draggable = res;
        }
        else {
            draggable = draggable instanceof Array ? draggable.join(', ') : draggable;
            result.dragInfo = draggable;
            draggable = (0,index_all.isString)(draggable) ? this.matches(trg, draggable) : draggable;
            result.draggable = draggable;
        }
        // Check if the target could accept the source
        var droppable = trgModel.get('droppable');
        if ((0,index_all.isFunction)(droppable)) {
            var res = droppable(srcModel, trgModel);
            result.droppable = res;
            result.dropInfo = res;
            droppable = res;
        }
        else {
            droppable = droppable instanceof common/* Collection */.FE ? 1 : droppable;
            droppable = droppable instanceof Array ? droppable.join(', ') : droppable;
            result.dropInfo = droppable;
            droppable = (0,index_all.isString)(droppable) ? this.matches(src, droppable) : droppable;
            droppable = draggable && this.isTextableActive(srcModel, trgModel) ? 1 : droppable;
            result.droppable = droppable;
        }
        if (!droppable || !draggable) {
            result.valid = false;
        }
        return result;
    };
    /**
     * Get dimensions of nodes relative to the coordinates
     * @param  {HTMLElement} target
     * @param {number} rX Relative X position
     * @param {number} rY Relative Y position
     * @return {Array<Array>}
     */
    Sorter.prototype.dimsFromTarget = function (target, rX, rY) {
        if (rX === void 0) { rX = 0; }
        if (rY === void 0) { rY = 0; }
        var em = this.em;
        var dims = [];
        if (!target) {
            return dims;
        }
        // Select the first valuable target
        if (!this.matches(target, "".concat(this.itemSel, ", ").concat(this.containerSel))) {
            target = this.closest(target, this.itemSel);
        }
        // If draggable is an array the target will be one of those
        if (this.draggable instanceof Array) {
            target = this.closest(target, this.draggable.join(','));
        }
        if (!target) {
            return dims;
        }
        // Check if the target is different from the previous one
        if (this.prevTarget && this.prevTarget != target) {
            delete this.prevTarget;
        }
        // New target found
        if (!this.prevTarget) {
            this.targetP = this.closest(target, this.containerSel);
            // Check if the source is valid with the target
            var validResult = this.validTarget(target);
            em && em.trigger('sorter:drag:validation', validResult);
            if (!validResult.valid && this.targetP) {
                return this.dimsFromTarget(this.targetP, rX, rY);
            }
            this.prevTarget = target;
            this.prevTargetDim = this.getDim(target);
            this.cacheDimsP = this.getChildrenDim(this.targetP);
            this.cacheDims = this.getChildrenDim(target);
        }
        // If the target is the previous one will return the cached dims
        if (this.prevTarget == target)
            dims = this.cacheDims;
        // Target when I will drop element to sort
        this.target = this.prevTarget;
        // Generally, on any new target the poiner enters inside its area and
        // triggers nearBorders(), so have to take care of this
        if (this.nearBorders(this.prevTargetDim, rX, rY) || (!this.nested && !this.cacheDims.length)) {
            var targetParent = this.targetP;
            if (targetParent && this.validTarget(targetParent).valid) {
                dims = this.cacheDimsP;
                this.target = targetParent;
            }
        }
        delete this.lastPos;
        return dims;
    };
    /**
     * Get valid target from element
     * This method should replace dimsFromTarget()
     * @param  {HTMLElement} el
     * @return {HTMLElement}
     */
    Sorter.prototype.getTargetFromEl = function (el) {
        var target = el;
        var targetParent;
        var targetPrev = this.targetPrev;
        var em = this.em;
        var containerSel = this.containerSel;
        var itemSel = this.itemSel;
        // Select the first valuable target
        if (!this.matches(target, "".concat(itemSel, ", ").concat(containerSel))) {
            target = this.closest(target, itemSel);
        }
        // If draggable is an array the target will be one of those
        // TODO check if this options is used somewhere
        if (this.draggable instanceof Array) {
            target = this.closest(target, this.draggable.join(','));
        }
        // Check if the target is different from the previous one
        if (targetPrev && targetPrev != target) {
            delete this.targetPrev;
        }
        // New target found
        if (!this.targetPrev) {
            targetParent = this.closest(target, containerSel);
            // If the current target is not valid (src/trg reasons) try with
            // the parent one (if exists)
            var validResult = this.validTarget(target);
            em && em.trigger('sorter:drag:validation', validResult);
            if (!validResult.valid && targetParent) {
                return this.getTargetFromEl(targetParent);
            }
            this.targetPrev = target;
        }
        // Generally, on any new target the poiner enters inside its area and
        // triggers nearBorders(), so have to take care of this
        if (this.nearElBorders(target)) {
            targetParent = this.closest(target, containerSel);
            if (targetParent && this.validTarget(targetParent).valid) {
                target = targetParent;
            }
        }
        return target;
    };
    /**
     * Check if the current pointer is neare to element borders
     * @return {Boolen}
     */
    Sorter.prototype.nearElBorders = function (el) {
        var off = 10;
        var rect = el.getBoundingClientRect();
        var body = el.ownerDocument.body;
        var _a = this.getCurrentPos(), x = _a.x, y = _a.y;
        var top = rect.top + body.scrollTop;
        var left = rect.left + body.scrollLeft;
        var width = rect.width;
        var height = rect.height;
        if (y < top + off || // near top edge
            y > top + height - off || // near bottom edge
            x < left + off || // near left edge
            x > left + width - off // near right edge
        ) {
            return 1;
        }
    };
    Sorter.prototype.getCurrentPos = function () {
        var ev = this.eventMove;
        var x = (ev === null || ev === void 0 ? void 0 : ev.pageX) || 0;
        var y = (ev === null || ev === void 0 ? void 0 : ev.pageY) || 0;
        return { x: x, y: y };
    };
    /**
     * Returns dimensions and positions about the element
     * @param {HTMLElement} el
     * @return {Array<number>}
     */
    Sorter.prototype.getDim = function (el) {
        var _a = this, em = _a.em, canvasRelative = _a.canvasRelative;
        var canvas = em === null || em === void 0 ? void 0 : em.Canvas;
        var offsets = canvas ? canvas.getElementOffsets(el) : {};
        var top, left, height, width;
        if (canvasRelative && em) {
            var pos = canvas.getElementPos(el, { noScroll: 1 });
            top = pos.top; // - offsets.marginTop;
            left = pos.left; // - offsets.marginLeft;
            height = pos.height; // + offsets.marginTop + offsets.marginBottom;
            width = pos.width; // + offsets.marginLeft + offsets.marginRight;
        }
        else {
            var o = this.offset(el);
            top = this.relative ? el.offsetTop : o.top - (this.wmargin ? -1 : 1) * this.elT;
            left = this.relative ? el.offsetLeft : o.left - (this.wmargin ? -1 : 1) * this.elL;
            height = el.offsetHeight;
            width = el.offsetWidth;
        }
        return { top: top, left: left, height: height, width: width, offsets: offsets };
    };
    /**
     * Get children dimensions
     * @param {HTMLELement} el Element root
     * @return {Array}
     * */
    Sorter.prototype.getChildrenDim = function (trg) {
        var _this = this;
        var dims = [];
        if (!trg)
            return dims;
        // Get children based on getChildrenContainer
        var trgModel = this.getTargetModel(trg);
        if (trgModel && trgModel.view && !this.ignoreViewChildren) {
            var view = trgModel.getCurrentView ? trgModel.getCurrentView() : trgModel.view;
            trg = view.getChildrenContainer();
        }
        (0,index_all.each)(trg.children, function (ele, i) {
            var el = ele;
            var model = (0,mixins.getModel)(el, cash_dom["default"]);
            var elIndex = model && model.index ? model.index() : i;
            if (!(0,dom/* isTextNode */.BM)(el) && !_this.matches(el, _this.itemSel)) {
                return;
            }
            var dim = _this.getDim(el);
            var dir = _this.direction;
            var dirValue;
            if (dir == 'v')
                dirValue = true;
            else if (dir == 'h')
                dirValue = false;
            else
                dirValue = _this.isInFlow(el, trg);
            dim.dir = dirValue;
            dim.el = el;
            dim.indexEl = elIndex;
            dims.push(dim);
        });
        return dims;
    };
    /**
     * Check if the coordinates are near to the borders
     * @param {Array<number>} dim
     * @param {number} rX Relative X position
     * @param {number} rY Relative Y position
     * @return {Boolean}
     * */
    Sorter.prototype.nearBorders = function (dim, rX, rY) {
        var result = false;
        var off = this.borderOffset;
        var x = rX || 0;
        var y = rY || 0;
        var t = dim.top;
        var l = dim.left;
        var h = dim.height;
        var w = dim.width;
        if (t + off > y || y > t + h - off || l + off > x || x > l + w - off)
            result = true;
        return result;
    };
    /**
     * Find the position based on passed dimensions and coordinates
     * @param {Array<Array>} dims Dimensions of nodes to parse
     * @param {number} posX X coordindate
     * @param {number} posY Y coordindate
     * @return {Object}
     * */
    Sorter.prototype.findPosition = function (dims, posX, posY) {
        var result = { index: 0, indexEl: 0, method: 'before' };
        var leftLimit = 0;
        var xLimit = 0;
        var dimRight = 0;
        var yLimit = 0;
        var xCenter = 0;
        var yCenter = 0;
        var dimDown = 0;
        var dim;
        // Each dim is: Top, Left, Height, Width
        for (var i = 0, len = dims.length; i < len; i++) {
            dim = dims[i];
            var top_1 = dim.top, left = dim.left, height = dim.height, width = dim.width;
            // Right position of the element. Left + Width
            dimRight = left + width;
            // Bottom position of the element. Top + Height
            dimDown = top_1 + height;
            // X center position of the element. Left + (Width / 2)
            xCenter = left + width / 2;
            // Y center position of the element. Top + (Height / 2)
            yCenter = top_1 + height / 2;
            // Skip if over the limits
            if ((xLimit && left > xLimit) ||
                (yLimit && yCenter >= yLimit) || // >= avoid issue with clearfixes
                (leftLimit && dimRight < leftLimit))
                continue;
            result.index = i;
            result.indexEl = dim.indexEl;
            // If it's not in flow (like 'float' element)
            if (!dim.dir) {
                if (posY < dimDown)
                    yLimit = dimDown;
                //If x lefter than center
                if (posX < xCenter) {
                    xLimit = xCenter;
                    result.method = 'before';
                }
                else {
                    leftLimit = xCenter;
                    result.method = 'after';
                }
            }
            else {
                // If y upper than center
                if (posY < yCenter) {
                    result.method = 'before';
                    break;
                }
                else
                    result.method = 'after'; // After last element
            }
        }
        return result;
    };
    /**
     * Updates the position of the placeholder
     * @param {HTMLElement} phl
     * @param {Array<Array>} dims
     * @param {Object} pos Position object
     * @param {Array<number>} trgDim target dimensions ([top, left, height, width])
     * */
    Sorter.prototype.movePlaceholder = function (plh, dims, pos, trgDim) {
        var marg = 0;
        var t = 0;
        var l = 0;
        var w = '';
        var h = '';
        var un = 'px';
        var margI = 5;
        var method = pos.method;
        var elDim = dims[pos.index];
        // Placeholder orientation
        plh.classList.remove('vertical');
        plh.classList.add('horizontal');
        if (elDim) {
            // If it's not in flow (like 'float' element)
            var top_2 = elDim.top, left = elDim.left, height = elDim.height, width = elDim.width;
            if (!elDim.dir) {
                w = 'auto';
                h = height - marg * 2 + un;
                t = top_2 + marg;
                l = method == 'before' ? left - marg : left + width - marg;
                plh.classList.remove('horizontal');
                plh.classList.add('vertical');
            }
            else {
                w = width + un;
                h = 'auto';
                t = method == 'before' ? top_2 - marg : top_2 + height - marg;
                l = left;
            }
        }
        else {
            // Placeholder inside the component
            if (!this.nested) {
                plh.style.display = 'none';
                return;
            }
            if (trgDim) {
                var offset = trgDim.offsets || {};
                var pT = offset.paddingTop || margI;
                var pL = offset.paddingLeft || margI;
                var bT = offset.borderTopWidth || 0;
                var bL = offset.borderLeftWidth || 0;
                var bR = offset.borderRightWidth || 0;
                var bWidth = bL + bR;
                t = trgDim.top + pT + bT;
                l = trgDim.left + pL + bL;
                w = parseInt("".concat(trgDim.width)) - pL * 2 - bWidth + un;
                h = 'auto';
            }
        }
        plh.style.top = t + un;
        plh.style.left = l + un;
        if (w)
            plh.style.width = w;
        if (h)
            plh.style.height = h;
    };
    /**
     * Build an array of all the parents, including the component itself
     * @return {Model|null}
     */
    Sorter.prototype.parents = function (model) {
        return model ? [model].concat(this.parents(model.parent())) : [];
    };
    /**
     * Sort according to the position in the dom
     * @param {Object} obj1 contains {model, parents}
     * @param {Object} obj2 contains {model, parents}
     */
    Sorter.prototype.sort = function (obj1, obj2) {
        // common ancesters
        var ancesters = obj1.parents.filter(function (p) { return obj2.parents.includes(p); });
        var ancester = ancesters[0];
        if (!ancester) {
            // this is never supposed to happen
            return obj2.model.index() - obj1.model.index();
        }
        // find siblings in the common ancester
        // the sibling is the element inside the ancester
        var s1 = obj1.parents[obj1.parents.indexOf(ancester) - 1];
        var s2 = obj2.parents[obj2.parents.indexOf(ancester) - 1];
        // order according to the position in the DOM
        return s2.index() - s1.index();
    };
    /**
     * Leave item
     * @param event
     *
     * @return void
     * */
    Sorter.prototype.endMove = function () {
        var _this = this;
        var _a;
        var src = this.sourceEl;
        var moved = [];
        var docs = this.getDocuments();
        var container = this.getContainerEl();
        var onEndMove = this.onEndMove;
        var onEnd = this.onEnd;
        var _b = this, target = _b.target, lastPos = _b.lastPos;
        var srcModel;
        (0,dom/* off */.S1)(container, 'mousemove dragover', this.onMove);
        (0,dom/* off */.S1)(docs, 'mouseup dragend touchend', this.endMove);
        (0,dom/* off */.S1)(docs, 'keydown', this.rollback);
        this.plh.style.display = 'none';
        if (src) {
            srcModel = this.getSourceModel();
        }
        if (this.moved && target) {
            var toMove = this.toMove;
            var toMoveArr = (0,index_all.isArray)(toMove) ? toMove : toMove ? [toMove] : [src];
            var domPositionOffset_1 = 0;
            if (toMoveArr.length === 1) {
                // do not sort the array in this case
                // there are cases for the sorter where toMoveArr is [undefined]
                // which allows the drop from blocks, native D&D and sort of layers in Style Manager
                moved.push(this.move(target, toMoveArr[0], lastPos));
            }
            else {
                toMoveArr
                    // add the model's parents
                    .map(function (model) { return ({
                    model: model,
                    parents: _this.parents(model),
                }); })
                    // sort based on elements positions in the dom
                    .sort(this.sort)
                    // move each component to the new parent and position
                    .forEach(function (_a) {
                    var model = _a.model;
                    // @ts-ignore store state before move
                    var index = model.index();
                    // @ts-ignore
                    var parent = model.parent().getEl();
                    // move the component to the desired position
                    moved.push(_this.move(target, model, Sorter_assign(Sorter_assign({}, lastPos), { indexEl: lastPos.indexEl - domPositionOffset_1, index: lastPos.index - domPositionOffset_1 })));
                    // when the element is dragged to the same parent and after its position
                    //  it will be removed from the children list
                    //  in that case we need to adjust the following elements target position
                    if (parent === target && index <= lastPos.index) {
                        // the next elements will be inserted 1 element before this one
                        domPositionOffset_1++;
                    }
                });
            }
        }
        if (this.plh)
            this.plh.style.display = 'none';
        var dragHelper = this.dragHelper;
        if (dragHelper) {
            dragHelper.parentNode.removeChild(dragHelper);
            delete this.dragHelper;
        }
        this.disableTextable();
        this.selectTargetModel();
        this.toggleSortCursor();
        (_a = this.em) === null || _a === void 0 ? void 0 : _a.Canvas.removeSpots(spotTarget);
        delete this.toMove;
        delete this.eventMove;
        delete this.dropModel;
        if ((0,index_all.isFunction)(onEndMove)) {
            var data_1 = {
                target: srcModel,
                // @ts-ignore
                parent: srcModel && srcModel.parent(),
                // @ts-ignore
                index: srcModel && srcModel.index(),
            };
            moved.length ? moved.forEach(function (m) { return onEndMove(m, _this, data_1); }) : onEndMove(null, this, Sorter_assign(Sorter_assign({}, data_1), { cancelled: 1 }));
        }
        (0,index_all.isFunction)(onEnd) && onEnd({ sorter: this });
    };
    /**
     * Move component to new position
     * @param {HTMLElement} dst Destination target
     * @param {HTMLElement} src Element to move
     * @param {Object} pos Object with position coordinates
     * */
    Sorter.prototype.move = function (dst, src, pos) {
        var _a = this, em = _a.em, dropContent = _a.dropContent;
        var srcEl = (0,mixins.getElement)(src);
        var warns = [];
        var index = pos.method === 'after' ? pos.indexEl + 1 : pos.indexEl;
        var validResult = this.validTarget(dst, srcEl);
        var targetCollection = (0,cash_dom["default"])(dst).data('collection');
        var trgModel = validResult.trgModel, srcModel = validResult.srcModel, draggable = validResult.draggable;
        var droppable = trgModel instanceof common/* Collection */.FE ? 1 : validResult.droppable;
        var modelToDrop, created;
        if (targetCollection && droppable && draggable) {
            var opts = { at: index, action: 'move-component' };
            var isTextable = this.isTextableActive(srcModel, trgModel);
            if (!dropContent) {
                var srcIndex = srcModel.collection.indexOf(srcModel);
                var sameCollection = targetCollection === srcModel.collection;
                var sameIndex = srcIndex === index || srcIndex === index - 1;
                var canRemove = !sameCollection || !sameIndex || isTextable;
                if (canRemove) {
                    modelToDrop = srcModel.collection.remove(srcModel, {
                        temporary: true,
                    });
                    if (sameCollection && index > srcIndex) {
                        opts.at = index - 1;
                    }
                }
            }
            else {
                // @ts-ignore
                modelToDrop = (0,index_all.isFunction)(dropContent) ? dropContent() : dropContent;
                opts.avoidUpdateStyle = true;
                opts.action = 'add-component';
            }
            if (modelToDrop) {
                if (isTextable) {
                    delete opts.at;
                    created = trgModel.getView().insertComponent(modelToDrop, opts);
                }
                else {
                    created = targetCollection.add(modelToDrop, opts);
                }
            }
            delete this.dropContent;
            delete this.prevTarget; // This will recalculate children dimensions
        }
        else if (em) {
            var dropInfo = validResult.dropInfo || (trgModel === null || trgModel === void 0 ? void 0 : trgModel.get('droppable'));
            var dragInfo = validResult.dragInfo || (srcModel === null || srcModel === void 0 ? void 0 : srcModel.get('draggable'));
            !targetCollection && warns.push('Target collection not found');
            !droppable && dropInfo && warns.push("Target is not droppable, accepts [".concat(dropInfo, "]"));
            !draggable && dragInfo && warns.push("Component not draggable, acceptable by [".concat(dragInfo, "]"));
            em.logWarning('Invalid target position', {
                errors: warns,
                model: srcModel,
                context: 'sorter',
                target: trgModel,
            });
        }
        em === null || em === void 0 ? void 0 : em.trigger('sorter:drag:end', {
            targetCollection: targetCollection,
            modelToDrop: modelToDrop,
            warns: warns,
            validResult: validResult,
            dst: dst,
            srcEl: srcEl,
        });
        return created;
    };
    /**
     * Rollback to previous situation
     * @param {Event}
     * @param {Bool} Indicates if rollback in anycase
     * */
    Sorter.prototype.rollback = function (e) {
        (0,dom/* off */.S1)(this.getDocuments(), 'keydown', this.rollback);
        var key = e.which || e.keyCode;
        if (key == 27) {
            this.moved = false;
            this.endMove();
        }
    };
    return Sorter;
}(common/* View */.G7));
/* harmony default export */ const utils_Sorter = (Sorter);

;// CONCATENATED MODULE: ./src/utils/Resizer.ts
var Resizer_assign = (undefined && undefined.__assign) || function () {
    Resizer_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return Resizer_assign.apply(this, arguments);
};



var createHandler = function (name, opts) {
    if (opts === void 0) { opts = {}; }
    var pfx = opts.prefix || '';
    var el = document.createElement('i');
    el.className = pfx + 'resizer-h ' + pfx + 'resizer-h-' + name;
    el.setAttribute('data-' + pfx + 'handler', name);
    return el;
};
var getBoundingRect = function (el, win) {
    var w = win || window;
    var rect = el.getBoundingClientRect();
    return {
        left: rect.left + w.pageXOffset,
        top: rect.top + w.pageYOffset,
        width: rect.width,
        height: rect.height,
    };
};
var Resizer = /** @class */ (function () {
    /**
     * Init the Resizer with options
     * @param  {Object} options
     */
    function Resizer(opts) {
        if (opts === void 0) { opts = {}; }
        this.defOpts = {
            ratioDefault: false,
            onUpdateContainer: function () { },
            step: 1,
            minDim: 10,
            maxDim: Infinity,
            unitHeight: 'px',
            unitWidth: 'px',
            keyHeight: 'height',
            keyWidth: 'width',
            currentUnit: true,
            silentFrames: false,
            avoidContainerUpdate: false,
            keepAutoHeight: false,
            keepAutoWidth: false,
            autoHeight: false,
            autoWidth: false,
            tl: true,
            tc: true,
            tr: true,
            cl: true,
            cr: true,
            bl: true,
            bc: true,
            br: true,
        };
        this.opts = Resizer_assign({}, this.defOpts);
        this.setOptions(opts);
        (0,index_all.bindAll)(this, 'handleKeyDown', 'handleMouseDown', 'move', 'stop');
    }
    /**
     * Get current connfiguration options
     * @return {Object}
     */
    Resizer.prototype.getConfig = function () {
        return this.opts;
    };
    /**
     * Setup options
     * @param {Object} options
     */
    Resizer.prototype.setOptions = function (options, reset) {
        if (options === void 0) { options = {}; }
        this.opts = Resizer_assign(Resizer_assign({}, (reset ? this.defOpts : this.opts)), options);
        this.setup();
    };
    /**
     * Setup resizer
     */
    Resizer.prototype.setup = function () {
        var opts = this.opts;
        var pfx = opts.prefix || '';
        var appendTo = opts.appendTo || document.body;
        var container = this.container;
        // Create container if not yet exist
        if (!container) {
            container = document.createElement('div');
            container.className = "".concat(pfx, "resizer-c");
            appendTo.appendChild(container);
            this.container = container;
        }
        while (container.firstChild) {
            container.removeChild(container.firstChild);
        }
        // Create handlers
        var handlers = {};
        ['tl', 'tc', 'tr', 'cl', 'cr', 'bl', 'bc', 'br'].forEach(
        // @ts-ignore
        function (hdl) { return (handlers[hdl] = opts[hdl] ? createHandler(hdl, opts) : null); });
        for (var n in handlers) {
            var handler = handlers[n];
            handler && container.appendChild(handler);
        }
        this.handlers = handlers;
        this.mousePosFetcher = opts.mousePosFetcher;
        this.updateTarget = opts.updateTarget;
        this.posFetcher = opts.posFetcher;
        this.onStart = opts.onStart;
        this.onMove = opts.onMove;
        this.onEnd = opts.onEnd;
        this.onUpdateContainer = opts.onUpdateContainer;
    };
    /**
     * Toggle iframes pointer event
     * @param {Boolean} silent If true, iframes will be silented
     */
    Resizer.prototype.toggleFrames = function (silent) {
        if (this.opts.silentFrames) {
            var frames_1 = document.querySelectorAll('iframe');
            (0,index_all.each)(frames_1, function (frame) { return (frame.style.pointerEvents = silent ? 'none' : ''); });
        }
    };
    /**
     * Detects if the passed element is a resize handler
     * @param  {HTMLElement} el
     * @return {Boolean}
     */
    Resizer.prototype.isHandler = function (el) {
        var handlers = this.handlers;
        for (var n in handlers) {
            if (handlers[n] === el)
                return true;
        }
        return false;
    };
    /**
     * Returns the focused element
     * @return {HTMLElement}
     */
    Resizer.prototype.getFocusedEl = function () {
        return this.el;
    };
    /**
     * Returns the parent of the focused element
     * @return {HTMLElement}
     */
    Resizer.prototype.getParentEl = function () {
        var _a;
        return (_a = this.el) === null || _a === void 0 ? void 0 : _a.parentElement;
    };
    /**
     * Returns documents
     */
    Resizer.prototype.getDocumentEl = function () {
        return [this.el.ownerDocument, document];
    };
    /**
     * Return element position
     * @param  {HTMLElement} el
     * @param  {Object} opts Custom options
     * @return {Object}
     */
    Resizer.prototype.getElementPos = function (el, opts) {
        if (opts === void 0) { opts = {}; }
        var posFetcher = this.posFetcher;
        return posFetcher ? posFetcher(el, opts) : getBoundingRect(el);
    };
    /**
     * Focus resizer on the element, attaches handlers to it
     * @param {HTMLElement} el
     */
    Resizer.prototype.focus = function (el) {
        // Avoid focusing on already focused element
        if (el && el === this.el) {
            return;
        }
        this.el = el;
        this.updateContainer({ forceShow: true });
        (0,dom.on)(this.getDocumentEl(), 'pointerdown', this.handleMouseDown);
    };
    /**
     * Blur from element
     */
    Resizer.prototype.blur = function () {
        this.container.style.display = 'none';
        if (this.el) {
            (0,dom/* off */.S1)(this.getDocumentEl(), 'pointerdown', this.handleMouseDown);
            delete this.el;
        }
    };
    /**
     * Start resizing
     * @param  {Event} e
     */
    Resizer.prototype.start = function (ev) {
        var e = ev;
        // @ts-ignore Right or middel click
        if (e.button !== 0)
            return;
        e.preventDefault();
        e.stopPropagation();
        var el = this.el;
        var parentEl = this.getParentEl();
        var resizer = this;
        var config = this.opts || {};
        var mouseFetch = this.mousePosFetcher;
        var attrName = 'data-' + config.prefix + 'handler';
        var rect = this.getElementPos(el, { avoidFrameZoom: true, avoidFrameOffset: true });
        var parentRect = this.getElementPos(parentEl);
        var target = e.target;
        this.handlerAttr = target.getAttribute(attrName);
        this.clickedHandler = target;
        this.startDim = {
            t: rect.top,
            l: rect.left,
            w: rect.width,
            h: rect.height,
        };
        this.rectDim = {
            t: rect.top,
            l: rect.left,
            w: rect.width,
            h: rect.height,
        };
        this.startPos = mouseFetch
            ? mouseFetch(e)
            : {
                x: e.clientX,
                y: e.clientY,
            };
        this.parentDim = {
            t: parentRect.top,
            l: parentRect.left,
            w: parentRect.width,
            h: parentRect.height,
        };
        // Listen events
        var docs = this.getDocumentEl();
        this.docs = docs;
        (0,dom.on)(docs, 'pointermove', this.move);
        (0,dom.on)(docs, 'keydown', this.handleKeyDown);
        (0,dom.on)(docs, 'pointerup', this.stop);
        (0,index_all.isFunction)(this.onStart) && this.onStart(e, { docs: docs, config: config, el: el, resizer: resizer });
        this.toggleFrames(true);
        this.move(e);
    };
    /**
     * While resizing
     * @param  {Event} e
     */
    Resizer.prototype.move = function (ev) {
        var e = ev;
        var onMove = this.onMove;
        var mouseFetch = this.mousePosFetcher;
        var currentPos = mouseFetch
            ? mouseFetch(e)
            : {
                x: e.clientX,
                y: e.clientY,
            };
        this.currentPos = currentPos;
        this.delta = {
            x: currentPos.x - this.startPos.x,
            y: currentPos.y - this.startPos.y,
        };
        this.keys = {
            shift: e.shiftKey,
            ctrl: e.ctrlKey,
            alt: e.altKey,
        };
        this.rectDim = this.calc(this);
        this.updateRect(false);
        // Move callback
        onMove && onMove(e);
    };
    /**
     * Stop resizing
     * @param  {Event} e
     */
    Resizer.prototype.stop = function (e) {
        var el = this.el;
        var config = this.opts;
        var docs = this.docs || this.getDocumentEl();
        (0,dom/* off */.S1)(docs, 'pointermove', this.move);
        (0,dom/* off */.S1)(docs, 'keydown', this.handleKeyDown);
        (0,dom/* off */.S1)(docs, 'pointerup', this.stop);
        this.updateRect(true);
        this.toggleFrames();
        (0,index_all.isFunction)(this.onEnd) && this.onEnd(e, { docs: docs, config: config, el: el, resizer: this });
        delete this.docs;
    };
    /**
     * Update rect
     */
    Resizer.prototype.updateRect = function (store) {
        var el = this.el;
        var resizer = this;
        var config = this.opts;
        var rect = this.rectDim;
        var updateTarget = this.updateTarget;
        var selectedHandler = this.getSelectedHandler();
        var unitHeight = config.unitHeight, unitWidth = config.unitWidth, keyWidth = config.keyWidth, keyHeight = config.keyHeight;
        // Use custom updating strategy if requested
        if ((0,index_all.isFunction)(updateTarget)) {
            updateTarget(el, rect, {
                store: store,
                selectedHandler: selectedHandler,
                resizer: resizer,
                config: config,
            });
        }
        else {
            var elStyle = el.style;
            elStyle[keyWidth] = rect.w + unitWidth;
            elStyle[keyHeight] = rect.h + unitHeight;
        }
        this.updateContainer();
    };
    Resizer.prototype.updateContainer = function (opt) {
        var _a;
        if (opt === void 0) { opt = {}; }
        var _b = this, opts = _b.opts, container = _b.container, el = _b.el;
        var style = container.style;
        if (!opts.avoidContainerUpdate && el) {
            // On component resize container fits the tool,
            // to check if this update is required somewhere else point
            // const toUpdate = ['left', 'top', 'width', 'height'];
            // const rectEl = this.getElementPos(el, { target: 'container' });
            // toUpdate.forEach(pos => (style[pos] = `${rectEl[pos]}px`));
            if (opt.forceShow)
                style.display = 'block';
        }
        (_a = this.onUpdateContainer) === null || _a === void 0 ? void 0 : _a.call(this, {
            el: container,
            resizer: this,
            opts: Resizer_assign(Resizer_assign({}, opts), opt),
        });
    };
    /**
     * Get selected handler name
     * @return {string}
     */
    Resizer.prototype.getSelectedHandler = function () {
        var handlers = this.handlers;
        if (!this.selectedHandler) {
            return;
        }
        for (var n in handlers) {
            if (handlers[n] === this.selectedHandler)
                return n;
        }
    };
    /**
     * Handle ESC key
     * @param  {Event} e
     */
    Resizer.prototype.handleKeyDown = function (e) {
        // @ts-ignore
        if (e.keyCode === 27) {
            // Rollback to initial dimensions
            this.rectDim = this.startDim;
            this.stop(e);
        }
    };
    /**
     * Handle mousedown to check if it's possible to start resizing
     * @param  {Event} e
     */
    Resizer.prototype.handleMouseDown = function (e) {
        var el = e.target;
        if (this.isHandler(el)) {
            this.selectedHandler = el;
            this.start(e);
        }
        else if (el !== this.el) {
            delete this.selectedHandler;
            this.blur();
        }
    };
    /**
     * All positioning logic
     * @return {Object}
     */
    Resizer.prototype.calc = function (data) {
        var value;
        var opts = this.opts || {};
        var step = opts.step;
        var startDim = this.startDim;
        var minDim = opts.minDim;
        var maxDim = opts.maxDim;
        var deltaX = data.delta.x;
        var deltaY = data.delta.y;
        var parentW = this.parentDim.w;
        var parentH = this.parentDim.h;
        var unitWidth = this.opts.unitWidth;
        var unitHeight = this.opts.unitHeight;
        var startW = unitWidth === '%' ? (startDim.w / 100) * parentW : startDim.w;
        var startH = unitHeight === '%' ? (startDim.h / 100) * parentH : startDim.h;
        var box = {
            t: startDim.t,
            l: startDim.l,
            w: startW,
            h: startH,
        };
        if (!data)
            return;
        var attr = data.handlerAttr;
        if (~attr.indexOf('r')) {
            value =
                unitWidth === '%'
                    ? (0,mixins.normalizeFloat)(((startW + deltaX * step) / parentW) * 100, 0.01)
                    : (0,mixins.normalizeFloat)(startW + deltaX * step, step);
            value = Math.max(minDim, value);
            maxDim && (value = Math.min(maxDim, value));
            box.w = value;
        }
        if (~attr.indexOf('b')) {
            value =
                unitHeight === '%'
                    ? (0,mixins.normalizeFloat)(((startH + deltaY * step) / parentH) * 100, 0.01)
                    : (0,mixins.normalizeFloat)(startH + deltaY * step, step);
            value = Math.max(minDim, value);
            maxDim && (value = Math.min(maxDim, value));
            box.h = value;
        }
        if (~attr.indexOf('l')) {
            value =
                unitWidth === '%'
                    ? (0,mixins.normalizeFloat)(((startW - deltaX * step) / parentW) * 100, 0.01)
                    : (0,mixins.normalizeFloat)(startW - deltaX * step, step);
            value = Math.max(minDim, value);
            maxDim && (value = Math.min(maxDim, value));
            box.w = value;
        }
        if (~attr.indexOf('t')) {
            value =
                unitHeight === '%'
                    ? (0,mixins.normalizeFloat)(((startH - deltaY * step) / parentH) * 100, 0.01)
                    : (0,mixins.normalizeFloat)(startH - deltaY * step, step);
            value = Math.max(minDim, value);
            maxDim && (value = Math.min(maxDim, value));
            box.h = value;
        }
        // Enforce aspect ratio (unless shift key is being held)
        var ratioActive = opts.ratioDefault ? !data.keys.shift : data.keys.shift;
        if (attr.indexOf('c') < 0 && ratioActive) {
            var ratio = startDim.w / startDim.h;
            if (box.w / box.h > ratio) {
                box.h = Math.round(box.w / ratio);
            }
            else {
                box.w = Math.round(box.h * ratio);
            }
        }
        if (~attr.indexOf('l')) {
            box.l += startDim.w - box.w;
        }
        if (~attr.indexOf('t')) {
            box.t += startDim.h - box.h;
        }
        for (var key in box) {
            var i = key;
            box[i] = parseInt("".concat(box[i]), 10);
        }
        return box;
    };
    return Resizer;
}());
/* harmony default export */ const utils_Resizer = (Resizer);

;// CONCATENATED MODULE: ./src/utils/index.ts
var utils_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var utils_assign = (undefined && undefined.__assign) || function () {
    utils_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return utils_assign.apply(this, arguments);
};





var UtilsModule = /** @class */ (function (_super) {
    utils_extends(UtilsModule, _super);
    function UtilsModule(em) {
        var _this = _super.call(this, em, 'Utils') || this;
        _this.Sorter = utils_Sorter;
        _this.Resizer = utils_Resizer;
        _this.Dragger = Dragger/* default */.Z;
        _this.helpers = utils_assign({}, mixins);
        return _this;
    }
    UtilsModule.prototype.destroy = function () { };
    return UtilsModule;
}(abstract_Module));
/* harmony default export */ const utils = (UtilsModule);

;// CONCATENATED MODULE: ./src/utils/keymaster.ts
// @ts-nocheck
// The initial version of this library was borrowed from https://github.com/madrobby/keymaster
// and adapted to the GrapesJS's need
var k, _handlers = {}, _mods = {
    16: false,
    18: false,
    17: false,
    91: false,
}, _scope = 'all', 
// modifier keys
_MODIFIERS = {
    '⇧': 16,
    shift: 16,
    '⌥': 18,
    alt: 18,
    option: 18,
    '⌃': 17,
    ctrl: 17,
    control: 17,
    '⌘': 91,
    command: 91,
}, 
// special keys
_MAP = {
    backspace: 8,
    tab: 9,
    clear: 12,
    enter: 13,
    return: 13,
    esc: 27,
    escape: 27,
    space: 32,
    left: 37,
    up: 38,
    right: 39,
    down: 40,
    del: 46,
    delete: 46,
    home: 36,
    end: 35,
    pageup: 33,
    pagedown: 34,
    ',': 188,
    '.': 190,
    '/': 191,
    '`': 192,
    '-': 189,
    '=': 187,
    ';': 186,
    "'": 222,
    '[': 219,
    ']': 221,
    '\\': 220,
}, code = function (x) {
    return _MAP[x] || x.toUpperCase().charCodeAt(0);
}, _downKeys = [];
for (k = 1; k < 20; k++)
    _MAP['f' + k] = 111 + k;
// IE doesn't support Array#indexOf, so have a simple replacement
function index(array, item) {
    var i = array.length;
    while (i--)
        if (array[i] === item)
            return i;
    return -1;
}
// for comparing mods before unassignment
function compareArray(a1, a2) {
    if (a1.length != a2.length)
        return false;
    for (var i = 0; i < a1.length; i++) {
        if (a1[i] !== a2[i])
            return false;
    }
    return true;
}
var modifierMap = {
    16: 'shiftKey',
    18: 'altKey',
    17: 'ctrlKey',
    91: 'metaKey',
};
function updateModifierKey(event) {
    for (k in _mods)
        _mods[k] = event[modifierMap[k]];
}
// handle keydown event
function dispatch(event) {
    var key, handler, k, i, modifiersMatch, scope;
    key = event.keyCode;
    if (index(_downKeys, key) == -1) {
        _downKeys.push(key);
    }
    // if a modifier key, set the key.<modifierkeyname> property to true and return
    if (key == 93 || key == 224)
        key = 91; // right command on webkit, command on Gecko
    if (key in _mods) {
        _mods[key] = true;
        // 'assignKey' from inside this closure is exported to window.key
        for (k in _MODIFIERS)
            if (_MODIFIERS[k] == key)
                assignKey[k] = true;
        return;
    }
    updateModifierKey(event);
    // see if we need to ignore the keypress (filter() can can be overridden)
    // by default ignore key presses if a select, textarea, or input is focused
    if (!assignKey.filter.call(this, event))
        return;
    // abort if no potentially matching shortcuts found
    if (!(key in _handlers))
        return;
    scope = getScope();
    // for each potential shortcut
    for (i = 0; i < _handlers[key].length; i++) {
        handler = _handlers[key][i];
        // see if it's in the current scope
        if (handler.scope == scope || handler.scope == 'all') {
            // check if modifiers match if any
            modifiersMatch = handler.mods.length > 0;
            for (k in _mods)
                if ((!_mods[k] && index(handler.mods, +k) > -1) || (_mods[k] && index(handler.mods, +k) == -1))
                    modifiersMatch = false;
            // call the handler and stop the event if neccessary
            if ((handler.mods.length == 0 && !_mods[16] && !_mods[18] && !_mods[17] && !_mods[91]) || modifiersMatch) {
                if (handler.method(event, handler) === false) {
                    if (event.preventDefault)
                        event.preventDefault();
                    else
                        event.returnValue = false;
                    if (event.stopPropagation)
                        event.stopPropagation();
                    if (event.cancelBubble)
                        event.cancelBubble = true;
                }
            }
        }
    }
}
// unset modifier keys on keyup
function clearModifier(event) {
    var key = event.keyCode, k, i = index(_downKeys, key);
    // remove key from _downKeys
    if (i >= 0) {
        _downKeys.splice(i, 1);
    }
    if (key == 93 || key == 224)
        key = 91;
    if (key in _mods) {
        _mods[key] = false;
        for (k in _MODIFIERS)
            if (_MODIFIERS[k] == key)
                assignKey[k] = false;
    }
}
function resetModifiers() {
    for (k in _mods)
        _mods[k] = false;
    for (k in _MODIFIERS)
        assignKey[k] = false;
}
// parse and assign shortcut
function assignKey(key, scope, method) {
    var keys, mods;
    keys = getKeys(key);
    if (method === undefined) {
        method = scope;
        scope = 'all';
    }
    // for each shortcut
    for (var i = 0; i < keys.length; i++) {
        // set modifier keys if any
        mods = [];
        key = keys[i].split('+');
        if (key.length > 1) {
            mods = getMods(key);
            key = [key[key.length - 1]];
        }
        // convert to keycode and...
        key = key[0];
        key = code(key);
        // ...store handler
        if (!(key in _handlers))
            _handlers[key] = [];
        _handlers[key].push({
            shortcut: keys[i],
            scope: scope,
            method: method,
            key: keys[i],
            mods: mods,
        });
    }
}
// unbind all handlers for given key in current scope
function unbindKey(key, scope) {
    var multipleKeys, keys, mods = [], i, j, obj;
    multipleKeys = getKeys(key);
    for (j = 0; j < multipleKeys.length; j++) {
        keys = multipleKeys[j].split('+');
        if (keys.length > 1) {
            mods = getMods(keys);
        }
        key = keys[keys.length - 1];
        key = code(key);
        if (scope === undefined) {
            scope = getScope();
        }
        if (!_handlers[key]) {
            return;
        }
        for (i = 0; i < _handlers[key].length; i++) {
            obj = _handlers[key][i];
            // only clear handlers if correct scope and mods match
            if (obj.scope === scope && compareArray(obj.mods, mods)) {
                _handlers[key][i] = {};
            }
        }
    }
}
// Returns true if the key with code 'keyCode' is currently down
// Converts strings into key codes.
function isPressed(keyCode) {
    if (typeof keyCode == 'string') {
        keyCode = code(keyCode);
    }
    return index(_downKeys, keyCode) != -1;
}
function getPressedKeyCodes() {
    return _downKeys.slice(0);
}
function filter(event) {
    var tagName = (event.target || event.srcElement).tagName;
    // ignore keypressed in any elements that support keyboard data input
    return !(tagName == 'INPUT' || tagName == 'SELECT' || tagName == 'TEXTAREA');
}
// initialize key.<modifier> to false
for (k in _MODIFIERS)
    assignKey[k] = false;
// set current scope (default 'all')
function setScope(scope) {
    _scope = scope || 'all';
}
function getScope() {
    return _scope || 'all';
}
// delete all handlers for a given scope
function deleteScope(scope) {
    var key, handlers, i;
    for (key in _handlers) {
        handlers = _handlers[key];
        for (i = 0; i < handlers.length;) {
            if (handlers[i].scope === scope)
                handlers.splice(i, 1);
            else
                i++;
        }
    }
}
// abstract key logic for assign and unassign
function getKeys(key) {
    var keys;
    key = key.replace(/\s/g, '');
    keys = key.split(',');
    if (keys[keys.length - 1] == '') {
        keys[keys.length - 2] += ',';
    }
    return keys;
}
// abstract mods logic for assign and unassign
function getMods(key) {
    var mods = key.slice(0, key.length - 1);
    for (var mi = 0; mi < mods.length; mi++)
        mods[mi] = _MODIFIERS[mods[mi]];
    return mods;
}
// cross-browser events
function addEvent(object, event, method) {
    if (object.addEventListener)
        object.addEventListener(event, method, false);
    else if (object.attachEvent)
        object.attachEvent('on' + event, function () {
            method(window.event);
        });
}
// set window.key and window.key.set/get/deleteScope, and the default filter
assignKey.setScope = setScope;
assignKey.getScope = getScope;
assignKey.deleteScope = deleteScope;
assignKey.filter = filter;
assignKey.isPressed = isPressed;
assignKey.getPressedKeyCodes = getPressedKeyCodes;
assignKey.unbind = unbindKey;
assignKey.handlers = _handlers;
assignKey.init = function (win) {
    // set the handlers globally on document
    // Passing _scope to a callback to ensure it remains the same by execution. Fixes #48
    addEvent(win.document, 'keydown', function (event) {
        dispatch(event);
    });
    addEvent(win.document, 'keyup', clearModifier);
    addEvent(win, 'focus', resetModifiers);
};
/* harmony default export */ const keymaster = (assignKey);

;// CONCATENATED MODULE: ./src/keymaps/config.ts
var keymaps_config_config = {
    defaults: {
        'core:undo': {
            keys: '⌘+z, ctrl+z',
            handler: 'core:undo',
            opts: { prevent: true },
        },
        'core:redo': {
            keys: '⌘+shift+z, ctrl+shift+z',
            handler: 'core:redo',
            opts: { prevent: true },
        },
        'core:copy': {
            keys: '⌘+c, ctrl+c',
            handler: 'core:copy',
        },
        'core:paste': {
            keys: '⌘+v, ctrl+v',
            handler: 'core:paste',
        },
        'core:component-next': {
            keys: 's',
            handler: 'core:component-next',
        },
        'core:component-prev': {
            keys: 'w',
            handler: 'core:component-prev',
        },
        'core:component-enter': {
            keys: 'd',
            handler: 'core:component-enter',
        },
        'core:component-exit': {
            keys: 'a',
            handler: 'core:component-exit',
        },
        'core:component-delete': {
            keys: 'backspace, delete',
            handler: 'core:component-delete',
            opts: { prevent: true },
        },
    },
};
/* harmony default export */ const keymaps_config = (keymaps_config_config);

;// CONCATENATED MODULE: ./src/keymaps/index.ts
/**
 * You can customize the initial state of the module from the editor initialization
 * ```js
 * const editor = grapesjs.init({
 *  keymaps: {
 *     // Object of keymaps
 *    defaults: {
 *      'your-namespace:keymap-name' {
 *        keys: '⌘+z, ctrl+z',
 *        handler: 'some-command-id'
 *      },
 *      ...
 *    }
 *  }
 * })
 * ```
 *
 * Once the editor is instantiated you can use its API and listen to its events. Before using these methods, you should get the module from the instance.
 *
 * ```js
 * // Listen to events
 * editor.on('keymap:add', () => { ... });
 *
 * // Use the API
 * const keymaps = editor.Keymaps;
 * keymaps.add(...);
 * ```
 *
 * ## Available Events
 * * `keymap:add` - New keymap added. The new keyamp object is passed as an argument
 * * `keymap:remove` - Keymap removed. The removed keyamp object is passed as an argument
 * * `keymap:emit` - Some keymap emitted, in arguments you get keymapId, shortcutUsed, Event
 * * `keymap:emit:{keymapId}` - `keymapId` emitted, in arguments you get keymapId, shortcutUsed, Event
 *
 * ## Methods
 * * [getConfig](#getconfig)
 * * [add](#add)
 * * [get](#get)
 * * [getAll](#getAll)
 * * [remove](#remove)
 * * [removeAll](#removeall)
 *
 * @module Keymaps
 */
var keymaps_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var keymaps_spreadArray = (undefined && undefined.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};





(0,mixins.hasWin)() && keymaster.init(window);
var KeymapsModule = /** @class */ (function (_super) {
    keymaps_extends(KeymapsModule, _super);
    function KeymapsModule(em) {
        var _this = _super.call(this, em, 'Keymaps', keymaps_config) || this;
        _this.keymaster = keymaster;
        _this.keymaps = {};
        return _this;
    }
    KeymapsModule.prototype.onLoad = function () {
        var defKeys = this.config.defaults;
        for (var id in defKeys) {
            var value = defKeys[id];
            this.add(id, value.keys, value.handler, value.opts || {});
        }
    };
    /**
     * Get configuration object
     * @name getConfig
     * @function
     * @return {Object}
     */
    /**
     * Add new keymap
     * @param {string} id Keymap id
     * @param {string} keys Keymap keys, eg. `ctrl+a`, `⌘+z, ctrl+z`
     * @param {Function|string} handler Keymap handler, might be a function
     * @param {Object} [opts={}] Options
     * @param {Boolean} [opts.force=false] Force the handler to be executed.
     * @param {Boolean} [opts.prevent=false] Prevent default of the original triggered event.
     * @returns {Object} Added keymap
     * @example
     * // 'ns' is just a custom namespace
     * keymaps.add('ns:my-keymap', '⌘+j, ⌘+u, ctrl+j, alt+u', editor => {
     *  console.log('do stuff');
     * });
     * // or
     * keymaps.add('ns:my-keymap', '⌘+s, ctrl+s', 'some-gjs-command', {
     *  // Prevent the default browser action
     *  prevent: true,
     * });
     *
     * // listen to events
     * editor.on('keymap:emit', (id, shortcut, event) => {
     *  // ...
     * })
     */
    KeymapsModule.prototype.add = function (id, keys, handler, opts) {
        if (opts === void 0) { opts = {}; }
        var em = this.em;
        var cmd = em.Commands;
        var editor = em.getEditor();
        var canvas = em.Canvas;
        var keymap = { id: id, keys: keys, handler: handler };
        var pk = this.keymaps[id];
        pk && this.remove(id);
        this.keymaps[id] = keymap;
        keymaster(keys, function (e, h) {
            // It's safer putting handlers resolution inside the callback
            var opt = { event: e, h: h };
            var handlerRes = (0,index_all.isString)(handler) ? cmd.get(handler) : handler;
            var ableTorun = !em.isEditing() && !editor.Canvas.isInputFocused();
            if (ableTorun || opts.force) {
                opts.prevent && canvas.getCanvasView().preventDefault(e);
                (0,index_all.isFunction)(handlerRes) ? handlerRes(editor, 0, opt) : cmd.runCommand(handlerRes, opt);
                var args = [id, h.shortcut, e];
                em.trigger.apply(em, keymaps_spreadArray(['keymap:emit'], args, false));
                em.trigger.apply(em, keymaps_spreadArray(["keymap:emit:".concat(id)], args, false));
            }
        }, undefined);
        em.trigger('keymap:add', keymap);
        return keymap;
    };
    /**
     * Get the keymap by id
     * @param {string} id Keymap id
     * @return {Object} Keymap object
     * @example
     * keymaps.get('ns:my-keymap');
     * // -> {keys, handler};
     */
    KeymapsModule.prototype.get = function (id) {
        return this.keymaps[id];
    };
    /**
     * Get all keymaps
     * @return {Object}
     * @example
     * keymaps.getAll();
     * // -> {id1: {}, id2: {}};
     */
    KeymapsModule.prototype.getAll = function () {
        return this.keymaps;
    };
    /**
     * Remove the keymap by id
     * @param {string} id Keymap id
     * @return {Object} Removed keymap
     * @example
     * keymaps.remove('ns:my-keymap');
     * // -> {keys, handler};
     */
    KeymapsModule.prototype.remove = function (id) {
        var em = this.em;
        var keymap = this.get(id);
        if (keymap) {
            delete this.keymaps[id];
            keymap.keys.split(', ').forEach(function (k) {
                // @ts-ignore
                keymaster.unbind(k.trim());
            });
            em === null || em === void 0 ? void 0 : em.trigger('keymap:remove', keymap);
            return keymap;
        }
    };
    /**
     * Remove all binded keymaps
     * @return {this}
     */
    KeymapsModule.prototype.removeAll = function () {
        var _this = this;
        Object.keys(this.keymaps).forEach(function (keymap) { return _this.remove(keymap); });
        keymaster.handlers = {};
        return this;
    };
    KeymapsModule.prototype.destroy = function () {
        this.removeAll();
        this.keymaps = {};
    };
    return KeymapsModule;
}(abstract_Module));
/* harmony default export */ const keymaps = (KeymapsModule);

;// CONCATENATED MODULE: ./src/modal_dialog/config/config.ts
var modal_dialog_config_config_config = {
    stylePrefix: 'mdl-',
    title: '',
    content: '',
    backdrop: true,
    custom: false,
    extend: {},
};
/* harmony default export */ const modal_dialog_config_config = (modal_dialog_config_config_config);

;// CONCATENATED MODULE: ./src/modal_dialog/model/Modal.ts
var Modal_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();

var Modal = /** @class */ (function (_super) {
    Modal_extends(Modal, _super);
    function Modal() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Modal.prototype.defaults = function () {
        return {
            title: '',
            content: '',
            attributes: {},
            open: false,
        };
    };
    Modal.prototype.open = function () {
        this.set('open', true);
    };
    Modal.prototype.close = function () {
        this.set('open', false);
    };
    return Modal;
}(ModuleModel/* default */.Z));
/* harmony default export */ const model_Modal = (Modal);

;// CONCATENATED MODULE: ./src/modal_dialog/view/ModalView.ts
var ModalView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var ModalView_assign = (undefined && undefined.__assign) || function () {
    ModalView_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return ModalView_assign.apply(this, arguments);
};

var ModalView = /** @class */ (function (_super) {
    ModalView_extends(ModalView, _super);
    function ModalView(o) {
        var _this = _super.call(this, o) || this;
        var model = _this.model;
        _this.listenTo(model, 'change:open', _this.updateOpen);
        _this.listenTo(model, 'change:title', _this.updateTitle);
        _this.listenTo(model, 'change:content', _this.updateContent);
        return _this;
    }
    ModalView.prototype.template = function (_a) {
        var pfx = _a.pfx, ppfx = _a.ppfx, content = _a.content, title = _a.title;
        return "<div class=\"".concat(pfx, "dialog ").concat(ppfx, "one-bg ").concat(ppfx, "two-color\">\n      <div class=\"").concat(pfx, "header\">\n        <div class=\"").concat(pfx, "title\">").concat(title, "</div>\n        <div class=\"").concat(pfx, "btn-close\" data-close-modal>&Cross;</div>\n      </div>\n      <div class=\"").concat(pfx, "content\">\n        <div id=\"").concat(pfx, "c\">").concat(content, "</div>\n        <div style=\"clear:both\"></div>\n      </div>\n    </div>\n    <div class=\"").concat(pfx, "collector\" style=\"display: none\"></div>");
    };
    ModalView.prototype.events = function () {
        return {
            click: 'onClick',
            'click [data-close-modal]': 'hide',
        };
    };
    ModalView.prototype.onClick = function (e) {
        var bkd = this.config.backdrop;
        bkd && e.target === this.el && this.hide();
    };
    /**
     * Returns collector element
     * @return {HTMLElement}
     * @private
     */
    ModalView.prototype.getCollector = function () {
        if (!this.$collector)
            this.$collector = this.$el.find('.' + this.pfx + 'collector');
        return this.$collector;
    };
    /**
     * Returns content element
     * @return {HTMLElement}
     */
    ModalView.prototype.getContent = function () {
        var pfx = this.pfx;
        if (!this.$content) {
            this.$content = this.$el.find(".".concat(pfx, "content #").concat(pfx, "c"));
        }
        return this.$content;
    };
    /**
     * Returns title element
     * @return {HTMLElement}
     * @private
     */
    ModalView.prototype.getTitle = function (opts) {
        if (opts === void 0) { opts = {}; }
        if (!this.$title)
            this.$title = this.$el.find('.' + this.pfx + 'title');
        return opts.$ ? this.$title : this.$title.get(0);
    };
    /**
     * Update content
     * @private
     * */
    ModalView.prototype.updateContent = function () {
        var content = this.getContent();
        var children = content.children();
        var coll = this.getCollector();
        var body = this.model.get('content');
        children.length && coll.append(children);
        content.empty().append(body);
    };
    /**
     * Update title
     * @private
     * */
    ModalView.prototype.updateTitle = function () {
        var title = this.getTitle({ $: true });
        //@ts-ignore
        title && title.empty().append(this.model.get('title'));
    };
    /**
     * Update open
     * @private
     * */
    ModalView.prototype.updateOpen = function () {
        this.el.style.display = this.model.get('open') ? '' : 'none';
    };
    /**
     * Hide modal
     * @private
     * */
    ModalView.prototype.hide = function () {
        this.model.close();
    };
    /**
     * Show modal
     * @private
     * */
    ModalView.prototype.show = function () {
        this.model.open();
    };
    ModalView.prototype.updateAttr = function (attr) {
        var _a = this, pfx = _a.pfx, $el = _a.$el, el = _a.el;
        //@ts-ignore
        var currAttr = [].slice.call(el.attributes).map(function (i) { return i.name; });
        $el.removeAttr(currAttr.join(' '));
        $el.attr(ModalView_assign(ModalView_assign({}, (attr || {})), { class: "".concat(pfx, "container ").concat((attr && attr.class) || '').trim() }));
    };
    ModalView.prototype.render = function () {
        var el = this.$el;
        var obj = this.model.toJSON();
        obj.pfx = this.pfx;
        obj.ppfx = this.ppfx;
        el.html(this.template(obj));
        this.updateAttr();
        this.updateOpen();
        return this;
    };
    return ModalView;
}(abstract_ModuleView));
/* harmony default export */ const view_ModalView = (ModalView);

;// CONCATENATED MODULE: ./src/modal_dialog/index.ts
/**
 * You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](https://github.com/GrapesJS/grapesjs/blob/master/src/modal_dialog/config/config.ts)
 * ```js
 * const editor = grapesjs.init({
 *  modal: {
 *    // options
 *  }
 * })
 * ```
 *
 * Once the editor is instantiated you can use its API. Before using these methods you should get the module from the instance
 *
 * ```js
 * const modal = editor.Modal;
 * ```
 *
 * ## Available Events
 * * `modal:open` - Modal is opened
 * * `modal:close` - Modal is closed
 * * `modal` - Event triggered on any change related to the modal. An object containing all the available data about the triggered event is passed as an argument to the callback.
 *
 * ## Methods
 * * [open](#open)
 * * [close](#close)
 * * [isOpen](#isopen)
 * * [setTitle](#settitle)
 * * [getTitle](#gettitle)
 * * [setContent](#setcontent)
 * * [getContent](#getcontent)
 * * [onceClose](#onceclose)
 * * [onceOpen](#onceopen)
 *
 * @module Modal
 */
var modal_dialog_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();






var ModalModule = /** @class */ (function (_super) {
    modal_dialog_extends(ModalModule, _super);
    /**
     * Initialize module. Automatically called with a new instance of the editor
     * @param {Object} config Configurations
     * @private
     */
    function ModalModule(em) {
        var _this = _super.call(this, em, 'Modal', modal_dialog_config_config) || this;
        _this.model = new model_Modal(_this);
        _this.model.on('change:open', function (m, enable) {
            em.trigger("modal:".concat(enable ? 'open' : 'close'));
        });
        _this.model.on('change', (0,index_all.debounce)(function () {
            var data = _this._evData();
            var custom = _this.config.custom;
            //@ts-ignore
            (0,index_all.isFunction)(custom) && custom(data);
            em.trigger('modal', data);
        }, 0));
        return _this;
    }
    ModalModule.prototype._evData = function () {
        var _this = this;
        var titl = this.getTitle();
        var cnt = this.getContent();
        var _a = this.model.attributes, open = _a.open, attributes = _a.attributes;
        return {
            open: open,
            attributes: attributes,
            title: (0,index_all.isString)(titl) ? (0,dom/* createText */.rw)(titl) : titl,
            //@ts-ignore
            content: (0,index_all.isString)(cnt) ? (0,dom/* createText */.rw)(cnt) : cnt.get ? cnt.get(0) : cnt,
            close: function () {
                _this.close();
            },
        };
    };
    ModalModule.prototype.postRender = function (view) {
        var el = view.model.config.el || view.el;
        var res = this.render();
        res && (el === null || el === void 0 ? void 0 : el.appendChild(res));
    };
    /**
     * Open the modal window
     * @param {Object} [opts={}] Options
     * @param {String|HTMLElement} [opts.title] Title to set for the modal
     * @param {String|HTMLElement} [opts.content] Content to set for the modal
     * @param {Object} [opts.attributes] Updates the modal wrapper with custom attributes
     * @returns {this}
     * @example
     * modal.open({
     *   title: 'My title',
     *   content: 'My content',
     *   attributes: { class: 'my-class' },
     * });
     */
    ModalModule.prototype.open = function (opts) {
        if (opts === void 0) { opts = {}; }
        var attr = opts.attributes || {};
        opts.title && this.setTitle(opts.title);
        opts.content && this.setContent(opts.content);
        this.model.set('attributes', attr);
        this.model.open();
        this.modal && this.modal.updateAttr(attr);
        return this;
    };
    /**
     * Close the modal window
     * @returns {this}
     * @example
     * modal.close();
     */
    ModalModule.prototype.close = function () {
        this.model.close();
        return this;
    };
    /**
     * Execute callback when the modal will be closed.
     * The callback will be called one only time
     * @param {Function} clb Callback to call
     * @returns {this}
     * @example
     * modal.onceClose(() => {
     *  console.log('The modal is closed');
     * });
     */
    ModalModule.prototype.onceClose = function (clb) {
        this.em.once('modal:close', clb);
        return this;
    };
    /**
     * Execute callback when the modal will be opened.
     * The callback will be called one only time
     * @param {Function} clb Callback to call
     * @returns {this}
     * @example
     * modal.onceOpen(() => {
     *  console.log('The modal is opened');
     * });
     */
    ModalModule.prototype.onceOpen = function (clb) {
        this.em.once('modal:open', clb);
        return this;
    };
    /**
     * Checks if the modal window is open
     * @returns {Boolean}
     * @example
     * modal.isOpen(); // true | false
     */
    ModalModule.prototype.isOpen = function () {
        return !!this.model.get('open');
    };
    /**
     * Set the title to the modal window
     * @param {string | HTMLElement} title Title
     * @returns {this}
     * @example
     * // pass a string
     * modal.setTitle('Some title');
     * // or an HTMLElement
     * const el = document.createElement('div');
     * el.innerText =  'New title';
     * modal.setTitle(el);
     */
    ModalModule.prototype.setTitle = function (title) {
        this.model.set('title', title);
        return this;
    };
    /**
     * Returns the title of the modal window
     * @returns {string | HTMLElement}
     * @example
     * modal.getTitle();
     */
    ModalModule.prototype.getTitle = function () {
        return this.model.get('title');
    };
    /**
     * Set the content of the modal window
     * @param {string | HTMLElement} content Content
     * @returns {this}
     * @example
     * // pass a string
     * modal.setContent('Some content');
     * // or an HTMLElement
     * const el = document.createElement('div');
     * el.innerText =  'New content';
     * modal.setContent(el);
     */
    ModalModule.prototype.setContent = function (content) {
        this.model.set('content', ' ');
        this.model.set('content', content);
        return this;
    };
    /**
     * Get the content of the modal window
     * @returns {string | HTMLElement}
     * @example
     * modal.getContent();
     */
    ModalModule.prototype.getContent = function () {
        return this.model.get('content');
    };
    /**
     * Returns content element
     * @return {HTMLElement}
     * @private
     */
    ModalModule.prototype.getContentEl = function () {
        var _a;
        return (_a = this.modal) === null || _a === void 0 ? void 0 : _a.getContent().get(0);
    };
    /**
     * Returns modal model
     * @return {Model}
     * @private
     */
    ModalModule.prototype.getModel = function () {
        return this.model;
    };
    /**
     * Render the modal window
     * @return {HTMLElement}
     * @private
     */
    ModalModule.prototype.render = function () {
        var _a;
        if (this.config.custom)
            return;
        var View = view_ModalView.extend(this.config.extend);
        var el = this.modal && this.modal.el;
        this.modal = new View({
            el: el,
            model: this.model,
            config: this.config,
        });
        return (_a = this.modal) === null || _a === void 0 ? void 0 : _a.render().el;
    };
    ModalModule.prototype.destroy = function () {
        var _a;
        (_a = this.modal) === null || _a === void 0 ? void 0 : _a.remove();
    };
    return ModalModule;
}(abstract_Module));
/* harmony default export */ const modal_dialog = (ModalModule);

;// CONCATENATED MODULE: ./src/panels/config/config.ts
var swv = 'sw-visibility';
var expt = 'export-template';
var osm = 'open-sm';
var otm = 'open-tm';
var ola = 'open-layers';
var obl = 'open-blocks';
var ful = 'fullscreen';
var prv = 'preview';
var panels_config_config_config = {
    stylePrefix: 'pn-',
    defaults: [
        {
            id: 'commands',
            buttons: [{}],
        },
        {
            id: 'options',
            buttons: [
                {
                    active: true,
                    id: swv,
                    className: 'fa fa-square-o',
                    command: 'core:component-outline',
                    context: swv,
                    attributes: { title: 'View components' },
                },
                {
                    id: prv,
                    className: 'fa fa-eye',
                    command: prv,
                    context: prv,
                    attributes: { title: 'Preview' },
                },
                {
                    id: ful,
                    className: 'fa fa-arrows-alt',
                    command: ful,
                    context: ful,
                    attributes: { title: 'Fullscreen' },
                },
                {
                    id: expt,
                    className: 'fa fa-code',
                    command: expt,
                    attributes: { title: 'View code' },
                },
            ],
        },
        {
            id: 'views',
            buttons: [
                {
                    id: osm,
                    className: 'fa fa-paint-brush',
                    command: osm,
                    active: true,
                    togglable: false,
                    attributes: { title: 'Open Style Manager' },
                },
                {
                    id: otm,
                    className: 'fa fa-cog',
                    command: otm,
                    togglable: false,
                    attributes: { title: 'Settings' },
                },
                {
                    id: ola,
                    className: 'fa fa-bars',
                    command: ola,
                    togglable: false,
                    attributes: { title: 'Open Layer Manager' },
                },
                {
                    id: obl,
                    className: 'fa fa-th-large',
                    command: obl,
                    togglable: false,
                    attributes: { title: 'Open Blocks' },
                },
            ],
        },
    ],
};
/* harmony default export */ const panels_config_config = (panels_config_config_config);

;// CONCATENATED MODULE: ./src/panels/model/Button.ts
var Button_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();


var Button = /** @class */ (function (_super) {
    Button_extends(Button, _super);
    function Button(module, options) {
        var _this = _super.call(this, module, options) || this;
        if (_this.get('buttons').length) {
            _this.set('buttons', new model_Buttons(_this.module, _this.get('buttons')));
        }
        return _this;
    }
    Button.prototype.defaults = function () {
        return {
            id: '',
            label: '',
            tagName: 'span',
            className: '',
            command: '',
            context: '',
            buttons: [],
            attributes: {},
            options: {},
            active: false,
            dragDrop: false,
            togglable: true,
            runDefaultCommand: true,
            stopDefaultCommand: false,
            disable: false,
        };
    };
    Object.defineProperty(Button.prototype, "className", {
        get: function () {
            return this.get('className');
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Button.prototype, "command", {
        get: function () {
            return this.get('command');
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Button.prototype, "active", {
        get: function () {
            return this.get('active');
        },
        set: function (isActive) {
            this.set('active', isActive);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Button.prototype, "togglable", {
        get: function () {
            return this.get('togglable');
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Button.prototype, "runDefaultCommand", {
        get: function () {
            return this.get('runDefaultCommand');
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Button.prototype, "stopDefaultCommand", {
        get: function () {
            return this.get('stopDefaultCommand');
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Button.prototype, "disable", {
        get: function () {
            return this.get('disable');
        },
        enumerable: false,
        configurable: true
    });
    return Button;
}(ModuleModel/* default */.Z));
/* harmony default export */ const model_Button = (Button);

;// CONCATENATED MODULE: ./src/panels/model/Buttons.ts
var Buttons_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();


var Buttons = /** @class */ (function (_super) {
    Buttons_extends(Buttons, _super);
    function Buttons(module, models) {
        return _super.call(this, module, models, model_Button) || this;
    }
    /**
     * Deactivate all buttons, except one passed
     * @param  {Object}  except  Model to ignore
     * @param  {Boolean}  r     Recursive flag
     *
     * @return  void
     * */
    Buttons.prototype.deactivateAllExceptOne = function (except, r) {
        this.forEach(function (model, index) {
            if (model !== except) {
                model.set('active', false);
                if (r && model.get('buttons').length)
                    model.get('buttons').deactivateAllExceptOne(except, r);
            }
        });
    };
    /**
     * Deactivate all buttons
     * @param  {String}  ctx Context string
     *
     * @return  void
     * */
    Buttons.prototype.deactivateAll = function (ctx, sender) {
        var context = ctx || '';
        this.forEach(function (model) {
            if (model.get('context') == context && model !== sender) {
                //@ts-ignore
                model.set('active', false, { fromCollection: true });
            }
        });
    };
    /**
     * Disables all buttons
     * @param  {String}  ctx Context string
     *
     * @return  void
     * */
    Buttons.prototype.disableAllButtons = function (ctx) {
        var context = ctx || '';
        this.forEach(function (model, index) {
            if (model.get('context') == context) {
                model.set('disable', true);
            }
        });
    };
    /**
     * Disables all buttons, except one passed
     * @param  {Object}  except  Model to ignore
     * @param  {Boolean}  r     Recursive flag
     *
     * @return  void
     * */
    Buttons.prototype.disableAllButtonsExceptOne = function (except, r) {
        this.forEach(function (model, index) {
            if (model !== except) {
                model.set('disable', true);
                if (r && model.get('buttons').length)
                    model.get('buttons').disableAllButtonsExceptOne(except, r);
            }
        });
    };
    return Buttons;
}(abstract_ModuleCollection));
/* harmony default export */ const model_Buttons = (Buttons);
Buttons.prototype.model = model_Button;

;// CONCATENATED MODULE: ./src/panels/model/Panel.ts
var Panel_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();


var Panel = /** @class */ (function (_super) {
    Panel_extends(Panel, _super);
    function Panel(module, options) {
        var _this = _super.call(this, module, options) || this;
        var btn = _this.get('buttons') || [];
        _this.buttons = new model_Buttons(module, btn);
        return _this;
    }
    Panel.prototype.defaults = function () {
        return {
            id: '',
            content: '',
            visible: true,
            buttons: [],
            attributes: {},
        };
    };
    Object.defineProperty(Panel.prototype, "buttons", {
        get: function () {
            return this.get('buttons');
        },
        set: function (buttons) {
            this.set('buttons', buttons);
        },
        enumerable: false,
        configurable: true
    });
    return Panel;
}(ModuleModel/* default */.Z));
/* harmony default export */ const model_Panel = (Panel);

;// CONCATENATED MODULE: ./src/panels/model/Panels.ts
var Panels_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();


var Panels = /** @class */ (function (_super) {
    Panels_extends(Panels, _super);
    function Panels(module, models) {
        return _super.call(this, module, models, model_Panel) || this;
    }
    return Panels;
}(abstract_ModuleCollection));
/* harmony default export */ const model_Panels = (Panels);
Panels.prototype.model = model_Panel;

;// CONCATENATED MODULE: ./src/panels/view/ButtonView.ts
var ButtonView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var ButtonView_assign = (undefined && undefined.__assign) || function () {
    ButtonView_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return ButtonView_assign.apply(this, arguments);
};


var ButtonView = /** @class */ (function (_super) {
    ButtonView_extends(ButtonView, _super);
    function ButtonView(o) {
        var _this = _super.call(this, o) || this;
        var _a = _this, model = _a.model, em = _a.em, pfx = _a.pfx, ppfx = _a.ppfx;
        var cls = model.className;
        var _b = model.attributes, command = _b.command, listen = _b.listen;
        _this.id = pfx + model.get('id');
        _this.activeCls = "".concat(pfx, "active ").concat(ppfx, "four-color");
        _this.disableCls = "".concat(ppfx, "disabled");
        _this.btnsVisCls = "".concat(pfx, "visible");
        _this.className = pfx + 'btn' + (cls ? ' ' + cls : '');
        _this.listenTo(model, 'change', _this.render);
        _this.listenTo(model, 'change:active updateActive', _this.updateActive);
        _this.listenTo(model, 'checkActive', _this.checkActive);
        _this.listenTo(model, 'change:bntsVis', _this.updateBtnsVis);
        _this.listenTo(model, 'change:attributes', _this.updateAttributes);
        _this.listenTo(model, 'change:className', _this.updateClassName);
        _this.listenTo(model, 'change:disable', _this.updateDisable);
        if (em && (0,index_all.isString)(command) && listen) {
            var chnOpt_1 = { fromListen: true };
            _this.listenTo(em, "run:".concat(command), function () { return model.set('active', true, chnOpt_1); });
            _this.listenTo(em, "stop:".concat(command), function () { return model.set('active', false, chnOpt_1); });
        }
        if (em && em.get)
            _this.commands = em.get('Commands');
        return _this;
    }
    //@ts-ignore
    ButtonView.prototype.tagName = function () {
        return this.model.get('tagName');
    };
    ButtonView.prototype.events = function () {
        return {
            click: 'clicked',
        };
    };
    /**
     * Updates class name of the button
     *
     * @return   void
     * */
    ButtonView.prototype.updateClassName = function () {
        var _a = this, model = _a.model, pfx = _a.pfx;
        var cls = model.className;
        var attrCls = model.get('attributes').class;
        var classStr = "".concat(attrCls ? attrCls : '', " ").concat(pfx, "btn ").concat(cls ? cls : '');
        this.$el.attr('class', classStr.trim());
    };
    /**
     * Updates attributes of the button
     *
     * @return   void
     * */
    ButtonView.prototype.updateAttributes = function () {
        var _a = this, em = _a.em, model = _a.model, $el = _a.$el;
        var attr = model.get('attributes') || {};
        var title = em && em.t && em.t("panels.buttons.titles.".concat(model.id));
        $el.attr(attr);
        title && $el.attr({ title: title });
        this.updateClassName();
    };
    /**
     * Updates visibility of children buttons
     *
     * @return  void
     * */
    ButtonView.prototype.updateBtnsVis = function () {
        if (!this.$buttons)
            return;
        if (this.model.get('bntsVis'))
            this.$buttons.addClass(this.btnsVisCls);
        else
            this.$buttons.removeClass(this.btnsVisCls);
    };
    /**
     * Update active status of the button
     *
     * @return   void
     * */
    ButtonView.prototype.updateActive = function (m, v, opts) {
        var _a;
        if (opts === void 0) { opts = {}; }
        var _b = this, model = _b.model, commands = _b.commands, $el = _b.$el, activeCls = _b.activeCls;
        var fromCollection = opts.fromCollection, fromListen = opts.fromListen;
        var context = model.get('context');
        var options = model.get('options');
        var commandName = model.command;
        var command = {};
        if (!commandName)
            return;
        if (commands && (0,index_all.isString)(commandName)) {
            command = commands.get(commandName) || {};
        }
        else if ((0,index_all.isFunction)(commandName)) {
            command = commands.create({ run: commandName });
        }
        else if (commandName !== null && (0,index_all.isObject)(commandName)) {
            command = commands.create(commandName);
        }
        if (model.active) {
            !fromCollection && ((_a = model.collection) === null || _a === void 0 ? void 0 : _a.deactivateAll(context, model));
            model.set('active', true, { silent: true }).trigger('checkActive');
            !fromListen && commands.runCommand(command, ButtonView_assign(ButtonView_assign({}, options), { sender: model }));
            // Disable button if the command has no stop method
            //@ts-ignore
            command.noStop && model.set('active', false);
        }
        else {
            $el.removeClass(activeCls);
            !fromListen && commands.stopCommand(command, ButtonView_assign(ButtonView_assign({}, options), { sender: model, force: 1 }));
        }
    };
    ButtonView.prototype.updateDisable = function () {
        var _a = this, disableCls = _a.disableCls, model = _a.model;
        var disable = model.disable;
        this.$el[disable ? 'addClass' : 'removeClass'](disableCls);
    };
    /**
     * Update active style status
     *
     * @return   void
     * */
    ButtonView.prototype.checkActive = function () {
        var _a = this, model = _a.model, $el = _a.$el, activeCls = _a.activeCls;
        model.active ? $el.addClass(activeCls) : $el.removeClass(activeCls);
    };
    /**
     * Triggered when button is clicked
     * @return   void
     * */
    ButtonView.prototype.clicked = function () {
        var model = this.model;
        if (model.get('bntsVis') || model.disable || !model.command)
            return;
        this.toggleActive();
    };
    ButtonView.prototype.toggleActive = function () {
        var _a = this, model = _a.model, em = _a.em;
        var active = model.active, togglable = model.togglable;
        if (active && !togglable)
            return;
        model.active = !active;
        // If the stop is requested
        if (active) {
            if (model.runDefaultCommand)
                em.runDefault();
        }
        else {
            if (model.stopDefaultCommand)
                em.stopDefault();
        }
    };
    ButtonView.prototype.render = function () {
        var model = this.model;
        var label = model.get('label');
        var $el = this.$el;
        !model.get('el') && $el.empty();
        this.updateAttributes();
        label && $el.append(label);
        this.checkActive();
        this.updateDisable();
        return this;
    };
    return ButtonView;
}(abstract_ModuleView));
/* harmony default export */ const view_ButtonView = (ButtonView);

;// CONCATENATED MODULE: ./src/panels/view/ButtonsView.ts
var ButtonsView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();



var ButtonsView = /** @class */ (function (_super) {
    ButtonsView_extends(ButtonsView, _super);
    function ButtonsView(collection) {
        var _this = _super.call(this, { collection: collection }) || this;
        _this.listenTo(_this.collection, 'add', _this.addTo);
        _this.listenTo(_this.collection, 'reset remove', _this.render);
        _this.className = _this.pfx + 'buttons';
        return _this;
    }
    /**
     * Add to collection
     * @param Object Model
     *
     * @return Object
     * */
    ButtonsView.prototype.addTo = function (model) {
        this.addToCollection(model);
    };
    /**
     * Add new object to collection
     * @param  Object  Model
     * @param  Object   Fragment collection
     *
     * @return Object Object created
     * */
    ButtonsView.prototype.addToCollection = function (model, fragmentEl) {
        var fragment = fragmentEl || null;
        var el = model.get('el');
        var view = new view_ButtonView({
            el: el,
            model: model,
        });
        var rendered = view.render().el;
        if (fragment) {
            fragment.appendChild(rendered);
        }
        else {
            this.$el.append(rendered);
        }
        return rendered;
    };
    ButtonsView.prototype.render = function () {
        var _this = this;
        var fragment = document.createDocumentFragment();
        this.$el.empty();
        this.collection.each(function (model) { return _this.addToCollection(model, fragment); });
        this.$el.append(fragment);
        this.$el.attr('class', (0,index_all.result)(this, 'className'));
        return this;
    };
    return ButtonsView;
}(abstract_ModuleView));
/* harmony default export */ const view_ButtonsView = (ButtonsView);

;// CONCATENATED MODULE: ./src/panels/view/PanelView.ts
var PanelView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var PanelView_assign = (undefined && undefined.__assign) || function () {
    PanelView_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return PanelView_assign.apply(this, arguments);
};


var PanelView = /** @class */ (function (_super) {
    PanelView_extends(PanelView, _super);
    function PanelView(model) {
        var _this = _super.call(this, { model: model, el: model.get('el') }) || this;
        _this.className = _this.pfx + 'panel';
        _this.id = _this.pfx + model.get('id');
        _this.listenTo(model, 'change:appendContent', _this.appendContent);
        _this.listenTo(model, 'change:content', _this.updateContent);
        _this.listenTo(model, 'change:visible', _this.toggleVisible);
        model.view = _this;
        return _this;
    }
    /**
     * Append content of the panel
     * */
    PanelView.prototype.appendContent = function () {
        this.$el.append(this.model.get('appendContent'));
    };
    /**
     * Update content
     * */
    PanelView.prototype.updateContent = function () {
        this.$el.html(this.model.get('content'));
    };
    PanelView.prototype.toggleVisible = function () {
        if (!this.model.get('visible')) {
            this.$el.addClass("".concat(this.ppfx, "hidden"));
            return;
        }
        this.$el.removeClass("".concat(this.ppfx, "hidden"));
    };
    //@ts-ignore
    PanelView.prototype.attributes = function () {
        return this.model.get('attributes');
    };
    PanelView.prototype.initResize = function () {
        var em = this.em;
        var editor = em === null || em === void 0 ? void 0 : em.Editor;
        var resizable = this.model.get('resizable');
        if (editor && resizable) {
            var resz = resizable === true ? [true, true, true, true] : resizable;
            var resLen = resz.length;
            var tc = void 0, cr = void 0, bc = void 0, cl = false;
            // Choose which sides of the panel are resizable
            if (resLen == 2) {
                var resBools = resz;
                tc = resBools[0];
                bc = resBools[0];
                cr = resBools[1];
                cl = resBools[1];
            }
            else if (resLen == 4) {
                var resBools = resz;
                tc = resBools[0];
                cr = resBools[1];
                bc = resBools[2];
                cl = resBools[3];
            }
            var resizer_1 = new editor.Utils.Resizer(PanelView_assign({ tc: tc, cr: cr, bc: bc, cl: cl, tl: false, tr: false, bl: false, br: false, appendTo: this.el, silentFrames: true, avoidContainerUpdate: true, prefix: editor.getConfig().stylePrefix, onEnd: function () {
                    em.Canvas.refresh({ all: true });
                }, posFetcher: function (el, _a) {
                    var target = _a.target;
                    var style = el.style;
                    var config = resizer_1.getConfig();
                    var keyWidth = config.keyWidth;
                    var keyHeight = config.keyHeight;
                    var rect = el.getBoundingClientRect();
                    var forContainer = target == 'container';
                    var styleWidth = style[keyWidth];
                    var styleHeight = style[keyHeight];
                    var width = styleWidth && !forContainer ? parseFloat(styleWidth) : rect.width;
                    var height = styleHeight && !forContainer ? parseFloat(styleHeight) : rect.height;
                    return {
                        left: 0,
                        top: 0,
                        width: width,
                        height: height,
                    };
                } }, (resizable && typeof resizable !== 'boolean' ? resizable : {})));
            resizer_1.blur = function () { };
            resizer_1.focus(this.el);
        }
    };
    PanelView.prototype.render = function () {
        var buttons = this.model.buttons;
        var $el = this.$el;
        var ppfx = this.ppfx;
        var cls = "".concat(this.className, " ").concat(this.id, " ").concat(ppfx, "one-bg ").concat(ppfx, "two-color");
        $el.addClass(cls);
        this.toggleVisible();
        if (buttons.length) {
            var buttonsView = new view_ButtonsView(buttons);
            $el.append(buttonsView.render().el);
        }
        $el.append(this.model.get('content'));
        return this;
    };
    return PanelView;
}(abstract_ModuleView));
/* harmony default export */ const view_PanelView = (PanelView);

;// CONCATENATED MODULE: ./src/panels/view/PanelsView.ts
var PanelsView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();


var PanelsView = /** @class */ (function (_super) {
    PanelsView_extends(PanelsView, _super);
    function PanelsView(target) {
        var _this = _super.call(this, { collection: target }) || this;
        _this.listenTo(target, 'add', _this.addTo);
        _this.listenTo(target, 'reset', _this.render);
        _this.listenTo(target, 'remove', _this.onRemove);
        _this.className = _this.pfx + 'panels';
        return _this;
    }
    PanelsView.prototype.onRemove = function (model) {
        var view = model.view;
        view && view.remove();
    };
    /**
     * Add to collection
     * @param Object Model
     *
     * @return Object
     * @private
     * */
    PanelsView.prototype.addTo = function (model) {
        this.addToCollection(model);
    };
    /**
     * Add new object to collection
     * @param  Object  Model
     * @param  Object   Fragment collection
     * @param  integer  Index of append
     *
     * @return Object Object created
     * @private
     * */
    PanelsView.prototype.addToCollection = function (model, fragmentEl) {
        var fragment = fragmentEl || null;
        var el = model.get('el');
        var view = new view_PanelView(model);
        var rendered = view.render().el;
        var appendTo = model.get('appendTo');
        // Do nothing if the panel was requested to be another element
        if (el) {
        }
        else if (appendTo) {
            var appendEl = document.querySelector(appendTo);
            appendEl === null || appendEl === void 0 ? void 0 : appendEl.appendChild(rendered);
        }
        else {
            if (fragment) {
                fragment.appendChild(rendered);
            }
            else {
                this.$el.append(rendered);
            }
        }
        view.initResize();
        return rendered;
    };
    PanelsView.prototype.render = function () {
        var _this = this;
        var $el = this.$el;
        var frag = document.createDocumentFragment();
        $el.empty();
        this.collection.each(function (model) { return _this.addToCollection(model, frag); });
        $el.append(frag);
        $el.attr('class', this.className);
        return this;
    };
    return PanelsView;
}(abstract_ModuleView));
/* harmony default export */ const view_PanelsView = (PanelsView);

;// CONCATENATED MODULE: ./src/panels/index.ts
var panels_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
/**
 * You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](https://github.com/GrapesJS/grapesjs/blob/master/src/panels/config/config.ts)
 * ```js
 * const editor = grapesjs.init({
 *  panels: {
 *    // options
 *  }
 * })
 * ```
 *
 * Once the editor is instantiated you can use its API. Before using these methods you should get the module from the instance
 *
 * ```js
 * const panelManager = editor.Panels;
 * ```
 *
 * * [addPanel](#addpanel)
 * * [addButton](#addbutton)
 * * [getButton](#getbutton)
 * * [getPanel](#getpanel)
 * * [getPanels](#getpanels)
 * * [getPanelsEl](#getpanelsel)
 * * [removePanel](#removepanel)
 * * [removeButton](#removebutton)
 *
 * @module Panels
 */




var PanelManager = /** @class */ (function (_super) {
    panels_extends(PanelManager, _super);
    /**
     * Initialize module. Automatically called with a new instance of the editor
     * @param {Object} config Configurations
     * @private
     */
    function PanelManager(em) {
        var _this = _super.call(this, em, 'Panels', panels_config_config) || this;
        _this.panels = new model_Panels(_this, _this.config.defaults);
        for (var name in panels_config_config) {
            //@ts-ignore
            if (!(name in _this.config))
                _this.config[name] = panels_config_config[name];
        }
        return _this;
    }
    /**
     * Returns the collection of panels
     * @return {Collection} Collection of panel
     */
    PanelManager.prototype.getPanels = function () {
        return this.panels;
    };
    /**
     * Returns panels element
     * @return {HTMLElement}
     */
    PanelManager.prototype.getPanelsEl = function () {
        var _a;
        return (_a = this.PanelsViewObj) === null || _a === void 0 ? void 0 : _a.el;
    };
    /**
     * Add new panel to the collection
     * @param {Object|Panel} panel Object with right properties or an instance of Panel
     * @return {Panel} Added panel. Useful in case passed argument was an Object
     * @example
     * const newPanel = panelManager.addPanel({
     *  id: 'myNewPanel',
     *  visible: true,
     *  buttons: [...],
     * });
     */
    PanelManager.prototype.addPanel = function (panel) {
        return this.panels.add(panel);
    };
    /**
     * Remove a panel from the collection
     * @param {Panel|String} panel Panel instance or panel id
     * @return {Panel} Removed panel
     * @example
     * const somePanel = panelManager.getPanel('somePanel');
     * const removedPanel = panelManager.removePanel(somePanel);
     *
     * // or by id
     * const removedPanel = panelManager.removePanel('myNewPanel');
     *
     */
    PanelManager.prototype.removePanel = function (panel) {
        return this.panels.remove(panel);
    };
    /**
     * Get panel by ID
     * @param  {string} id Id string
     * @return {Panel|null}
     * @example
     * const myPanel = panelManager.getPanel('myPanel');
     */
    PanelManager.prototype.getPanel = function (id) {
        var res = this.panels.where({ id: id });
        return res.length ? res[0] : null;
    };
    /**
     * Add button to the panel
     * @param {string} panelId Panel's ID
     * @param {Object|Button} button Button object or instance of Button
     * @return {Button|null} Added button. Useful in case passed button was an Object
     * @example
     * const newButton = panelManager.addButton('myNewPanel',{
     *   id: 'myNewButton',
     *   className: 'someClass',
     *   command: 'someCommand',
     *   attributes: { title: 'Some title'},
     *   active: false,
     * });
     * // It's also possible to pass the command as an object
     * // with .run and .stop methods
     * ...
     * command: {
     *   run: function(editor) {
     *     ...
     *   },
     *   stop: function(editor) {
     *     ...
     *   }
     * },
     * // Or simply like a function which will be evaluated as a single .run command
     * ...
     * command: function(editor) {
     *   ...
     * }
     */
    PanelManager.prototype.addButton = function (panelId, button) {
        var pn = this.getPanel(panelId);
        return pn ? pn.buttons.add(button) : null;
    };
    /**
     * Remove button from the panel
     * @param {String} panelId Panel's ID
     * @param {String} buttonId Button's ID
     * @return {Button|null} Removed button.
     * @example
     * const removedButton = panelManager.addButton('myNewPanel',{
     *   id: 'myNewButton',
     *   className: 'someClass',
     *   command: 'someCommand',
     *   attributes: { title: 'Some title'},
     *   active: false,
     * });
     *
     * const removedButton = panelManager.removeButton('myNewPanel', 'myNewButton');
     *
     */
    PanelManager.prototype.removeButton = function (panelId, button) {
        var pn = this.getPanel(panelId);
        return pn && pn.buttons.remove(button);
    };
    /**
     * Get button from the panel
     * @param {string} panelId Panel's ID
     * @param {string} id Button's ID
     * @return {Button|null}
     * @example
     * const button = panelManager.getButton('myPanel', 'myButton');
     */
    PanelManager.prototype.getButton = function (panelId, id) {
        var pn = this.getPanel(panelId);
        if (pn) {
            var res = pn.buttons.where({ id: id });
            return res.length ? res[0] : null;
        }
        return null;
    };
    /**
     * Render panels and buttons
     * @return {HTMLElement}
     * @private
     */
    PanelManager.prototype.render = function () {
        var _a;
        (_a = this.PanelsViewObj) === null || _a === void 0 ? void 0 : _a.remove();
        this.PanelsViewObj = new view_PanelsView(this.panels);
        return this.PanelsViewObj.render().el;
    };
    /**
     * Active activable buttons
     * @private
     */
    PanelManager.prototype.active = function () {
        this.getPanels().each(function (p) {
            p.buttons.each(function (btn) {
                btn.get('active') && btn.trigger('updateActive');
            });
        });
    };
    /**
     * Disable buttons flagged as disabled
     * @private
     */
    PanelManager.prototype.disableButtons = function () {
        this.getPanels().each(function (p) {
            p.buttons.each(function (btn) {
                if (btn.get('disable'))
                    btn.trigger('change:disable');
            });
        });
    };
    PanelManager.prototype.destroy = function () {
        this.panels.reset();
        this.panels.stopListening();
        this.PanelsViewObj && this.PanelsViewObj.remove();
    };
    return PanelManager;
}(abstract_Module));
/* harmony default export */ const panels = (PanelManager);

;// CONCATENATED MODULE: ./src/code_manager/config/config.ts
var code_manager_config_config_config = {
    stylePrefix: 'cm-',
    optsCodeViewer: {},
};
/* harmony default export */ const code_manager_config_config = (code_manager_config_config_config);

;// CONCATENATED MODULE: ./src/code_manager/model/HtmlGenerator.ts
var HtmlGenerator_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var HtmlGenerator_rest = (undefined && undefined.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};

var HTMLGenerator = /** @class */ (function (_super) {
    HtmlGenerator_extends(HTMLGenerator, _super);
    function HTMLGenerator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    HTMLGenerator.prototype.build = function (model, opts) {
        if (opts === void 0) { opts = {}; }
        var em = opts.em, restOpts = HtmlGenerator_rest(opts, ["em"]);
        var htmlOpts = restOpts;
        // Remove unnecessary IDs
        if (opts.cleanId && em) {
            var rules = em.Css.getAll();
            var idRules_1 = rules
                .toJSON()
                .map(function (rule) {
                var sels = rule.selectors;
                var sel = sels && sels.length === 1 && sels.models[0];
                return sel && sel.isId() && sel.get('name');
            })
                .filter(Boolean);
            if (!htmlOpts.attributes) {
                htmlOpts.attributes = function (mod, attrs) {
                    var id = attrs.id;
                    if (id &&
                        id[0] === 'i' && // all autogenerated IDs start with 'i'
                        !mod.get('script') && // if the component has script, we have to leave the ID
                        !mod.get('attributes').id && // id is not intentionally in attributes
                        idRules_1.indexOf(id) < 0 // we shouldn't have any rule with this ID
                    ) {
                        delete attrs.id;
                    }
                    return attrs;
                };
            }
        }
        return model.toHTML(htmlOpts);
    };
    return HTMLGenerator;
}(common/* Model */.Hn));
/* harmony default export */ const HtmlGenerator = (HTMLGenerator);

;// CONCATENATED MODULE: ./src/code_manager/model/JsonGenerator.ts
var JsonGenerator_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();


var JsonGenerator = /** @class */ (function (_super) {
    JsonGenerator_extends(JsonGenerator, _super);
    function JsonGenerator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    JsonGenerator.prototype.build = function (model) {
        var _this = this;
        // @ts-ignore
        var json = model.toJSON();
        this.beforeEach(json);
        (0,index_all.each)(json, function (v, attr) {
            var obj = json[attr];
            if (obj instanceof common/* Model */.Hn) {
                // @ts-ignore
                json[attr] = _this.build(obj);
            }
            else if (obj instanceof common/* Collection */.FE) {
                var coll = obj;
                json[attr] = [];
                if (coll.length) {
                    coll.forEach(function (el, index) {
                        json[attr][index] = _this.build(el);
                    });
                }
            }
        });
        return json;
    };
    /**
     * Execute on each object
     * @param {Object} obj
     */
    JsonGenerator.prototype.beforeEach = function (obj) {
        delete obj.status;
    };
    return JsonGenerator;
}(common/* Model */.Hn));
/* harmony default export */ const model_JsonGenerator = (JsonGenerator);

;// CONCATENATED MODULE: ./src/code_manager/model/JsGenerator.ts
var JsGenerator_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();


function isFunctionEmpty(fn) {
    var _a;
    var content = ((_a = fn.toString().match(/\{([\s\S]*)\}/m)) === null || _a === void 0 ? void 0 : _a[1]) || ''; // content between first and last { }
    return content.replace(/^\s*\/\/.*$/gm, '').trim().length === 0; // remove comments
}
var JsGenerator = /** @class */ (function (_super) {
    JsGenerator_extends(JsGenerator, _super);
    function JsGenerator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    JsGenerator.prototype.mapModel = function (model) {
        var _a;
        var _this = this;
        var code = '';
        var script = model.get('script-export') || model.get('script');
        var type = model.get('type');
        var comps = model.get('components');
        var id = model.getId();
        if (script) {
            // If the component has scripts we need to expose his ID
            var attr = model.get('attributes');
            attr = (0,index_all.extend)({}, attr, { id: id });
            model.set('attributes', attr, { silent: true });
            // @ts-ignore
            var scrStr = model.getScriptString(script);
            var scrProps = model.get('script-props');
            // If the script was updated, I'll put its code in a separate container
            if (model.get('scriptUpdated') && !scrProps) {
                this.mapJs[type + '-' + id] = { ids: [id], code: scrStr };
            }
            else {
                var props = void 0;
                var mapType = this.mapJs[type];
                if (scrProps) {
                    props = model.__getScriptProps();
                }
                if (mapType) {
                    mapType.ids.push(id);
                    if (props)
                        mapType.props[id] = props;
                }
                else {
                    var res = { ids: [id], code: scrStr };
                    if (props)
                        res.props = (_a = {}, _a[id] = props, _a);
                    this.mapJs[type] = res;
                }
            }
        }
        comps.forEach(function (model) {
            code += _this.mapModel(model);
        });
        return code;
    };
    JsGenerator.prototype.build = function (model) {
        this.mapJs = {};
        this.mapModel(model);
        var code = '';
        for (var type in this.mapJs) {
            var mapType = this.mapJs[type];
            if (!mapType.code) {
                continue;
            }
            if (mapType.props) {
                if (isFunctionEmpty(mapType.code)) {
                    continue;
                }
                code += "\n          var props = ".concat(JSON.stringify(mapType.props), ";\n          var ids = Object.keys(props).map(function(id) { return '#'+id }).join(',');\n          var els = document.querySelectorAll(ids);\n          for (var i = 0, len = els.length; i < len; i++) {\n            var el = els[i];\n            (").concat(mapType.code, ".bind(el))(props[el.id]);\n          }");
            }
            else {
                // Deprecated
                var ids = '#' + mapType.ids.join(', #');
                code += "\n          var items = document.querySelectorAll('".concat(ids, "');\n          for (var i = 0, len = items.length; i < len; i++) {\n            (function(){\n").concat(mapType.code, "\n}.bind(items[i]))();\n          }");
            }
        }
        return code;
    };
    return JsGenerator;
}(common/* Model */.Hn));
/* harmony default export */ const model_JsGenerator = (JsGenerator);

;// CONCATENATED MODULE: ./src/code_manager/model/CodeMirrorEditor.ts
var CodeMirrorEditor_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var CodeMirrorEditor_assign = (undefined && undefined.__assign) || function () {
    CodeMirrorEditor_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return CodeMirrorEditor_assign.apply(this, arguments);
};



var CodeMirror;
if ((0,mixins.hasWin)()) {
    CodeMirror = __webpack_require__(631);
    __webpack_require__(531);
    __webpack_require__(629);
    __webpack_require__(210);
}
var CodeMirrorEditor = /** @class */ (function (_super) {
    CodeMirrorEditor_extends(CodeMirrorEditor, _super);
    function CodeMirrorEditor() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    CodeMirrorEditor.prototype.defaults = function () {
        return {
            input: '',
            label: '',
            codeName: '',
            theme: 'hopscotch',
            readOnly: true,
            lineNumbers: true,
            autoFormat: true,
        };
    };
    CodeMirrorEditor.prototype.init = function (el) {
        (0,index_all.bindAll)(this, 'onChange');
        this.editor = CodeMirror.fromTextArea(el, CodeMirrorEditor_assign({ dragDrop: false, lineWrapping: true, mode: this.get('codeName') }, this.attributes));
        this.element = el;
        this.editor.on('change', this.onChange);
        return this;
    };
    CodeMirrorEditor.prototype.onChange = function () {
        this.trigger('update', this);
    };
    CodeMirrorEditor.prototype.getEditor = function () {
        return this.editor;
    };
    /**
     * The element where the viewer is attached
     * @return {HTMLElement}
     */
    CodeMirrorEditor.prototype.getElement = function () {
        return this.element;
    };
    /**
     * Set the element which contains the viewer attached.
     * Generally, it should be just a textarea, but some editor might require
     * a container for it some in that case this method can be used
     * @param {HTMLElement} el
     * @return {self}
     */
    CodeMirrorEditor.prototype.setElement = function (el) {
        this.element = el;
        return this;
    };
    /**
     * Refresh the viewer
     * @return {self}
     */
    CodeMirrorEditor.prototype.refresh = function () {
        this.getEditor().refresh();
        return this;
    };
    /**
     * Focus the viewer
     * @return {self}
     */
    CodeMirrorEditor.prototype.focus = function () {
        this.getEditor().focus();
        return this;
    };
    CodeMirrorEditor.prototype.getContent = function () {
        var ed = this.getEditor();
        return ed && ed.getValue();
    };
    /** @inheritdoc */
    CodeMirrorEditor.prototype.setContent = function (value, opts) {
        var _this = this;
        if (opts === void 0) { opts = {}; }
        var editor = this.editor;
        if (!editor)
            return;
        editor.setValue(value);
        var autoFormat = this.get('autoFormat');
        var canAutoFormat = editor.autoFormatRange &&
            (autoFormat === true || (Array.isArray(autoFormat) && autoFormat.includes(this.get('codeName'))));
        if (canAutoFormat) {
            CodeMirror.commands.selectAll(editor);
            editor.autoFormatRange(editor.getCursor(true), editor.getCursor(false));
            CodeMirror.commands.goDocStart(editor);
        }
        !opts.noRefresh && setTimeout(function () { return _this.refresh(); });
    };
    return CodeMirrorEditor;
}(common/* Model */.Hn));
/* harmony default export */ const model_CodeMirrorEditor = (CodeMirrorEditor);
// @ts-ignore
CodeMirrorEditor.prototype.CodeMirror = CodeMirror;

;// CONCATENATED MODULE: ./src/code_manager/view/EditorView.ts
var EditorView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var EditorView_makeTemplateObject = (undefined && undefined.__makeTemplateObject) || function (cooked, raw) {
    if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
    return cooked;
};


var CodeEditorView = /** @class */ (function (_super) {
    EditorView_extends(CodeEditorView, _super);
    function CodeEditorView() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    CodeEditorView.prototype.template = function (_a) {
        var pfx = _a.pfx, codeName = _a.codeName, label = _a.label;
        return html(EditorView_templateObject_1 || (EditorView_templateObject_1 = EditorView_makeTemplateObject(["\n      <div class=\"", "editor\" id=\"", "", "\">\n        <div id=\"", "title\">", "</div>\n        <div id=\"", "code\"></div>\n      </div>\n    "], ["\n      <div class=\"", "editor\" id=\"", "", "\">\n        <div id=\"", "title\">", "</div>\n        <div id=\"", "code\"></div>\n      </div>\n    "])), pfx, pfx, codeName, pfx, label, pfx);
    };
    CodeEditorView.prototype.initialize = function (o) {
        this.config = o.config || {};
        this.pfx = this.config.stylePrefix;
    };
    CodeEditorView.prototype.render = function () {
        var _a, _b;
        var _c = this, model = _c.model, pfx = _c.pfx, $el = _c.$el;
        var obj = model.toJSON();
        var toAppend = model.get('input') || ((_b = (_a = model).getElement) === null || _b === void 0 ? void 0 : _b.call(_a));
        obj.pfx = pfx;
        $el.html(this.template(obj));
        $el.attr('class', "".concat(pfx, "editor-c"));
        $el.find("#".concat(pfx, "code")).append(toAppend);
        return this;
    };
    return CodeEditorView;
}(common/* View */.G7));
/* harmony default export */ const EditorView = (CodeEditorView);
var EditorView_templateObject_1;

;// CONCATENATED MODULE: ./src/code_manager/index.ts
var code_manager_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var code_manager_assign = (undefined && undefined.__assign) || function () {
    code_manager_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return code_manager_assign.apply(this, arguments);
};
/**
 * - [addGenerator](#addgenerator)
 * - [getGenerator](#getgenerator)
 * - [getGenerators](#getgenerators)
 * - [addViewer](#addviewer)
 * - [getViewer](#getviewer)
 * - [getViewers](#getviewers)
 * - [updateViewer](#updateviewer)
 * - [getCode](#getcode)
 *
 *
 * Before using methods you should get first the module from the editor instance, in this way:
 *
 * ```js
 * var codeManager = editor.CodeManager;
 * ```
 *
 * @module CodeManager
 */









var defaultViewer = 'CodeMirror';
var CodeManagerModule = /** @class */ (function (_super) {
    code_manager_extends(CodeManagerModule, _super);
    function CodeManagerModule(em) {
        var _this = _super.call(this, em, 'CodeManager', code_manager_config_config) || this;
        _this.EditorView = EditorView;
        var config = _this.config;
        var ppfx = config.pStylePrefix;
        if (ppfx)
            config.stylePrefix = ppfx + config.stylePrefix;
        _this.generators = {};
        _this.viewers = {};
        _this.defGenerators = {
            html: new HtmlGenerator(),
            css: new model_CssGenerator(),
            json: new model_JsonGenerator(),
            js: new model_JsGenerator(),
        };
        _this.defViewers = { CodeMirror: new model_CodeMirrorEditor() };
        _this.loadDefaultGenerators().loadDefaultViewers();
        return _this;
    }
    /**
     * Add new code generator to the collection
     * @param  {string} id Code generator ID
     * @param  {Object} generator Code generator wrapper
     * @param {Function} generator.build Function that builds the code
     * @return {this}
     * @example
     * codeManager.addGenerator('html7',{
     *   build: function(model){
     *    return 'myCode';
     *   }
     * });
     * */
    CodeManagerModule.prototype.addGenerator = function (id, generator) {
        this.generators[id] = generator;
        return this;
    };
    /**
     * Get code generator by id
     * @param  {string} id Code generator ID
     * @return {Object|null}
     * @example
     * var generator = codeManager.getGenerator('html7');
     * generator.build = function(model){
     *   //extend
     * };
     * */
    CodeManagerModule.prototype.getGenerator = function (id) {
        return this.generators[id];
    };
    /**
     * Returns all code generators
     * @return {Array<Object>}
     * */
    CodeManagerModule.prototype.getGenerators = function () {
        return this.generators;
    };
    /**
     * Add new code viewer
     * @param  {string} id Code viewer ID
     * @param  {Object} viewer Code viewer wrapper
     * @param {Function} viewer.init Set element on which viewer will be displayed
     * @param {Function} viewer.setContent Set content to the viewer
     * @return {this}
     * @example
     * codeManager.addViewer('ace',{
     *   init: function(el){
     *     var ace = require('ace-editor');
     *     this.editor  = ace.edit(el.id);
     *   },
     *   setContent: function(code){
     *    this.editor.setValue(code);
     *   }
     * });
     * */
    CodeManagerModule.prototype.addViewer = function (id, viewer) {
        this.viewers[id] = viewer;
        return this;
    };
    /**
     * Get code viewer by id
     * @param  {string} id Code viewer ID
     * @return {Object|null}
     * @example
     * var viewer = codeManager.getViewer('ace');
     * */
    CodeManagerModule.prototype.getViewer = function (id) {
        return this.viewers[id];
    };
    /**
     * Returns all code viewers
     * @return {Array<Object>}
     * */
    CodeManagerModule.prototype.getViewers = function () {
        return this.viewers;
    };
    CodeManagerModule.prototype.createViewer = function (opts) {
        if (opts === void 0) { opts = {}; }
        var type = !(0,index_all.isUndefined)(opts.type) ? opts.type : defaultViewer;
        var viewer = this.getViewer(type) && this.getViewer(type).clone();
        var cont = document.createElement('div');
        var txtarea = document.createElement('textarea');
        cont.appendChild(txtarea);
        viewer.set(code_manager_assign(code_manager_assign({}, this.config.optsCodeViewer), opts));
        viewer.init(txtarea);
        viewer.setElement(cont);
        return viewer;
    };
    /**
     * Update code viewer content
     * @param  {Object} viewer Viewer instance
     * @param  {string} code  Code string
     * @example
     * var AceViewer = codeManager.getViewer('ace');
     * // ...
     * var viewer = AceViewer.init(el);
     * // ...
     * codeManager.updateViewer(AceViewer, 'code');
     * */
    CodeManagerModule.prototype.updateViewer = function (viewer, code) {
        viewer.setContent(code);
    };
    /**
     * Get code from model
     * @param  {Object} model Any kind of model that will be passed to the build method of generator
     * @param  {string} genId Code generator id
     * @param  {Object} [opt] Options
     * @return {string}
     * @example
     * var codeStr = codeManager.getCode(model, 'html');
     * */
    CodeManagerModule.prototype.getCode = function (model, genId, opt) {
        if (opt === void 0) { opt = {}; }
        opt.em = this.em;
        var generator = this.getGenerator(genId);
        return generator ? generator.build(model, opt) : '';
    };
    /**
     * Load default code generators
     * @return {this}
     * @private
     * */
    CodeManagerModule.prototype.loadDefaultGenerators = function () {
        for (var id in this.defGenerators) {
            this.addGenerator(id, this.defGenerators[id]);
        }
        return this;
    };
    /**
     * Load default code viewers
     * @return {this}
     * @private
     * */
    CodeManagerModule.prototype.loadDefaultViewers = function () {
        for (var id in this.defViewers) {
            this.addViewer(id, this.defViewers[id]);
        }
        return this;
    };
    CodeManagerModule.prototype.destroy = function () { };
    return CodeManagerModule;
}(abstract_Module));
/* harmony default export */ const code_manager = (CodeManagerModule);

// EXTERNAL MODULE: ./node_modules/backbone-undo/Backbone.Undo.js
var Backbone_Undo = __webpack_require__(410);
var Backbone_Undo_default = /*#__PURE__*/__webpack_require__.n(Backbone_Undo);
;// CONCATENATED MODULE: ./src/undo_manager/config.ts
var undo_manager_config_config = {
    maximumStackLength: 500,
    trackSelection: true,
};
/* harmony default export */ const undo_manager_config = (undo_manager_config_config);

;// CONCATENATED MODULE: ./src/undo_manager/index.ts
var undo_manager_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var undo_manager_assign = (undefined && undefined.__assign) || function () {
    undo_manager_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return undo_manager_assign.apply(this, arguments);
};
var undo_manager_spreadArray = (undefined && undefined.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
/**
 * This module allows to manage the stack of changes applied in canvas.
 * Once the editor is instantiated you can use its API. Before using these methods you should get the module from the instance
 *
 * ```js
 * const um = editor.UndoManager;
 * ```
 *
 * * [getConfig](#getconfig)
 * * [add](#add)
 * * [remove](#remove)
 * * [removeAll](#removeall)
 * * [start](#start)
 * * [stop](#stop)
 * * [undo](#undo)
 * * [undoAll](#undoall)
 * * [redo](#redo)
 * * [redoAll](#redoall)
 * * [hasUndo](#hasundo)
 * * [hasRedo](#hasredo)
 * * [getStack](#getstack)
 * * [clear](#clear)
 *
 * @module UndoManager
 */
// @ts-ignore




var hasSkip = function (opts) { return opts.avoidStore || opts.noUndo; };
var getChanged = function (obj) { return Object.keys(obj.changedAttributes()); };
var UndoManagerModule = /** @class */ (function (_super) {
    undo_manager_extends(UndoManagerModule, _super);
    function UndoManagerModule(em) {
        var _this = _super.call(this, em, 'UndoManager', undo_manager_config) || this;
        if (_this.config._disable) {
            _this.config.maximumStackLength = 0;
        }
        var fromUndo = true;
        _this.um = new (Backbone_Undo_default())(undo_manager_assign({ track: true, register: [] }, _this.config));
        _this.um.changeUndoType('change', {
            condition: function (object) {
                var hasUndo = object.get('_undo');
                if (hasUndo) {
                    var undoExc_1 = object.get('_undoexc');
                    if ((0,index_all.isArray)(undoExc_1)) {
                        if (getChanged(object).some(function (chn) { return undoExc_1.indexOf(chn) >= 0; }))
                            return false;
                    }
                    if ((0,index_all.isBoolean)(hasUndo))
                        return true;
                    if ((0,index_all.isArray)(hasUndo)) {
                        if (getChanged(object).some(function (chn) { return hasUndo.indexOf(chn) >= 0; }))
                            return true;
                    }
                }
                return false;
            },
            on: function (object, v, opts) {
                var _this = this;
                !this.beforeCache && (this.beforeCache = object.previousAttributes());
                var opt = opts || v || {};
                opt.noUndo &&
                    setTimeout(function () {
                        _this.beforeCache = null;
                    });
                if (hasSkip(opt)) {
                    return;
                }
                else {
                    var after = object.toJSON({ fromUndo: fromUndo });
                    var result = {
                        object: object,
                        before: this.beforeCache,
                        after: after,
                    };
                    this.beforeCache = null;
                    // Skip undo in case of empty changes
                    if ((0,index_all.isEmpty)(after))
                        return;
                    return result;
                }
            },
        });
        _this.um.changeUndoType('add', {
            on: function (model, collection, options) {
                if (options === void 0) { options = {}; }
                if (hasSkip(options) || !_this.isRegistered(collection))
                    return;
                return {
                    object: collection,
                    before: undefined,
                    after: model,
                    options: undo_manager_assign(undo_manager_assign({}, options), { fromUndo: fromUndo }),
                };
            },
        });
        _this.um.changeUndoType('remove', {
            on: function (model, collection, options) {
                if (options === void 0) { options = {}; }
                if (hasSkip(options) || !_this.isRegistered(collection))
                    return;
                return {
                    object: collection,
                    before: model,
                    after: undefined,
                    options: undo_manager_assign(undo_manager_assign({}, options), { fromUndo: fromUndo }),
                };
            },
        });
        _this.um.changeUndoType('reset', {
            undo: function (collection, before) {
                collection.reset(before, { fromUndo: fromUndo });
            },
            redo: function (collection, b, after) {
                collection.reset(after, { fromUndo: fromUndo });
            },
            on: function (collection, options) {
                if (options === void 0) { options = {}; }
                if (hasSkip(options) || !_this.isRegistered(collection))
                    return;
                return {
                    object: collection,
                    before: options.previousModels,
                    after: undo_manager_spreadArray([], collection.models, true),
                    options: undo_manager_assign(undo_manager_assign({}, options), { fromUndo: fromUndo }),
                };
            },
        });
        _this.um.on('undo redo', function () {
            em.getSelectedAll().map(function (c) { return c.trigger('rerender:layer'); });
        });
        ['undo', 'redo'].forEach(function (ev) { return _this.um.on(ev, function () { return em.trigger(ev); }); });
        return _this;
    }
    UndoManagerModule.prototype.postLoad = function () {
        var _a = this, config = _a.config, em = _a.em;
        config.trackSelection && em && this.add(em.get('selected'));
    };
    /**
     * Get configuration object
     * @name getConfig
     * @function
     * @return {Object}
     */
    /**
     * Add an entity (Model/Collection) to track
     * Note: New Components and CSSRules will be added automatically
     * @param {Model|Collection} entity Entity to track
     * @return {this}
     * @example
     * um.add(someModelOrCollection);
     */
    UndoManagerModule.prototype.add = function (entity) {
        this.um.register(entity);
        return this;
    };
    /**
     * Remove and stop tracking the entity (Model/Collection)
     * @param {Model|Collection} entity Entity to remove
     * @return {this}
     * @example
     * um.remove(someModelOrCollection);
     */
    UndoManagerModule.prototype.remove = function (entity) {
        this.um.unregister(entity);
        return this;
    };
    /**
     * Remove all entities
     * @return {this}
     * @example
     * um.removeAll();
     */
    UndoManagerModule.prototype.removeAll = function () {
        this.um.unregisterAll();
        return this;
    };
    /**
     * Start/resume tracking changes
     * @return {this}
     * @example
     * um.start();
     */
    UndoManagerModule.prototype.start = function () {
        this.um.startTracking();
        return this;
    };
    /**
     * Stop tracking changes
     * @return {this}
     * @example
     * um.stop();
     */
    UndoManagerModule.prototype.stop = function () {
        this.um.stopTracking();
        return this;
    };
    /**
     * Undo last change
     * @return {this}
     * @example
     * um.undo();
     */
    UndoManagerModule.prototype.undo = function (all) {
        if (all === void 0) { all = true; }
        var _a = this, em = _a.em, um = _a.um;
        !em.isEditing() && um.undo(all);
        return this;
    };
    /**
     * Undo all changes
     * @return {this}
     * @example
     * um.undoAll();
     */
    UndoManagerModule.prototype.undoAll = function () {
        this.um.undoAll();
        return this;
    };
    /**
     * Redo last change
     * @return {this}
     * @example
     * um.redo();
     */
    UndoManagerModule.prototype.redo = function (all) {
        if (all === void 0) { all = true; }
        var _a = this, em = _a.em, um = _a.um;
        !em.isEditing() && um.redo(all);
        return this;
    };
    /**
     * Redo all changes
     * @return {this}
     * @example
     * um.redoAll();
     */
    UndoManagerModule.prototype.redoAll = function () {
        this.um.redoAll();
        return this;
    };
    /**
     * Checks if exists an available undo
     * @return {Boolean}
     * @example
     * um.hasUndo();
     */
    UndoManagerModule.prototype.hasUndo = function () {
        return !!this.um.isAvailable('undo');
    };
    /**
     * Checks if exists an available redo
     * @return {Boolean}
     * @example
     * um.hasRedo();
     */
    UndoManagerModule.prototype.hasRedo = function () {
        return !!this.um.isAvailable('redo');
    };
    /**
     * Check if the entity (Model/Collection) to tracked
     * Note: New Components and CSSRules will be added automatically
     * @param {Model|Collection} entity Entity to track
     * @returns {Boolean}
     */
    UndoManagerModule.prototype.isRegistered = function (obj) {
        return !!this.getInstance().objectRegistry.isRegistered(obj);
    };
    /**
     * Get stack of changes
     * @return {Collection}
     * @example
     * const stack = um.getStack();
     * stack.each(item => ...);
     */
    UndoManagerModule.prototype.getStack = function () {
        return this.um.stack;
    };
    /**
     * Get grouped undo manager stack.
     * The difference between `getStack` is when you do multiple operations at a time,
     * like appending multiple components:
     * `editor.getWrapper().append('<div>C1</div><div>C2</div>');`
     * `getStack` will return a collection length of 2.
     *  `getStackGroup` instead will group them as a single operation (the first
     * inserted component will be returned in the list) by returning an array length of 1.
     * @return {Array}
     * @private
     */
    UndoManagerModule.prototype.getStackGroup = function () {
        var result = [];
        var inserted = [];
        this.getStack().forEach(function (item) {
            var index = item.get('magicFusionIndex');
            if (inserted.indexOf(index) < 0) {
                inserted.push(index);
                result.push(item);
            }
        });
        return result;
    };
    UndoManagerModule.prototype.skip = function (clb) {
        var isTracking = !!this.um.isTracking();
        isTracking && this.stop();
        clb();
        isTracking && this.start();
    };
    UndoManagerModule.prototype.getGroupedStack = function () {
        var result = {};
        var stack = this.getStack();
        var createItem = function (item, index) {
            var _a = item.attributes, type = _a.type, after = _a.after, before = _a.before, object = _a.object, _b = _a.options, options = _b === void 0 ? {} : _b;
            return { index: index, type: type, after: after, before: before, object: object, options: options };
        };
        stack.forEach(function (item, i) {
            var index = item.get('magicFusionIndex');
            var value = createItem(item, i);
            if (!result[index]) {
                result[index] = [value];
            }
            else {
                result[index].push(value);
            }
        });
        return Object.keys(result).map(function (index) {
            var actions = result[index];
            return {
                index: actions[actions.length - 1].index,
                actions: actions,
                labels: (0,index_all.unique)(actions.reduce(function (res, item) {
                    var _a;
                    var label = (_a = item.options) === null || _a === void 0 ? void 0 : _a.action;
                    label && res.push(label);
                    return res;
                }, [])),
            };
        });
    };
    UndoManagerModule.prototype.goToGroup = function (group) {
        var _this = this;
        if (!group)
            return;
        var current = this.getPointer();
        var goTo = group.index - current;
        (0,index_all.times)(Math.abs(goTo), function () {
            _this[goTo < 0 ? 'undo' : 'redo'](false);
        });
    };
    UndoManagerModule.prototype.getPointer = function () {
        // @ts-ignore
        return this.getStack().pointer;
    };
    /**
     * Clear the stack
     * @return {this}
     * @example
     * um.clear();
     */
    UndoManagerModule.prototype.clear = function () {
        this.um.clear();
        return this;
    };
    UndoManagerModule.prototype.getInstance = function () {
        return this.um;
    };
    UndoManagerModule.prototype.destroy = function () {
        this.clear().removeAll();
    };
    return UndoManagerModule;
}(abstract_Module));
/* harmony default export */ const undo_manager = (UndoManagerModule);

;// CONCATENATED MODULE: ./src/rich_text_editor/config/config.ts
var rich_text_editor_config_config_config = {
    stylePrefix: 'rte-',
    adjustToolbar: true,
    actions: ['bold', 'italic', 'underline', 'strikethrough', 'link', 'wrap'],
    custom: false,
};
/* harmony default export */ const rich_text_editor_config_config = (rich_text_editor_config_config_config);

;// CONCATENATED MODULE: ./src/rich_text_editor/model/RichTextEditor.ts
// The initial version of this RTE was borrowed from https://github.com/jaredreich/pell
// and adapted to the GrapesJS's need
var RichTextEditor_assign = (undefined && undefined.__assign) || function () {
    RichTextEditor_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return RichTextEditor_assign.apply(this, arguments);
};



var RichTextEditorActionState;
(function (RichTextEditorActionState) {
    RichTextEditorActionState[RichTextEditorActionState["ACTIVE"] = 1] = "ACTIVE";
    RichTextEditorActionState[RichTextEditorActionState["INACTIVE"] = 0] = "INACTIVE";
    RichTextEditorActionState[RichTextEditorActionState["DISABLED"] = -1] = "DISABLED";
})(RichTextEditorActionState || (RichTextEditorActionState = {}));
var RTE_KEY = '_rte';
var btnState = {
    ACTIVE: 1,
    INACTIVE: 0,
    DISABLED: -1,
};
var isValidTag = function (rte, tagName) {
    if (tagName === void 0) { tagName = 'A'; }
    var _a = rte.selection() || {}, anchorNode = _a.anchorNode, focusNode = _a.focusNode;
    var parentAnchor = anchorNode === null || anchorNode === void 0 ? void 0 : anchorNode.parentNode;
    var parentFocus = focusNode === null || focusNode === void 0 ? void 0 : focusNode.parentNode;
    return (parentAnchor === null || parentAnchor === void 0 ? void 0 : parentAnchor.nodeName) == tagName || (parentFocus === null || parentFocus === void 0 ? void 0 : parentFocus.nodeName) == tagName;
};
var customElAttr = 'data-selectme';
var defActions = {
    bold: {
        name: 'bold',
        icon: '<b>B</b>',
        attributes: { title: 'Bold' },
        result: function (rte) { return rte.exec('bold'); },
    },
    italic: {
        name: 'italic',
        icon: '<i>I</i>',
        attributes: { title: 'Italic' },
        result: function (rte) { return rte.exec('italic'); },
    },
    underline: {
        name: 'underline',
        icon: '<u>U</u>',
        attributes: { title: 'Underline' },
        result: function (rte) { return rte.exec('underline'); },
    },
    strikethrough: {
        name: 'strikethrough',
        icon: '<s>S</s>',
        attributes: { title: 'Strike-through' },
        result: function (rte) { return rte.exec('strikeThrough'); },
    },
    link: {
        icon: "<svg viewBox=\"0 0 24 24\">\n          <path fill=\"currentColor\" d=\"M3.9,12C3.9,10.29 5.29,8.9 7,8.9H11V7H7A5,5 0 0,0 2,12A5,5 0 0,0 7,17H11V15.1H7C5.29,15.1 3.9,13.71 3.9,12M8,13H16V11H8V13M17,7H13V8.9H17C18.71,8.9 20.1,10.29 20.1,12C20.1,13.71 18.71,15.1 17,15.1H13V17H17A5,5 0 0,0 22,12A5,5 0 0,0 17,7Z\" />\n        </svg>",
        name: 'link',
        attributes: {
            style: 'font-size:1.4rem;padding:0 4px 2px;',
            title: 'Link',
        },
        state: function (rte) {
            return rte && rte.selection() && isValidTag(rte) ? btnState.ACTIVE : btnState.INACTIVE;
        },
        result: function (rte) {
            if (isValidTag(rte)) {
                rte.exec('unlink');
            }
            else {
                rte.insertHTML("<a href=\"\" ".concat(customElAttr, ">").concat(rte.selection(), "</a>"), {
                    select: true,
                });
            }
        },
    },
    wrap: {
        name: 'wrap',
        icon: "<svg viewBox=\"0 0 24 24\">\n            <path fill=\"currentColor\" d=\"M20.71,4.63L19.37,3.29C19,2.9 18.35,2.9 17.96,3.29L9,12.25L11.75,15L20.71,6.04C21.1,5.65 21.1,5 20.71,4.63M7,14A3,3 0 0,0 4,17C4,18.31 2.84,19 2,19C2.92,20.22 4.5,21 6,21A4,4 0 0,0 10,17A3,3 0 0,0 7,14Z\" />\n        </svg>",
        attributes: { title: 'Wrap for style' },
        state: function (rte) {
            return (rte === null || rte === void 0 ? void 0 : rte.selection()) && isValidTag(rte, 'SPAN') ? btnState.DISABLED : btnState.INACTIVE;
        },
        result: function (rte) {
            !isValidTag(rte, 'SPAN') &&
                rte.insertHTML("<span ".concat(customElAttr, ">").concat(rte.selection(), "</span>"), {
                    select: true,
                });
        },
    },
};
var RichTextEditor = /** @class */ (function () {
    function RichTextEditor(em, el, settings) {
        var _this = this;
        if (settings === void 0) { settings = {}; }
        this.em = em;
        this.settings = settings;
        if (el[RTE_KEY]) {
            return el[RTE_KEY];
        }
        el[RTE_KEY] = this;
        this.setEl(el);
        this.updateActiveActions = this.updateActiveActions.bind(this);
        this.__onKeydown = this.__onKeydown.bind(this);
        this.__onPaste = this.__onPaste.bind(this);
        var acts = (settings.actions || []).map(function (action) {
            var result = action;
            if ((0,index_all.isString)(action)) {
                result = RichTextEditor_assign({}, defActions[action]);
            }
            else if (defActions[action.name]) {
                result = RichTextEditor_assign(RichTextEditor_assign({}, defActions[action.name]), action);
            }
            return result;
        });
        var actions = acts.length ? acts : Object.keys(defActions).map(function (a) { return defActions[a]; });
        settings.classes = RichTextEditor_assign({ actionbar: 'actionbar', button: 'action', active: 'active', disabled: 'disabled', inactive: 'inactive' }, settings.classes);
        var classes = settings.classes;
        var actionbar = settings.actionbar;
        this.actionbar = actionbar;
        this.classes = classes;
        this.actions = actions;
        if (!actionbar) {
            if (!this.isCustom(settings.module)) {
                var actionbarCont = settings.actionbarContainer;
                actionbar = document.createElement('div');
                actionbar.className = classes.actionbar;
                actionbarCont === null || actionbarCont === void 0 ? void 0 : actionbarCont.appendChild(actionbar);
                this.actionbar = actionbar;
            }
            actions.forEach(function (action) { return _this.addAction(action); });
        }
        settings.styleWithCSS && this.exec('styleWithCSS');
        return this;
    }
    RichTextEditor.prototype.isCustom = function (module) {
        var rte = module || this.em.RichTextEditor;
        return !!((rte === null || rte === void 0 ? void 0 : rte.config.custom) || (rte === null || rte === void 0 ? void 0 : rte.customRte));
    };
    RichTextEditor.prototype.destroy = function () { };
    RichTextEditor.prototype.setEl = function (el) {
        this.el = el;
        this.doc = el.ownerDocument;
    };
    RichTextEditor.prototype.updateActiveActions = function () {
        var _this = this;
        var actions = this.getActions();
        actions.forEach(function (action) {
            var update = action.update, btn = action.btn;
            var _a = _this.classes, active = _a.active, inactive = _a.inactive, disabled = _a.disabled;
            var state = action.state;
            var name = action.name;
            var doc = _this.doc;
            var currentState = RichTextEditorActionState.INACTIVE;
            if (btn) {
                btn.className = btn.className.replace(active, '').trim();
                btn.className = btn.className.replace(inactive, '').trim();
                btn.className = btn.className.replace(disabled, '').trim();
            }
            // if there is a state function, which depicts the state,
            // i.e. `active`, `disabled`, then call it
            if (state) {
                var newState = state(_this, doc);
                currentState = newState;
                if (btn) {
                    switch (newState) {
                        case btnState.ACTIVE:
                            btn.className += " ".concat(active);
                            break;
                        case btnState.INACTIVE:
                            btn.className += " ".concat(inactive);
                            break;
                        case btnState.DISABLED:
                            btn.className += " ".concat(disabled);
                            break;
                    }
                }
            }
            else {
                // otherwise default to checking if the name command is supported & enabled
                if (doc.queryCommandSupported(name) && doc.queryCommandState(name)) {
                    btn && (btn.className += " ".concat(active));
                    currentState = RichTextEditorActionState.ACTIVE;
                }
            }
            action.currentState = currentState;
            update === null || update === void 0 ? void 0 : update(_this, action);
        });
        actions.length && this.em.RichTextEditor.__dbdTrgCustom();
    };
    RichTextEditor.prototype.enable = function (opts) {
        if (this.enabled)
            return this;
        return this.__toggleEffects(true, opts);
    };
    RichTextEditor.prototype.disable = function () {
        return this.__toggleEffects(false);
    };
    RichTextEditor.prototype.__toggleEffects = function (enable, opts) {
        if (enable === void 0) { enable = false; }
        if (opts === void 0) { opts = {}; }
        var method = enable ? dom.on : dom/* off */.S1;
        var _a = this, el = _a.el, doc = _a.doc;
        var actionbar = this.actionbarEl();
        actionbar && (actionbar.style.display = enable ? '' : 'none');
        el.contentEditable = "".concat(!!enable);
        method(el, 'mouseup keyup', this.updateActiveActions);
        method(doc, 'keydown', this.__onKeydown);
        method(doc, 'paste', this.__onPaste);
        this.enabled = enable;
        if (enable) {
            var event_1 = opts.event;
            this.syncActions();
            this.updateActiveActions();
            if (event_1) {
                var range = null;
                // Still used as caretPositionFromPoint is not yet well adopted
                if (doc.caretRangeFromPoint) {
                    var poiner = (0,dom/* getPointerEvent */.VB)(event_1);
                    range = doc.caretRangeFromPoint(poiner.clientX, poiner.clientY);
                    // @ts-ignore for Firefox
                }
                else if (event_1.rangeParent) {
                    range = doc.createRange();
                    // @ts-ignore
                    range.setStart(event_1.rangeParent, event_1.rangeOffset);
                }
                var sel = doc.getSelection();
                sel === null || sel === void 0 ? void 0 : sel.removeAllRanges();
                range && (sel === null || sel === void 0 ? void 0 : sel.addRange(range));
            }
            el.focus();
        }
        return this;
    };
    RichTextEditor.prototype.__onKeydown = function (ev) {
        var em = this.em;
        var onKeydown = em.RichTextEditor.getConfig().onKeydown;
        if (onKeydown) {
            return onKeydown({ ev: ev, rte: this, editor: em.getEditor() });
        }
        var doc = this.doc;
        var cmdList = ['insertOrderedList', 'insertUnorderedList'];
        if (ev.key === 'Enter' && !cmdList.some(function (cmd) { return doc.queryCommandState(cmd); })) {
            doc.execCommand('insertLineBreak');
            ev.preventDefault();
        }
    };
    RichTextEditor.prototype.__onPaste = function (ev) {
        var em = this.em;
        var onPaste = em.RichTextEditor.getConfig().onPaste;
        if (onPaste) {
            return onPaste({ ev: ev, rte: this, editor: em.getEditor() });
        }
        var clipboardData = ev.clipboardData;
        var text = clipboardData.getData('text');
        var textHtml = clipboardData.getData('text/html');
        // Replace \n with <br> in case of a plain text
        if (text && !textHtml) {
            ev.preventDefault();
            var html = text.replace(/(?:\r\n|\r|\n)/g, '<br/>');
            this.doc.execCommand('insertHTML', false, html);
        }
    };
    /**
     * Sync actions with the current RTE
     */
    RichTextEditor.prototype.syncActions = function () {
        var _this = this;
        this.getActions().forEach(function (action) {
            if (_this.actionbar) {
                if (!action.state || (action.state && action.state(_this, _this.doc) >= 0)) {
                    var event_2 = action.event || 'click';
                    var btn = action.btn;
                    if (btn) {
                        btn["on".concat(event_2)] = function () {
                            action.result(_this, action);
                            _this.updateActiveActions();
                        };
                    }
                }
            }
        });
    };
    /**
     * Add new action to the actionbar
     * @param {Object} action
     * @param {Object} [opts={}]
     */
    RichTextEditor.prototype.addAction = function (action, opts) {
        if (opts === void 0) { opts = {}; }
        var sync = opts.sync;
        var actionbar = this.actionbarEl();
        if (actionbar) {
            var icon = action.icon, _a = action.attributes, attr = _a === void 0 ? {} : _a;
            var btn = document.createElement('span');
            btn.className = this.classes.button;
            action.btn = btn;
            for (var key in attr) {
                btn.setAttribute(key, attr[key]);
            }
            if (typeof icon == 'string') {
                btn.innerHTML = icon;
            }
            else {
                btn.appendChild(icon);
            }
            actionbar.appendChild(btn);
        }
        if (sync) {
            this.actions.push(action);
            this.syncActions();
        }
    };
    /**
     * Get the array of current actions
     * @return {Array}
     */
    RichTextEditor.prototype.getActions = function () {
        return this.actions;
    };
    /**
     * Returns the Selection instance
     * @return {Selection}
     */
    RichTextEditor.prototype.selection = function () {
        return this.doc.getSelection();
    };
    /**
     * Wrapper around [execCommand](https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand) to allow
     * you to perform operations like `insertText`
     * @param  {string} command Command name
     * @param  {any} [value=null Command's arguments
     */
    RichTextEditor.prototype.exec = function (command, value) {
        this.doc.execCommand(command, false, value);
    };
    /**
     * Get the actionbar element
     * @return {HTMLElement}
     */
    RichTextEditor.prototype.actionbarEl = function () {
        return this.actionbar;
    };
    /**
     * Set custom HTML to the selection, useful as the default 'insertHTML' command
     * doesn't work in the same way on all browsers
     * @param  {string} value HTML string
     */
    RichTextEditor.prototype.insertHTML = function (value, _a) {
        var _b = _a === void 0 ? {} : _a, select = _b.select;
        var _c = this, em = _c.em, doc = _c.doc, el = _c.el;
        var sel = doc.getSelection();
        if (sel && sel.rangeCount) {
            var model_1 = (0,mixins.getComponentModel)(el) || em.getSelected();
            var node = doc.createElement('div');
            var range_1 = sel.getRangeAt(0);
            range_1.deleteContents();
            if ((0,index_all.isString)(value)) {
                node.innerHTML = value;
            }
            else if (value) {
                node.appendChild(value);
            }
            Array.prototype.slice.call(node.childNodes).forEach(function (nd) {
                range_1.insertNode(nd);
            });
            sel.removeAllRanges();
            sel.addRange(range_1);
            el.focus();
            if (select && model_1) {
                model_1.once('rte:disable', function () {
                    var toSel = model_1.find("[".concat(customElAttr, "]"))[0];
                    if (!toSel)
                        return;
                    em.setSelected(toSel);
                    toSel.removeAttributes(customElAttr);
                });
                model_1.trigger('disable');
            }
        }
    };
    return RichTextEditor;
}());
/* harmony default export */ const model_RichTextEditor = (RichTextEditor);

;// CONCATENATED MODULE: ./src/rich_text_editor/index.ts
/**
 * This module allows to customize the built-in toolbar of the Rich Text Editor and use commands from the [HTML Editing APIs](https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand).
 * It's highly recommended to keep this toolbar as small as possible, especially from styling commands (eg. 'fontSize') and leave this task to the Style Manager
 *
 * You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](https://github.com/GrapesJS/grapesjs/blob/master/src/rich_text_editor/config/config.ts)
 * ```js
 * const editor = grapesjs.init({
 *  richTextEditor: {
 *    // options
 *  }
 * })
 * ```
 *
 * Once the editor is instantiated you can use its API and listen to its events. Before using these methods, you should get the module from the instance.
 *
 * ```js
 * // Listen to events
 * editor.on('rte:enable', () => { ... });
 *
 * // Use the API
 * const rte = editor.RichTextEditor;
 * rte.add(...);
 * ```
 *
 * ## Available Events
 * * `rte:enable` - RTE enabled. The view, on which RTE is enabled, is passed as an argument
 * * `rte:disable` - RTE disabled. The view, on which RTE is disabled, is passed as an argument
 *
 * ## Methods
 * * [add](#add)
 * * [get](#get)
 * * [run](#run)
 * * [getAll](#getall)
 * * [remove](#remove)
 * * [getToolbarEl](#gettoolbarel)
 *
 * @module RichTextEditor
 */
var rich_text_editor_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var rich_text_editor_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var rich_text_editor_generator = (undefined && undefined.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var rich_text_editor_spreadArray = (undefined && undefined.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};








var eventsUp = "".concat(canvas_types.refresh, " frame:scroll component:update");
var evEnable = 'rte:enable';
var evDisable = 'rte:disable';
var rich_text_editor_evCustom = 'rte:custom';
var rich_text_editor_events = {
    enable: evEnable,
    disable: evDisable,
    custom: rich_text_editor_evCustom,
};
var RichTextEditorModule = /** @class */ (function (_super) {
    rich_text_editor_extends(RichTextEditorModule, _super);
    /**
     * Get configuration object
     * @name getConfig
     * @function
     * @return {Object}
     */
    function RichTextEditorModule(em) {
        var _this = _super.call(this, em, 'RichTextEditor', rich_text_editor_config_config) || this;
        _this.events = rich_text_editor_events;
        var config = _this.config;
        var ppfx = config.pStylePrefix;
        if (ppfx) {
            config.stylePrefix = ppfx + config.stylePrefix;
        }
        _this.pfx = config.stylePrefix;
        _this.actions = config.actions || [];
        var model = new common/* Model */.Hn();
        _this.model = model;
        model.on('change:currentView', _this.__trgCustom, _this);
        _this.__dbdTrgCustom = (0,index_all.debounce)(function () { return _this.__trgCustom(); }, 0);
        return _this;
    }
    RichTextEditorModule.prototype.onLoad = function () {
        if (!(0,mixins.hasWin)())
            return;
        var config = this.config;
        var ppfx = config.pStylePrefix;
        var isCustom = config.custom;
        var toolbar = (0,dom/* createEl */.ut)('div', {
            class: (0,dom.cx)("".concat(ppfx, "rte-toolbar"), !isCustom && "".concat(ppfx, "one-bg ").concat(ppfx, "rte-toolbar-ui")),
        });
        this.toolbar = toolbar;
        this.initRte((0,dom/* createEl */.ut)('div'));
        //Avoid closing on toolbar clicking
        (0,dom.on)(toolbar, 'mousedown', function (e) { return e.stopPropagation(); });
    };
    RichTextEditorModule.prototype.__trgCustom = function () {
        var _a = this, model = _a.model, em = _a.em, events = _a.events;
        em.trigger(events.custom, {
            enabled: !!model.get('currentView'),
            container: this.getToolbarEl(),
            actions: this.getAll(),
        });
    };
    RichTextEditorModule.prototype.destroy = function () {
        var _a, _b, _c;
        (_a = this.globalRte) === null || _a === void 0 ? void 0 : _a.destroy();
        (_c = (_b = this.customRte) === null || _b === void 0 ? void 0 : _b.destroy) === null || _c === void 0 ? void 0 : _c.call(_b);
        this.model.stopListening().clear({ silent: true });
        this.__dbdTrgCustom.cancel();
        (0,dom/* removeEl */.L_)(this.toolbar);
    };
    /**
     * Post render callback
     * @param  {View} ev
     * @private
     */
    RichTextEditorModule.prototype.postRender = function (ev) {
        var canvas = ev.model.get('Canvas');
        this.toolbar.style.pointerEvents = 'all';
        this.hideToolbar();
        canvas.getToolsEl().appendChild(this.toolbar);
    };
    /**
     * Init the built-in RTE
     * @param  {HTMLElement} el
     * @return {RichTextEditor}
     * @private
     */
    RichTextEditorModule.prototype.initRte = function (el) {
        var globalRte = this.globalRte;
        var _a = this, em = _a.em, pfx = _a.pfx, actionbar = _a.actionbar, config = _a.config;
        var actions = this.actions || rich_text_editor_spreadArray([], config.actions, true);
        var classes = {
            actionbar: "".concat(pfx, "actionbar"),
            button: "".concat(pfx, "action"),
            active: "".concat(pfx, "active"),
            inactive: "".concat(pfx, "inactive"),
            disabled: "".concat(pfx, "disabled"),
        };
        if (!globalRte) {
            globalRte = new model_RichTextEditor(em, el, {
                classes: classes,
                actions: actions,
                actionbar: actionbar,
                actionbarContainer: this.toolbar,
                module: this,
            });
            this.globalRte = globalRte;
        }
        else {
            globalRte.em = em;
            globalRte.setEl(el);
        }
        if (globalRte.actionbar) {
            this.actionbar = globalRte.actionbar;
        }
        if (globalRte.actions) {
            this.actions = globalRte.actions;
        }
        return globalRte;
    };
    /**
     * Add a new action to the built-in RTE toolbar
     * @param {string} name Action name
     * @param {Object} action Action options
     * @example
     * rte.add('bold', {
     *   icon: '<b>B</b>',
     *   attributes: {title: 'Bold'},
     *   result: rte => rte.exec('bold')
     * });
     * rte.add('link', {
     *   icon: document.getElementById('t'),
     *   attributes: { title: 'Link' },
     *   // Example on how to wrap selected content
     *   result: rte => rte.insertHTML(`<a href="#">${rte.selection()}</a>`)
     * });
     * // An example with fontSize
     * rte.add('fontSize', {
     *   icon: `<select class="gjs-field">
     *         <option>1</option>
     *         <option>4</option>
     *         <option>7</option>
     *       </select>`,
     *     // Bind the 'result' on 'change' listener
     *   event: 'change',
     *   result: (rte, action) => rte.exec('fontSize', action.btn.firstChild.value),
     *   // Callback on any input change (mousedown, keydown, etc..)
     *   update: (rte, action) => {
     *     const value = rte.doc.queryCommandValue(action.name);
     *     if (value != 'false') { // value is a string
     *       action.btn.firstChild.value = value;
     *     }
     *    }
     *   })
     * // An example with state
     * const isValidAnchor = (rte) => {
     *   // a utility function to help determine if the selected is a valid anchor node
     *   const anchor = rte.selection().anchorNode;
     *   const parentNode  = anchor && anchor.parentNode;
     *   const nextSibling = anchor && anchor.nextSibling;
     *   return (parentNode && parentNode.nodeName == 'A') || (nextSibling && nextSibling.nodeName == 'A')
     * }
     * rte.add('toggleAnchor', {
     *   icon: `<span style="transform:rotate(45deg)">&supdsub;</span>`,
     *   state: (rte, doc) => {
     *    if (rte && rte.selection()) {
     *      // `btnState` is a integer, -1 for disabled, 0 for inactive, 1 for active
     *      return isValidAnchor(rte) ? btnState.ACTIVE : btnState.INACTIVE;
     *    } else {
     *      return btnState.INACTIVE;
     *    }
     *   },
     *   result: (rte, action) => {
     *     if (isValidAnchor(rte)) {
     *       rte.exec('unlink');
     *     } else {
     *       rte.insertHTML(`<a class="link" href="">${rte.selection()}</a>`);
     *     }
     *   }
     * })
     */
    RichTextEditorModule.prototype.add = function (name, action) {
        var _a;
        if (action === void 0) { action = {}; }
        action.name = name;
        (_a = this.globalRte) === null || _a === void 0 ? void 0 : _a.addAction(action, { sync: true });
    };
    /**
     * Get the action by its name
     * @param {string} name Action name
     * @return {Object}
     * @example
     * const action = rte.get('bold');
     * // {name: 'bold', ...}
     */
    RichTextEditorModule.prototype.get = function (name) {
        var _a;
        var result;
        (_a = this.globalRte) === null || _a === void 0 ? void 0 : _a.getActions().forEach(function (action) {
            if (action.name == name) {
                result = action;
            }
        });
        return result;
    };
    /**
     * Get all actions
     * @return {Array}
     */
    RichTextEditorModule.prototype.getAll = function () {
        var _a;
        return ((_a = this.globalRte) === null || _a === void 0 ? void 0 : _a.getActions()) || [];
    };
    /**
     * Remove the action from the toolbar
     * @param  {string} name
     * @return {Object} Removed action
     * @example
     * const action = rte.remove('bold');
     * // {name: 'bold', ...}
     */
    RichTextEditorModule.prototype.remove = function (name) {
        var _a;
        var actions = this.getAll();
        var action = this.get(name);
        if (action) {
            var btn = action.btn;
            var index = actions.indexOf(action);
            (_a = btn === null || btn === void 0 ? void 0 : btn.parentNode) === null || _a === void 0 ? void 0 : _a.removeChild(btn);
            actions.splice(index, 1);
        }
        return action;
    };
    /**
     * Run action command.
     * @param action Action to run
     * @example
     * const action = rte.get('bold');
     * rte.run(action) // or rte.run('bold')
     */
    RichTextEditorModule.prototype.run = function (action) {
        var rte = this.globalRte;
        var actionRes = (0,index_all.isString)(action) ? this.get(action) : action;
        if (rte && actionRes) {
            actionRes.result(rte, actionRes);
            rte.updateActiveActions();
        }
    };
    /**
     * Get the toolbar element
     * @return {HTMLElement}
     */
    RichTextEditorModule.prototype.getToolbarEl = function () {
        return this.toolbar;
    };
    /**
     * Triggered when the offset of the editor is changed
     * @private
     */
    RichTextEditorModule.prototype.updatePosition = function () {
        var _a = this, em = _a.em, toolbar = _a.toolbar;
        var un = 'px';
        var canvas = em.Canvas;
        var style = toolbar.style;
        var pos = canvas.getTargetToElementFixed(this.lastEl, toolbar, {
            event: 'rteToolbarPosUpdate',
            left: 0,
        });
        ['top', 'left', 'bottom', 'right'].forEach(function (key) {
            var value = pos[key];
            if ((0,mixins.isDef)(value)) {
                style[key] = (0,index_all.isString)(value) ? value : (value || 0) + un;
            }
        });
    };
    /**
     * Enable rich text editor on the element
     * @param {View} view Component view
     * @param {Object} rte The instance of already defined RTE
     * @private
     * */
    RichTextEditorModule.prototype.enable = function (view, rte, opts) {
        if (opts === void 0) { opts = {}; }
        return rich_text_editor_awaiter(this, void 0, void 0, function () {
            var _a, customRte, em, el, rteInst;
            return rich_text_editor_generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        this.lastEl = view.el;
                        _a = this, customRte = _a.customRte, em = _a.em;
                        el = view.getChildrenContainer();
                        this.toolbar.style.display = '';
                        return [4 /*yield*/, (customRte ? customRte.enable(el, rte) : this.initRte(el).enable(opts))];
                    case 1:
                        rteInst = _b.sent();
                        if (em) {
                            setTimeout(this.updatePosition.bind(this), 0);
                            em.off(eventsUp, this.updatePosition, this);
                            em.on(eventsUp, this.updatePosition, this);
                            em.trigger('rte:enable', view, rteInst);
                        }
                        this.model.set({ currentView: view });
                        return [2 /*return*/, rteInst];
                }
            });
        });
    };
    RichTextEditorModule.prototype.getContent = function (view, rte) {
        return rich_text_editor_awaiter(this, void 0, void 0, function () {
            var customRte;
            return rich_text_editor_generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        customRte = this.customRte;
                        if (!(customRte && rte && (0,index_all.isFunction)(customRte.getContent))) return [3 /*break*/, 2];
                        return [4 /*yield*/, customRte.getContent(view.el, rte)];
                    case 1: return [2 /*return*/, _a.sent()];
                    case 2: return [2 /*return*/, view.getChildrenContainer().innerHTML];
                }
            });
        });
    };
    RichTextEditorModule.prototype.hideToolbar = function () {
        var style = this.toolbar.style;
        var size = '-1000px';
        style.top = size;
        style.left = size;
        style.display = 'none';
    };
    /**
     * Unbind rich text editor from the element
     * @param {View} view
     * @param {Object} rte The instance of already defined RTE
     * @private
     * */
    RichTextEditorModule.prototype.disable = function (view, rte, opts) {
        if (opts === void 0) { opts = {}; }
        var em = this.em;
        var customRte = this.customRte;
        // @ts-ignore
        var el = view.getChildrenContainer();
        if (customRte) {
            customRte.disable(el, rte);
        }
        else {
            rte && rte.disable();
        }
        this.hideToolbar();
        if (em) {
            em.off(eventsUp, this.updatePosition, this);
            !opts.fromMove && em.trigger('rte:disable', view, rte);
        }
        this.model.unset('currentView');
    };
    return RichTextEditorModule;
}(abstract_Module));
/* harmony default export */ const rich_text_editor = (RichTextEditorModule);

;// CONCATENATED MODULE: ./src/style_manager/config/config.ts
/* harmony default export */ const style_manager_config_config = ({
    sectors: [
        {
            name: 'General',
            open: false,
            properties: ['display', 'float', 'position', 'top', 'right', 'left', 'bottom'],
        },
        {
            name: 'Flex',
            open: false,
            properties: [
                'flex-direction',
                'flex-wrap',
                'justify-content',
                'align-items',
                'align-content',
                'order',
                'flex-basis',
                'flex-grow',
                'flex-shrink',
                'align-self',
            ],
        },
        {
            name: 'Dimension',
            open: false,
            properties: ['width', 'height', 'max-width', 'min-height', 'margin', 'padding'],
        },
        {
            name: 'Typography',
            open: false,
            properties: [
                'font-family',
                'font-size',
                'font-weight',
                'letter-spacing',
                'color',
                'line-height',
                'text-align',
                'text-shadow',
            ],
        },
        {
            name: 'Decorations',
            open: false,
            properties: ['background-color', 'border-radius', 'border', 'box-shadow', 'background'],
        },
        {
            name: 'Extra',
            open: false,
            properties: ['opacity', 'transition', 'transform'],
        },
    ],
    appendTo: '',
    stylePrefix: 'sm-',
    custom: false,
    hideNotStylable: true,
    highlightChanged: true,
    highlightComputed: true,
    showComputed: true,
    clearProperties: true,
    avoidComputed: ['width', 'height'],
});

;// CONCATENATED MODULE: ./src/style_manager/model/Property.ts
var Property_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var Property_assign = (undefined && undefined.__assign) || function () {
    Property_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return Property_assign.apply(this, arguments);
};
var Property_rest = (undefined && undefined.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
var Property_spreadArray = (undefined && undefined.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};



/**
 * @typedef Property
 * @property {String} id Property id, eg. `my-property-id`.
 * @property {String} property Related CSS property name, eg. `text-align`.
 * @property {String} default Defaul value of the property.
 * @property {String} label Label to use in UI, eg. `Text Align`.
 * @property {Function} [onChange] Change callback.
 * \n
 * ```js
 *  onChange: ({ property, from, to }) => {
 *    console.log(`Changed property`, property.getName(), { from, to });
 *  }
 * ```
 *
 */
var Property = /** @class */ (function (_super) {
    Property_extends(Property, _super);
    function Property() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Property.getDefaults = function () {
        return (0,index_all.result)(this.prototype, 'defaults');
    };
    /**
     * @private
     * @ts-ignore */
    Property.prototype.defaults = function () {
        return {
            name: '',
            property: '',
            type: '',
            defaults: '',
            info: '',
            value: '',
            icon: '',
            functionName: '',
            status: '',
            visible: true,
            fixedValues: ['initial', 'inherit'],
            full: false,
            important: false,
            toRequire: false,
            requires: undefined,
            requiresParent: null,
            parentTarget: null,
        };
    };
    Property.prototype.initialize = function (props, opts) {
        if (props === void 0) { props = {}; }
        if (opts === void 0) { opts = {}; }
        this.em = opts.em;
        var id = this.getId() || '';
        var name = this.get('name') || this.get('label') || '';
        // @ts-ignore
        !this.get('property') && this.set('property', (name || id).replace(/ /g, '-'));
        var prop = this.get('property');
        !this.get('id') && this.set('id', prop);
        // @ts-ignore
        !name && this.set('name', (0,mixins.capitalize)(prop).replace(/-/g, ' '));
        this.on('change', this.__upTargets);
        // @ts-ignore
        Property.callInit(this, props, opts);
    };
    Property.prototype.__getParentProp = function () {
        var _a, _b;
        // @ts-ignore
        return (_b = (_a = this.collection) === null || _a === void 0 ? void 0 : _a.opts) === null || _b === void 0 ? void 0 : _b.parentProp;
    };
    Property.prototype.__upTargets = function (p, opts) {
        var _a;
        var _this = this;
        if (opts === void 0) { opts = {}; }
        var em = this.em;
        var sm = em.Styles;
        var name = this.getName();
        var isClear = opts.__clear;
        var value = isClear ? '' : this.__getFullValue(opts);
        var parentProp = this.__getParentProp();
        var to = this.changedAttributes();
        var from = (0,index_all.keys)(to).reduce(function (a, i) {
            a[i] = _this.previous(i);
            return a;
        }, {});
        var kProps = Property_spreadArray(Property_spreadArray([], (0,index_all.keys)(this.__getClearProps()), true), ['__p'], false);
        var toProps = (0,index_all.keys)(to);
        var applyStyle = !opts.__up && !parentProp && (isClear || kProps.some(function (k) { return toProps.indexOf(k) >= 0; }));
        var onChange = this.get('onChange');
        var evOpts = { property: this, from: from, to: to, value: value, opts: opts };
        sm.__trgEv(sm.events.propertyUpdate, evOpts);
        onChange && onChange(evOpts);
        applyStyle && this.__upTargetsStyle((_a = {}, _a[name] = value, _a), opts);
    };
    Property.prototype.__upTargetsStyle = function (style, opts) {
        var _a;
        var sm = (_a = this.em) === null || _a === void 0 ? void 0 : _a.get('StyleManager');
        sm === null || sm === void 0 ? void 0 : sm.addStyleTargets(Property_assign(Property_assign({}, style), { __p: !!opts.avoidStore }), opts);
    };
    Property.prototype._up = function (props, opts) {
        if (opts === void 0) { opts = {}; }
        if (opts.noTarget)
            opts.__up = true;
        var partial = opts.partial, rest = Property_rest(opts, ["partial"]);
        // @ts-ignore
        props.__p = !!(rest.avoidStore || partial);
        return this.set(props, Property_assign(Property_assign({}, rest), { avoidStore: props.__p }));
    };
    Property.prototype.up = function (props, opts) {
        if (opts === void 0) { opts = {}; }
        // @ts-ignore
        this.set(props, Property_assign(Property_assign({}, opts), { __up: true }));
    };
    Property.prototype.init = function () { };
    /**
     * Get property id.
     * @returns {String}
     */
    Property.prototype.getId = function () {
        return this.get('id');
    };
    /**
     * Get the property type.
     * The type of the property is defined on property creation and based on its value the proper Property class is assigned.
     * The default type is `base`.
     * @returns {String}
     */
    Property.prototype.getType = function () {
        return this.get('type');
    };
    /**
     * Get name (the CSS property name).
     * @returns {String}
     */
    Property.prototype.getName = function () {
        return this.get('property');
    };
    /**
     * Get property label.
     * @param {Object} [opts={}] Options
     * @param {Boolean} [opts.locale=true] Use the locale string from i18n module
     * @returns {String}
     */
    Property.prototype.getLabel = function (opts) {
        var _a;
        if (opts === void 0) { opts = {}; }
        var _b = opts.locale, locale = _b === void 0 ? true : _b;
        var id = this.getId();
        var name = this.get('name') || this.get('label');
        return (locale && ((_a = this.em) === null || _a === void 0 ? void 0 : _a.t("styleManager.properties.".concat(id)))) || name;
    };
    /**
     * Get property value.
     * @param {Object} [opts={}] Options
     * @param {Boolean} [opts.noDefault=false] Avoid returning the default value
     * @returns {String}
     */
    Property.prototype.getValue = function (opts) {
        if (opts === void 0) { opts = {}; }
        var noDefault = opts.noDefault;
        var val = this.get('value');
        return !this.hasValue() && !noDefault ? this.getDefaultValue() : val;
    };
    /**
     * Check if the property has value.
     * @param {Object} [opts={}] Options
     * @param {Boolean} [opts.noParent=false] Ignore the value if it comes from the parent target.
     * @returns {Boolean}
     */
    Property.prototype.hasValue = function (opts) {
        if (opts === void 0) { opts = {}; }
        var noParent = opts.noParent;
        var parentValue = noParent && this.getParentTarget();
        var val = this.get('value');
        return !(0,index_all.isUndefined)(val) && val !== '' && !parentValue;
    };
    /**
     * Indicates if the current value is coming from a parent target (eg. another CSSRule).
     * @returns {Boolean}
     */
    Property.prototype.hasValueParent = function () {
        return this.hasValue() && !this.hasValue({ noParent: true });
    };
    /**
     * Get the CSS style object of the property.
     * @param {Object} [opts={}] Options
     * @param {Boolean} [opts.camelCase] Return property name in camelCase.
     * @return {Object}
     * @example
     * // In case the property is `color` with a value of `red`.
     * console.log(property.getStyle());
     * // { color: 'red' };
     */
    Property.prototype.getStyle = function (opts) {
        var _a;
        if (opts === void 0) { opts = {}; }
        var name = this.getName();
        var key = opts.camelCase ? (0,mixins.camelCase)(name) : name;
        return _a = {}, _a[key] = this.__getFullValue(opts), _a;
    };
    /**
     * Get the default value.
     * @return {string}
     */
    Property.prototype.getDefaultValue = function () {
        var def = this.get('default');
        return "".concat(!(0,index_all.isUndefined)(def) ? def : this.get('defaults'));
    };
    /**
     * Update the value.
     * The change is also propagated to the selected targets (eg. CSS rule).
     * @param {String} value New value
     * @param {Object} [opts={}] Options
     * @param {Boolean} [opts.partial=false] If `true` the update on targets won't be considered complete (not stored in UndoManager)
     * @param {Boolean} [opts.noTarget=false] If `true` the change won't be propagated to selected targets.
     */
    Property.prototype.upValue = function (value, opts) {
        if (opts === void 0) { opts = {}; }
        var parsed = value === null || value === '' ? this.__getClearProps() : this.__parseValue(value, opts);
        return this._up(parsed, opts);
    };
    /**
     * Check if the property is visible
     * @returns {Boolean}
     */
    Property.prototype.isVisible = function () {
        return !!this.get('visible');
    };
    /**
     * Clear the value.
     * The change is also propagated to the selected targets (eg. the css property is cleared).
     * @param {Object} [opts={}] Options
     * @param {Boolean} [opts.noTarget=false] If `true` the change won't be propagated to selected targets.
     */
    Property.prototype.clear = function (opts) {
        if (opts === void 0) { opts = {}; }
        this._up(this.__getClearProps(), Property_assign(Property_assign({}, opts), { __clear: true }));
        return this;
    };
    /**
     * Indicates if the current value comes directly from the selected target and so can be cleared.
     * @returns {Boolean}
     */
    Property.prototype.canClear = function () {
        var parent = this.getParent();
        return parent ? parent.__canClearProp(this) : this.hasValue({ noParent: true });
    };
    /**
     * If the current property is a sub-property, this will return the parent Property.
     * @returns {[Property]|null}
     */
    Property.prototype.getParent = function () {
        return this.__getParentProp();
    };
    /**
     * Indicates if the property is full-width in UI.
     * @returns {Boolean}
     */
    Property.prototype.isFull = function () {
        return !!this.get('full');
    };
    Property.prototype.__parseValue = function (value, opts) {
        return this.parseValue(value, opts);
    };
    Property.prototype.__getClearProps = function () {
        return { value: '' };
    };
    /**
     * Update value
     * @param {any} value
     * @param {Boolen} [complete=true] Indicates if it's a final state
     * @param {Object} [opts={}] Options
     * @private
     */
    Property.prototype.setValue = function (value, complete, opts) {
        if (complete === void 0) { complete = true; }
        if (opts === void 0) { opts = {}; }
        var parsed = this.parseValue(value);
        var avoidStore = !complete;
        // @ts-ignore
        !avoidStore && this.set({ value: undefined }, { avoidStore: avoidStore, silent: true });
        this.set(parsed, Property_assign({ avoidStore: avoidStore }, opts));
    };
    /**
     * Like `setValue` but, in addition, prevents the update of the input element
     * as the changes should come from the input itself.
     * This method is useful with the definition of custom properties
     * @param {any} value
     * @param {Boolen} [complete=true] Indicates if it's a final state
     * @param {Object} [opts={}] Options
     * @private
     * @deprecated
     */
    Property.prototype.setValueFromInput = function (value, complete, opts) {
        if (opts === void 0) { opts = {}; }
        this.setValue(value, complete, Property_assign(Property_assign({}, opts), { fromInput: 1 }));
    };
    /**
     * Parse a raw value, generally fetched from the target, for this property
     * @param  {string} value Raw value string
     * @return {Object}
     * @private
     * @example
     * // example with an Input type
     * prop.parseValue('translateX(10deg)');
     * // -> { value: 10, unit: 'deg', functionName: 'translateX' }
     *
     */
    Property.prototype.parseValue = function (value, opts) {
        if (opts === void 0) { opts = {}; }
        var result = { value: value };
        var imp = '!important';
        var fn = this.get('functionName') || '';
        if ((0,index_all.isString)(value) && value.indexOf(imp) !== -1) {
            result.value = value.replace(imp, '').trim();
            result.important = true;
        }
        if (!fn && !opts.complete) {
            return result;
        }
        var args = [];
        var valueStr = "".concat(result.value).trim();
        var start = valueStr.indexOf('(') + 1;
        var functionName = fn || valueStr.substring(0, start - 1);
        if (functionName) {
            result.functionName = functionName;
        }
        if (!fn || valueStr.indexOf("".concat(fn, "(")) === 0) {
            var end = valueStr.lastIndexOf(')');
            args.push(start);
            // Will try even if the last closing parentheses is not found
            end >= 0 && args.push(end);
            result.value = String.prototype.substring.apply(valueStr, args);
        }
        if (opts.numeric) {
            var num = parseFloat(result.value);
            result.unit = result.value.replace(num, '');
            result.value = num;
        }
        return result;
    };
    /**
     * Helper function to safely split a string of values.
     * Useful when style values are inside functions
     * eg:
     * -> input: 'value(1,2,4), 123, value(4,5)' -- default separator: ','
     * -> output: ['value(1,2,4)', '123', 'value(4,5)']
     * @param {String} values Values to split
     * @param {String} [separator] Separator
     * @private
     */
    // splitValues(values, separator = ',') {
    //   const res = [];
    //   const op = '(';
    //   const cl = ')';
    //   let curr = '';
    //   let acc = 0;
    //   (values || '').split('').forEach(str => {
    //     if (str == op) {
    //       acc++;
    //       curr = curr + op;
    //     } else if (str == cl && acc > 0) {
    //       acc--;
    //       curr = curr + cl;
    //     } else if (str === separator && acc == 0) {
    //       res.push(curr);
    //       curr = '';
    //     } else {
    //       curr = curr + str;
    //     }
    //   });
    //   curr !== '' && res.push(curr);
    //   return res.map(i => i.trim());
    // }
    Property.prototype.__getFullValue = function (_a) {
        var _b = _a === void 0 ? {} : _a, withDefault = _b.withDefault;
        return !this.hasValue() && withDefault ? this.getDefaultValue() : this.getFullValue();
    };
    /**
     * Get a complete value of the property.
     * This probably will replace the getValue when all
     * properties models will be splitted
     * @param {String} val Custom value to replace the one on the model
     * @return {string}
     * @private
     */
    Property.prototype.getFullValue = function (val, opts) {
        if (opts === void 0) { opts = {}; }
        var fn = this.get('functionName');
        var def = this.getDefaultValue();
        var value = (0,index_all.isUndefined)(val) ? this.get('value') : val;
        var hasValue = !(0,index_all.isUndefined)(value) && value !== '';
        if (value && def && value === def) {
            return def;
        }
        if (fn && hasValue) {
            var fnParameter = fn === 'url' ? "'".concat(value.replace(/'|"/g, ''), "'") : value;
            value = "".concat(fn, "(").concat(fnParameter, ")");
        }
        if (hasValue && this.get('important') && !opts.skipImportant) {
            value = "".concat(value, " !important");
        }
        return value || '';
    };
    Property.prototype.__setParentTarget = function (parentTarget) {
        this.up({ parentTarget: parentTarget });
    };
    Property.prototype.getParentTarget = function () {
        return this.get('parentTarget') || null;
    };
    Property.prototype.__parseFn = function (input) {
        if (input === void 0) { input = ''; }
        var start = input.indexOf('(') + 1;
        var end = input.lastIndexOf(')');
        return {
            name: input.substring(0, start - 1).trim(),
            value: String.prototype.substring.apply(input, [start, end >= 0 ? end : undefined]).trim(),
        };
    };
    Property.prototype.__checkVisibility = function (_a) {
        var target = _a.target, component = _a.component, sectors = _a.sectors;
        var trg = component || target;
        if (!trg)
            return false;
        var id = this.getId();
        var property = this.getName();
        var toRequire = this.get('toRequire');
        var requires = this.get('requires');
        var requiresParent = this.get('requiresParent');
        var unstylable = trg.get('unstylable');
        var stylableReq = trg.get('stylable-require');
        var stylable = trg.get('stylable');
        // Stylable could also be an array indicating with which property
        // the target could be styled
        if ((0,index_all.isArray)(stylable)) {
            stylable = stylable.indexOf(property) >= 0;
        }
        // Check if the property was signed as unstylable
        if ((0,index_all.isArray)(unstylable)) {
            stylable = unstylable.indexOf(property) < 0;
        }
        // Check if the property is available only if requested
        if (toRequire) {
            stylable = !target || (stylableReq && (stylableReq.indexOf(id) >= 0 || stylableReq.indexOf(property) >= 0));
        }
        // Check if the property is available based on other property's values
        if (sectors && requires) {
            var properties_1 = (0,index_all.keys)(requires);
            sectors.forEach(function (sector) {
                sector.getProperties().forEach(function (model) {
                    if ((0,index_all.includes)(properties_1, model.id)) {
                        var values = requires[model.id];
                        stylable = stylable && (0,index_all.includes)(values, model.get('value'));
                    }
                });
            });
        }
        // Check if the property is available based on parent's property values
        if (requiresParent) {
            var parent_1 = component && component.parent();
            var parentEl = parent_1 && parent_1.getEl();
            if (parentEl) {
                var styles_1 = (0,mixins.hasWin)() ? window.getComputedStyle(parentEl) : {};
                (0,index_all.each)(requiresParent, function (values, property) {
                    stylable = stylable && styles_1[property] && (0,index_all.includes)(values, styles_1[property]);
                });
            }
            else {
                stylable = false;
            }
        }
        return !!stylable;
    };
    return Property;
}(common/* Model */.Hn));
/* harmony default export */ const model_Property = (Property);
// @ts-ignore
Property.callParentInit = function (property, ctx, props, opts) {
    if (opts === void 0) { opts = {}; }
    property.prototype.initialize.apply(ctx, [
        props,
        Property_assign(Property_assign({}, opts), { skipInit: 1 }),
    ]);
};
// @ts-ignore
Property.callInit = function (context, props, opts) {
    if (opts === void 0) { opts = {}; }
    !opts.skipInit && context.init(props, opts);
};

;// CONCATENATED MODULE: ./src/style_manager/model/Layer.ts
var Layer_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var Layer_assign = (undefined && undefined.__assign) || function () {
    Layer_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return Layer_assign.apply(this, arguments);
};


var Layer = /** @class */ (function (_super) {
    Layer_extends(Layer, _super);
    function Layer() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Layer.prototype.defaults = function () {
        return {
            values: {},
        };
    };
    Layer.prototype.initialize = function () {
        var cl = this.collection;
        // @ts-ignore
        this.prop = cl === null || cl === void 0 ? void 0 : cl.prop;
    };
    /**
     * Get layer id.
     * @returns {String}
     */
    Layer.prototype.getId = function () {
        return this.cid;
    };
    /**
     * Get layer index.
     * @returns {Number}
     */
    Layer.prototype.getIndex = function () {
        var coll = this.collection;
        return coll ? coll.indexOf(this) : -1;
    };
    /**
     * Get layer values.
     * @param {Object} [opts={}] Options
     * @param {Boolean} [opts.camelCase] Return property names in camelCase.
     * @returns {Object}
     */
    Layer.prototype.getValues = function (opts) {
        if (opts === void 0) { opts = {}; }
        var values = this.get('values');
        return opts.camelCase
            ? Object.keys(values).reduce(function (res, key) {
                res[(0,mixins.camelCase)(key)] = values[key];
                return res;
            }, {})
            : values;
    };
    /**
     * Get layer label.
     * @returns {String}
     */
    Layer.prototype.getLabel = function () {
        var _a;
        return (_a = this.prop) === null || _a === void 0 ? void 0 : _a.getLayerLabel(this);
    };
    /**
     * Check if the layer is selected.
     * @returns {Boolean}
     */
    Layer.prototype.isSelected = function () {
        var _a;
        return ((_a = this.prop) === null || _a === void 0 ? void 0 : _a.getSelectedLayer()) === this;
    };
    /**
     * Select the layer.
     */
    Layer.prototype.select = function () {
        var _a;
        return (_a = this.prop) === null || _a === void 0 ? void 0 : _a.selectLayer(this);
    };
    /**
     * Remove the layer.
     */
    Layer.prototype.remove = function () {
        var _a;
        return (_a = this.prop) === null || _a === void 0 ? void 0 : _a.removeLayer(this);
    };
    /**
     * Move layer to a new index.
     * @param {Number} index New index
     */
    Layer.prototype.move = function (index) {
        var _a;
        return (_a = this.prop) === null || _a === void 0 ? void 0 : _a.moveLayer(this, index);
    };
    /**
     * Get style object for the preview.
     * @param {Object} [opts={}] Options. Same of `PropertyStack.getStyleFromLayer`
     * @returns {Object} Style object
     */
    Layer.prototype.getStylePreview = function (opts) {
        var _a;
        if (opts === void 0) { opts = {}; }
        return (_a = this.prop) === null || _a === void 0 ? void 0 : _a.getStylePreview(this, opts);
    };
    /**
     * Check if the property has the preview enabled for this layer.
     * @returns {Boolean}
     */
    Layer.prototype.hasPreview = function () {
        var _a;
        return !!((_a = this.prop) === null || _a === void 0 ? void 0 : _a.get('preview'));
    };
    Layer.prototype.upValues = function (props) {
        if (props === void 0) { props = {}; }
        return this.set('values', Layer_assign(Layer_assign({}, this.getValues()), props));
    };
    return Layer;
}(common/* Model */.Hn));
/* harmony default export */ const model_Layer = (Layer);

;// CONCATENATED MODULE: ./src/style_manager/model/Layers.ts
var Layers_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();


var Layers = /** @class */ (function (_super) {
    Layers_extends(Layers, _super);
    function Layers() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Layers.prototype.initialize = function (p, opts) {
        if (opts === void 0) { opts = {}; }
        this.prop = opts.prop;
    };
    return Layers;
}(common/* Collection */.FE));
/* harmony default export */ const model_Layers = (Layers);
Layers.prototype.model = model_Layer;

;// CONCATENATED MODULE: ./src/style_manager/model/PropertyComposite.ts
var PropertyComposite_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var PropertyComposite_assign = (undefined && undefined.__assign) || function () {
    PropertyComposite_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return PropertyComposite_assign.apply(this, arguments);
};
var PropertyComposite_spreadArray = (undefined && undefined.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};





var isNumberType = function (type) { return type === 'integer' || type === 'number'; };
/**
 *
 * [Property]: property.html
 *
 *
 * @typedef PropertyComposite
 * @property {Array<Object>} properties Array of sub properties, eg. `[{ type: 'number', property: 'margin-top' }, ...]`
 * @property {Boolean} [detached=false] Indicate if the final CSS property is splitted (detached: `margin-top: X; margin-right: Y; ...`) or combined (not detached: `margin: X Y ...;`)
 * @property {String|RegExp} [separator=' '] Value used to split property values, default `" "`.
 * @property {String} [join=' '] Value used to join property values, default `" "`.
 * @property {Function} [fromStyle] Custom logic for getting property values from the target style object.
 * \n
 * ```js
 *  fromStyle: (style) => {
 *    const margins = parseMarginShorthand(style.margin);
 *    return {
 *      'margin-top': margins.top,
 *      // ...
 *    };
 *  }
 * ```
 * @property {Function} [toStyle] Custom logic for creating the CSS style object to apply on selected targets.
 * \n
 * ```js
 *  toStyle: (values) => {
 *    const top = values['margin-top'] || 0;
 *    const right = values['margin-right'] || 0;
 *    // ...
 *    return {
 *      margin: `${top} ${right} ...`,
 *    };
 *  }
 * ```
 */
var PropertyComposite = /** @class */ (function (_super) {
    PropertyComposite_extends(PropertyComposite, _super);
    function PropertyComposite() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    PropertyComposite.prototype.defaults = function () {
        return PropertyComposite_assign(PropertyComposite_assign({}, model_Property.getDefaults()), { detached: false, properties: [], separator: ' ', join: null, fromStyle: null, toStyle: null, full: true });
    };
    PropertyComposite.prototype.initialize = function (props, opts) {
        if (props === void 0) { props = {}; }
        if (opts === void 0) { opts = {}; }
        // @ts-ignore
        model_Property.callParentInit(model_Property, this, props, opts);
        var em = this.em;
        var properties = new model_Properties(this.get('properties') || [], {
            em: em,
            parentProp: this,
        });
        this.set('properties', properties, { silent: true });
        this.listenTo(properties, 'change', this.__upProperties);
        // @ts-ignore
        model_Property.callInit(this, props, opts);
    };
    Object.defineProperty(PropertyComposite.prototype, "properties", {
        get: function () {
            // @ts-ignore
            return this.get('properties') || [];
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Get properties.
     * @returns {Array<[Property]>}
     */
    PropertyComposite.prototype.getProperties = function () {
        // @ts-ignore
        return PropertyComposite_spreadArray([], this.get('properties').models, true);
    };
    /**
     * Get property by id.
     * @param  {String} id Property id.
     * @returns {[Property]|null}
     */
    PropertyComposite.prototype.getProperty = function (id) {
        return this.properties.filter(function (prop) { return prop.getId() === id || prop.getName() === id; })[0];
    };
    /**
     * Get property at index.
     * @param  {Number} index
     * @returns {[Property]|null}
     */
    PropertyComposite.prototype.getPropertyAt = function (index) {
        // @ts-ignore
        return this.get('properties').at(index);
    };
    /**
     * Check if the property is detached.
     * @returns {Boolean}
     */
    PropertyComposite.prototype.isDetached = function () {
        return !!this.get('detached');
    };
    /**
     * Get current values of properties.
     * @param {Object} [opts={}] Options
     * @param {Boolean} [opts.byName=false] Use property names as a key instead of the id.
     * @returns {Object}
     * @example
     * // In case the property is `margin` with sub properties like `margin-top`, `margin-right`, etc.
     * console.log(property.getValues());
     * // { 'margin-top': '10px', 'margin-right': '20px', ... };
     */
    PropertyComposite.prototype.getValues = function (_a) {
        var _b = _a === void 0 ? {} : _a, byName = _b.byName;
        return this.getProperties().reduce(function (res, prop) {
            var key = byName ? prop.getName() : prop.getId();
            res[key] = "".concat(prop.__getFullValue());
            return res;
        }, {});
    };
    /**
     * Get property separator.
     * @returns {RegExp}
     */
    PropertyComposite.prototype.getSeparator = function () {
        return this.getSplitSeparator();
    };
    /**
     * Get the join value.
     * @returns {String}
     */
    PropertyComposite.prototype.getJoin = function () {
        return this.__getJoin();
    };
    /**
     * Get style object from current properties
     * @param {Object} [opts={}] Options
     * @param {Boolean} [opts.camelCase] Return property names in camelCase.
     * @returns {Object} Style object
     * @private
     */
    PropertyComposite.prototype.getStyleFromProps = function (opts) {
        var _a;
        if (opts === void 0) { opts = {}; }
        var name = this.getName();
        var join = this.__getJoin();
        var toStyle = this.get('toStyle');
        var values = this.getValues();
        var style = {};
        if (toStyle) {
            style = toStyle(values, { join: join, name: name, property: this });
        }
        else {
            values = this.getValues({ byName: true });
            if (this.isDetached()) {
                style = values;
            }
            else {
                var value = this.getProperties()
                    .map(function (p) { return p.__getFullValue({ withDefault: 1 }); })
                    .filter(Boolean)
                    .join(join);
                style = (_a = {}, _a[name] = value, _a);
            }
        }
        if (this.isDetached()) {
            style[name] = '';
        }
        else {
            style[name] = style[name] || '';
            style = PropertyComposite_assign(PropertyComposite_assign({}, style), this.getProperties().reduce(function (acc, prop) {
                acc[prop.getName()] = '';
                return acc;
            }, {}));
        }
        return opts.camelCase
            ? Object.keys(style).reduce(function (res, key) {
                res[(0,mixins.camelCase)(key)] = style[key];
                return res;
            }, {})
            : style;
    };
    PropertyComposite.prototype.getSplitSeparator = function () {
        return new RegExp("".concat(this.get('separator'), "(?![^\\(]*\\))"));
    };
    PropertyComposite.prototype.__upProperties = function (p, opts) {
        if (opts === void 0) { opts = {}; }
        if (opts.__up || opts.__clearIn)
            return;
        var parentProp = this.__getParentProp();
        if (parentProp)
            return parentProp.__upProperties(this, opts);
        this.__upTargetsStyleProps(opts, p);
    };
    PropertyComposite.prototype.__upTargetsStyleProps = function (opts, prop) {
        var _a;
        if (opts === void 0) { opts = {}; }
        var style = this.getStyleFromProps();
        if (this.isDetached() && prop) {
            var name_1 = prop.getName();
            style = (_a = {}, _a[name_1] = style[name_1], _a);
        }
        this.__upTargetsStyle(style, opts);
    };
    PropertyComposite.prototype._up = function (props, opts) {
        if (opts === void 0) { opts = {}; }
        this.__setProperties(this.__getSplitValue(props.value), opts);
        model_Property.prototype._up.call(this, props, opts);
        return this;
    };
    PropertyComposite.prototype.getStyle = function (opts) {
        return this.getStyleFromProps(opts);
    };
    PropertyComposite.prototype.__getFullValue = function (opts) {
        if (opts === void 0) { opts = {}; }
        if (this.isDetached() || opts.__clear)
            return '';
        var result = this.getStyleFromProps()[this.getName()] || '';
        return getLastStyleValue(result);
    };
    PropertyComposite.prototype.__getJoin = function () {
        var join = this.get('join');
        return (0,index_all.isString)(join) ? join : this.get('separator');
    };
    PropertyComposite.prototype.__styleHasProps = function (style) {
        if (style === void 0) { style = {}; }
        var name = this.getName();
        var props = this.getProperties();
        var nameProps = props.map(function (prop) { return prop.getName(); });
        var allNameProps = PropertyComposite_spreadArray([name], nameProps, true);
        return allNameProps.some(function (prop) { return !(0,index_all.isUndefined)(style[prop]) && style[prop] !== ''; });
    };
    PropertyComposite.prototype.__splitValue = function (value, sep) {
        return getLastStyleValue(value)
            .split(sep)
            .map(function (value) { return value.trim(); })
            .filter(Boolean);
    };
    PropertyComposite.prototype.__splitStyleName = function (style, name, sep) {
        return this.__splitValue(style[name] || '', sep);
    };
    PropertyComposite.prototype.__getSplitValue = function (value, _a) {
        if (value === void 0) { value = ''; }
        var _b = _a === void 0 ? {} : _a, byName = _b.byName;
        var props = this.getProperties();
        var props4Nums = props.length === 4 && props.every(function (prop) { return isNumberType(prop.getType()); });
        var values = this.__splitValue(value, this.getSplitSeparator());
        var result = {};
        props.forEach(function (prop, i) {
            var value = values[i];
            var res = !(0,index_all.isUndefined)(value) ? value : ''; // : prop.getDefaultValue();
            if (props4Nums) {
                // Try to get value from a shorthand:
                // 11px -> 11px 11px 11px 11xp
                // 11px 22px -> 11px 22px 11px 22xp
                var len = values.length;
                res = values[i] || values[(i % len) + (len != 1 && len % 2 ? 1 : 0)] || res;
            }
            var key = byName ? prop.getName() : prop.getId();
            result[key] = res || '';
        });
        return result;
    };
    PropertyComposite.prototype.__getPropsFromStyle = function (style, opts) {
        if (style === void 0) { style = {}; }
        if (opts === void 0) { opts = {}; }
        if (!this.__styleHasProps(style))
            return null;
        var byName = opts.byName;
        var name = this.getName();
        var props = this.getProperties();
        var sep = this.getSplitSeparator();
        var fromStyle = this.get('fromStyle');
        var result = fromStyle ? fromStyle(style, { property: this, name: name, separator: sep }) : {};
        if (!fromStyle) {
            // Get props from the main property
            result = this.__getSplitValue(style[name] || '', { byName: byName });
            // Get props from the inner properties
            props.forEach(function (prop) {
                var value = style[prop.getName()];
                var key = byName ? prop.getName() : prop.getId();
                if (!(0,index_all.isUndefined)(value) && value !== '')
                    result[key] = value;
            });
        }
        return result;
    };
    PropertyComposite.prototype.__setProperties = function (values, opts) {
        if (values === void 0) { values = {}; }
        if (opts === void 0) { opts = {}; }
        this.getProperties().forEach(function (prop) {
            var value = values[prop.getId()];
            prop.__getFullValue() !== value && prop.upValue(value, opts);
        });
        // Keep track of the values, otherwise clear() will not trigger changes.
        var valuesStr = (0,index_all.keys)(values)
            .map(function (k) { return values[k]; })
            .join(' ');
        this.set('value', valuesStr, { silent: true });
    };
    PropertyComposite.prototype.clear = function () {
        var _this = this;
        this.getProperties().map(function (p) { return p.clear({ __clearIn: !_this.isDetached() }); });
        model_Property.prototype.clear.call(this);
        return this;
    };
    PropertyComposite.prototype.hasValue = function (opts) {
        return this.getProperties().some(function (prop) { return prop.hasValue(opts); });
    };
    PropertyComposite.prototype.getFullValue = function () {
        return this.__getFullValue();
    };
    PropertyComposite.prototype.__canClearProp = function (prop) {
        return this.isDetached() && prop.hasValue({ noParent: true });
    };
    return PropertyComposite;
}(model_Property));
/* harmony default export */ const model_PropertyComposite = (PropertyComposite);

;// CONCATENATED MODULE: ./src/style_manager/model/PropertyStack.ts
var PropertyStack_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var PropertyStack_assign = (undefined && undefined.__assign) || function () {
    PropertyStack_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return PropertyStack_assign.apply(this, arguments);
};
var PropertyStack_rest = (undefined && undefined.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};






var VALUES_REG = /,(?![^\(]*\))/;
var PARTS_REG = /\s(?![^(]*\))/;
/**
 *
 * [Layer]: layer.html
 *
 *
 * @typedef PropertyStack
 * @property {Boolean} [preview=false] Indicate if the layer should display a preview.
 * @property {String|RegExp} [layerSeparator=', '] The separator used to split layer values.
 * @property {String} [layerJoin=', '] Value used to join layer values.
 * @property {Function} [layerLabel] Custom logic for creating layer labels.
 * \n
 * ```js
 *  layerLabel: (layer) => {
 *    const values = layer.getValues();
 *    return `A: ${values['prop-a']} B: ${values['prop-b']}`;
 *  }
 *  ```
 * @property {String|Function} [emptyValue='unset'] Empty value to apply when all layers are removed.
 * \n
 * ```js
 *  // use simple string
 *  emptyValue: 'inherit',
 *  // or a function for a custom style object
 *  emptyValue: () => ({
 *    color: 'unset',
 *    width: 'auto'
 *  }),
 *  ```
 *
 */
var PropertyStack = /** @class */ (function (_super) {
    PropertyStack_extends(PropertyStack, _super);
    function PropertyStack() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    PropertyStack.prototype.defaults = function () {
        return PropertyStack_assign(PropertyStack_assign({}, model_PropertyComposite.getDefaults()), { layers: [], emptyValue: 'unset', layerSeparator: ', ', layerJoin: '', prepend: 0, preview: false, layerLabel: null, selectedLayer: null });
    };
    PropertyStack.prototype.initialize = function (props, opts) {
        if (props === void 0) { props = {}; }
        if (opts === void 0) { opts = {}; }
        // @ts-ignore
        model_PropertyComposite.callParentInit(model_PropertyComposite, this, props, opts);
        var layers = this.get('layers');
        var layersColl = new model_Layers(layers, { prop: this });
        // @ts-ignore
        layersColl.property = this;
        // @ts-ignore
        layersColl.properties = this.get('properties');
        this.set('layers', layersColl, { silent: true });
        this.on('change:selectedLayer', this.__upSelected);
        this.listenTo(layersColl, 'add remove', this.__upLayers);
        // @ts-ignore
        model_PropertyComposite.callInit(this, props, opts);
    };
    Object.defineProperty(PropertyStack.prototype, "layers", {
        get: function () {
            return this.get('layers');
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Get all available layers.
     * @returns {Array<[Layer]>}
     */
    PropertyStack.prototype.getLayers = function () {
        return this.layers.models;
    };
    /**
     * Check if the property has layers.
     * @returns {Boolean}
     */
    PropertyStack.prototype.hasLayers = function () {
        return this.getLayers().length > 0;
    };
    /**
     * Get layer by index.
     * @param {Number} [index=0] Layer index position.
     * @returns {[Layer]|null}
     * @example
     * // Get the first layer
     * const layerFirst = property.getLayer(0);
     * // Get the last layer
     * const layers = this.getLayers();
     * const layerLast = property.getLayer(layers.length - 1);
     */
    PropertyStack.prototype.getLayer = function (index) {
        if (index === void 0) { index = 0; }
        return this.layers.at(index) || undefined;
    };
    /**
     * Get selected layer.
     * @returns {[Layer] | undefined}
     */
    PropertyStack.prototype.getSelectedLayer = function () {
        var layer = this.get('selectedLayer');
        return layer && layer.getIndex() >= 0 ? layer : undefined;
    };
    /**
     * Select layer.
     * Without a selected layer any update made on inner properties has no effect.
     * @param {[Layer]} layer Layer to select
     * @example
     * const layer = property.getLayer(0);
     * property.selectLayer(layer);
     */
    PropertyStack.prototype.selectLayer = function (layer) {
        return this.set('selectedLayer', layer, { __select: true });
    };
    /**
     * Select layer by index.
     * @param {Number} index Index of the layer to select.
     * @example
     * property.selectLayerAt(1);
     */
    PropertyStack.prototype.selectLayerAt = function (index) {
        if (index === void 0) { index = 0; }
        var layer = this.getLayer(index);
        return layer && this.selectLayer(layer);
    };
    /**
     * Move layer by index.
     * @param {[Layer]} layer Layer to move.
     * @param {Number} index New layer index.
     * @example
     * const layer = property.getLayer(1);
     * property.moveLayer(layer, 0);
     */
    PropertyStack.prototype.moveLayer = function (layer, index) {
        if (index === void 0) { index = 0; }
        var layers = this.layers;
        var currIndex = layer ? layer.getIndex() : -1;
        if (currIndex >= 0 && (0,index_all.isNumber)(index) && index >= 0 && index < layers.length && currIndex !== index) {
            this.removeLayer(layer);
            layers.add(layer, { at: index });
        }
    };
    /**
     * Add new layer to the stack.
     * @param {Object} [props={}] Custom property values to use in a new layer.
     * @param {Object} [opts={}] Options
     * @param {Number} [opts.at] Position index (by default the layer will be appended at the end).
     * @returns {[Layer]} Added layer.
     * @example
     * // Add new layer at the beginning of the stack with custom values
     * property.addLayer({ 'sub-prop1': 'value1', 'sub-prop2': 'value2' }, { at: 0 });
     */
    PropertyStack.prototype.addLayer = function (props, opts) {
        if (props === void 0) { props = {}; }
        if (opts === void 0) { opts = {}; }
        var values = {};
        this.getProperties().forEach(function (prop) {
            var key = prop.getId();
            var value = props[key];
            values[key] = (0,index_all.isUndefined)(value) ? prop.getDefaultValue() : value;
        });
        var layer = this.layers.push({ values: values }, opts);
        return layer;
    };
    /**
     * Remove layer.
     * @param {[Layer]} layer Layer to remove.
     * @returns {[Layer]} Removed layer
     * @example
     * const layer = property.getLayer(0);
     * property.removeLayer(layer);
     */
    PropertyStack.prototype.removeLayer = function (layer) {
        return this.layers.remove(layer);
    };
    /**
     * Remove layer by index.
     * @param {Number} index Index of the layer to remove
     * @returns {[Layer]|null} Removed layer
     * @example
     * property.removeLayerAt(0);
     */
    PropertyStack.prototype.removeLayerAt = function (index) {
        if (index === void 0) { index = 0; }
        var layer = this.getLayer(index);
        return layer ? this.removeLayer(layer) : null;
    };
    /**
     * Get the layer label. The label can be customized with the `layerLabel` property.
     * @param {[Layer]} layer
     * @returns {String}
     * @example
     * const layer = this.getLayer(1);
     * const label = this.getLayerLabel(layer);
     */
    PropertyStack.prototype.getLayerLabel = function (layer) {
        var result = '';
        if (layer) {
            var layerLabel = this.get('layerLabel');
            var values_1 = layer.getValues();
            var index = layer.getIndex();
            if (layerLabel) {
                result = layerLabel(layer, { index: index, values: values_1, property: this });
            }
            else {
                var parts_1 = [];
                this.getProperties().map(function (prop) {
                    parts_1.push(values_1[prop.getId()]);
                });
                result = parts_1.filter(Boolean).join(' ');
            }
        }
        return result;
    };
    /**
     * Get style object from the layer.
     * @param {[Layer]} layer
     * @param {Object} [opts={}] Options
     * @param {Boolean} [opts.camelCase] Return property names in camelCase.
     * @param {Object} [opts.number] Limit the result of the number types, eg. `number: { min: -3, max: 3 }`
     * @returns {Object} Style object
     */
    PropertyStack.prototype.getStyleFromLayer = function (layer, opts) {
        var _a;
        if (opts === void 0) { opts = {}; }
        var join = this.__getJoin();
        var joinLayers = this.__getJoinLayers();
        var toStyle = this.get('toStyle');
        var name = this.getName();
        var values = layer.getValues();
        var style;
        if (toStyle) {
            style = toStyle(values, {
                join: join,
                joinLayers: joinLayers,
                name: name,
                layer: layer,
                property: this,
            });
        }
        else {
            var result = this.getProperties().map(function (prop) {
                var name = prop.getName();
                var val = values[prop.getId()];
                var value = (0,index_all.isUndefined)(val) ? prop.getDefaultValue() : val;
                // Limit number values if necessary (useful for previews)
                if (opts.number && isNumberType(prop.getType())) {
                    var newVal = prop.parseValue(val, opts.number);
                    value = "".concat(newVal.value).concat(newVal.unit);
                }
                return { name: name, value: value };
            });
            style = this.isDetached()
                ? result.reduce(function (acc, item) {
                    acc[item.name] = item.value;
                    return acc;
                }, {})
                : (_a = {},
                    _a[this.getName()] = result.map(function (r) { return r.value; }).join(join),
                    _a);
        }
        return opts.camelCase
            ? Object.keys(style).reduce(function (res, key) {
                res[(0,mixins.camelCase)(key)] = style[key];
                return res;
            }, {})
            : style;
    };
    /**
     * Get preview style object from the layer.
     * If the property has `preview: false` the returned object will be empty.
     * @param {[Layer]} layer
     * @param {Object} [opts={}] Options. Same of `getStyleFromLayer`
     * @returns {Object} Style object
     */
    PropertyStack.prototype.getStylePreview = function (layer, opts) {
        if (opts === void 0) { opts = {}; }
        var result = {};
        var preview = this.get('preview');
        if (preview) {
            result = this.getStyleFromLayer(layer, opts);
        }
        return result;
    };
    /**
     * Get layer separator.
     * @return {RegExp}
     */
    PropertyStack.prototype.getLayerSeparator = function () {
        var sep = this.get('layerSeparator');
        return (0,index_all.isString)(sep) ? new RegExp("".concat(sep, "(?![^\\(]*\\))")) : sep;
    };
    /**
     * Check if the property is with an empty value.
     * @returns {Boolean}
     */
    PropertyStack.prototype.hasEmptyValue = function () {
        return !this.hasLayers() && !!this.attributes.isEmptyValue;
    };
    PropertyStack.prototype.__upProperties = function (prop, opts) {
        var _a;
        if (opts === void 0) { opts = {}; }
        var layer = this.getSelectedLayer();
        if (!layer)
            return;
        layer.upValues((_a = {}, _a[prop.getId()] = prop.__getFullValue(), _a));
        if (opts.__up)
            return;
        this.__upTargetsStyleProps(opts);
    };
    PropertyStack.prototype.__upLayers = function (m, c, o) {
        this.__upTargetsStyleProps(o || c);
    };
    PropertyStack.prototype.__upTargets = function (p, opts) {
        if (opts === void 0) { opts = {}; }
        if (opts.__select)
            return;
        return model_Property.prototype.__upTargets.call(this, p, opts);
    };
    PropertyStack.prototype.__upTargetsStyleProps = function (opts) {
        if (opts === void 0) { opts = {}; }
        this.__upTargetsStyle(this.getStyleFromLayers(opts), opts);
    };
    PropertyStack.prototype.__upTargetsStyle = function (style, opts) {
        return model_Property.prototype.__upTargetsStyle.call(this, style, opts);
    };
    PropertyStack.prototype.__upSelected = function (_a, opts) {
        var _b = _a === void 0 ? {} : _a, noEvent = _b.noEvent;
        if (opts === void 0) { opts = {}; }
        var sm = this.em.Styles;
        var selected = this.getSelectedLayer();
        var values = selected === null || selected === void 0 ? void 0 : selected.getValues();
        // Update properties by layer value
        values &&
            this.getProperties().forEach(function (prop) {
                var _a;
                var value = (_a = values[prop.getId()]) !== null && _a !== void 0 ? _a : '';
                prop.__getFullValue() !== value && prop.upValue(value, PropertyStack_assign(PropertyStack_assign({}, opts), { __up: true }));
            });
        !noEvent && sm.__trgEv(sm.events.layerSelect, { property: this });
    };
    // @ts-ignore
    PropertyStack.prototype._up = function (props, opts) {
        if (opts === void 0) { opts = {}; }
        var _a = props.__layers, __layers = _a === void 0 ? [] : _a, rest = PropertyStack_rest(props, ["__layers"]);
        // Detached props will update their layers later in sm.__upProp
        !this.isDetached() && this.__setLayers(__layers);
        this.__upSelected({ noEvent: true }, opts);
        model_Property.prototype._up.call(this, rest, opts);
        return this;
    };
    PropertyStack.prototype.__setLayers = function (newLayers, opts) {
        if (newLayers === void 0) { newLayers = []; }
        if (opts === void 0) { opts = {}; }
        var layers = this.layers;
        var layersNew = newLayers.map(function (values) { return ({ values: values }); });
        if (layers.length === layersNew.length) {
            layersNew.map(function (layer, n) { var _a; return (_a = layers.at(n)) === null || _a === void 0 ? void 0 : _a.upValues(layer.values); });
        }
        else {
            layers.reset(layersNew);
        }
        this.set({ isEmptyValue: !!opts.isEmptyValue });
        this.__upSelected({ noEvent: true });
    };
    PropertyStack.prototype.__parseValue = function (value) {
        var _this = this;
        var result = this.parseValue(value);
        result.__layers = value
            .split(VALUES_REG)
            .map(function (v) { return v.trim(); })
            .map(function (v) { return _this.__parseLayer(v); })
            .filter(Boolean);
        return result;
    };
    PropertyStack.prototype.__parseLayer = function (value) {
        var parseFn = this.get('parseLayer');
        var values = value.split(PARTS_REG);
        var properties = this.getProperties();
        return parseFn
            ? parseFn({ value: value, values: values })
            : properties.reduce(function (acc, prop, i) {
                var value = values[i];
                acc[prop.getId()] = !(0,index_all.isUndefined)(value) ? value : prop.getDefaultValue();
                return acc;
            }, {});
    };
    PropertyStack.prototype.__getLayersFromStyle = function (style) {
        var _this = this;
        if (style === void 0) { style = {}; }
        if (!this.__styleHasProps(style))
            return null;
        if (this.isEmptyValueStyle(style))
            return [];
        var name = this.getName();
        var props = this.getProperties();
        var sep = this.getLayerSeparator();
        var fromStyle = this.attributes.fromStyle;
        var result = fromStyle ? fromStyle(style, { property: this, name: name, separatorLayers: sep }) : [];
        if (!fromStyle) {
            // Get layers from the main property
            var layers_1 = this.__splitStyleName(style, name, sep)
                .map(function (value) { return value.split(_this.getSplitSeparator()); })
                .map(function (parts) {
                var result = {};
                props.forEach(function (prop, i) {
                    var value = parts[i];
                    result[prop.getId()] = !(0,index_all.isUndefined)(value) ? value : prop.getDefaultValue();
                });
                return result;
            });
            // Get layers from the inner properties
            props.forEach(function (prop) {
                var id = prop.getId();
                _this.__splitStyleName(style, prop.getName(), sep)
                    .map(function (value) {
                    var _a;
                    return (_a = {}, _a[id] = value || prop.getDefaultValue(), _a);
                })
                    .forEach(function (inLayer, i) {
                    layers_1[i] = layers_1[i] ? PropertyStack_assign(PropertyStack_assign({}, layers_1[i]), inLayer) : inLayer;
                });
            });
            result = layers_1;
        }
        return (0,index_all.isArray)(result) ? result : [result];
    };
    PropertyStack.prototype.getStyle = function (opts) {
        if (opts === void 0) { opts = {}; }
        return this.getStyleFromLayers(opts);
    };
    PropertyStack.prototype.getStyleFromLayers = function (opts) {
        var _this = this;
        if (opts === void 0) { opts = {}; }
        var result = {};
        var name = this.getName();
        var layers = this.getLayers();
        var props = this.getProperties();
        var styles = layers.map(function (l) { return _this.getStyleFromLayer(l, opts); });
        styles.forEach(function (style) {
            (0,index_all.keys)(style).map(function (key) {
                if (!result[key]) {
                    result[key] = [];
                }
                // @ts-ignore
                result[key].push(style[key]);
            });
        });
        (0,index_all.keys)(result).map(function (key) {
            result[key] = result[key].join(_this.__getJoinLayers());
        });
        if (this.isDetached()) {
            result[name] = '';
            !layers.length &&
                props.map(function (prop) {
                    result[prop.getName()] = '';
                });
        }
        else {
            var style = props.reduce(function (acc, prop) {
                acc[prop.getName()] = '';
                return acc;
            }, {});
            result[name] = result[name] || '';
            result = PropertyStack_assign(PropertyStack_assign({}, result), style);
        }
        return PropertyStack_assign(PropertyStack_assign({}, result), (opts.__clear ? {} : this.getEmptyValueStyle()));
    };
    PropertyStack.prototype.isEmptyValueStyle = function (style) {
        if (style === void 0) { style = {}; }
        var emptyStyle = this.getEmptyValueStyle({ force: true });
        var props = (0,index_all.keys)(emptyStyle);
        return !!props.length && props.every(function (prop) { return emptyStyle[prop] === style[prop]; });
    };
    PropertyStack.prototype.getEmptyValueStyle = function (opts) {
        if (opts === void 0) { opts = {}; }
        var emptyValue = this.attributes.emptyValue;
        if (emptyValue && (!this.hasLayers() || opts.force)) {
            var name_1 = this.getName();
            var props = this.getProperties();
            var result_1 = (0,index_all.isString)(emptyValue) ? emptyValue : emptyValue({ property: this });
            if ((0,index_all.isString)(result_1)) {
                var style_1 = {};
                if (this.isDetached()) {
                    props.map(function (prop) {
                        style_1[prop.getName()] = result_1;
                    });
                }
                else {
                    style_1[name_1] = result_1;
                }
                return style_1;
            }
            else {
                return result_1;
            }
        }
        else {
            return {};
        }
    };
    PropertyStack.prototype.__getJoinLayers = function () {
        var join = this.get('layerJoin');
        var sep = this.get('layerSeparator');
        return join || ((0,index_all.isString)(sep) ? sep : join);
    };
    PropertyStack.prototype.__getFullValue = function () {
        if (this.get('detached'))
            return '';
        var style = this.getStyleFromLayers();
        return getLastStyleValue(style[this.getName()]);
    };
    /**
     * Extended
     * @private
     */
    PropertyStack.prototype.hasValue = function (opts) {
        if (opts === void 0) { opts = {}; }
        var noParent = opts.noParent;
        var parentValue = noParent && this.getParentTarget();
        return (this.hasLayers() || this.hasEmptyValue()) && !parentValue;
    };
    /**
     * Extended
     * @private
     */
    PropertyStack.prototype.clear = function (opts) {
        if (opts === void 0) { opts = {}; }
        this.layers.reset();
        this.__upTargetsStyleProps(PropertyStack_assign(PropertyStack_assign({}, opts), { __clear: true }));
        model_Property.prototype.clear.call(this);
        return this;
    };
    PropertyStack.prototype.__canClearProp = function () {
        return false;
    };
    /**
     * @deprecated
     * @private
     */
    PropertyStack.prototype.__getLayers = function () {
        return this.layers;
    };
    return PropertyStack;
}(model_PropertyComposite));
/* harmony default export */ const model_PropertyStack = (PropertyStack);

;// CONCATENATED MODULE: ./src/style_manager/view/PropertyView.ts
var PropertyView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var PropertyView_assign = (undefined && undefined.__assign) || function () {
    PropertyView_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return PropertyView_assign.apply(this, arguments);
};
var PropertyView_rest = (undefined && undefined.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
var PropertyView_spreadArray = (undefined && undefined.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};



var clearProp = 'data-clear-style';
var PropertyView = /** @class */ (function (_super) {
    PropertyView_extends(PropertyView, _super);
    function PropertyView(o) {
        if (o === void 0) { o = {}; }
        var _this = _super.call(this, o) || this;
        (0,index_all.bindAll)(_this, '__change', '__updateStyle');
        // @ts-ignore
        var config = o.config || {};
        var em = config.em;
        _this.config = config;
        _this.em = em;
        _this.pfx = config.stylePrefix || '';
        _this.ppfx = config.pStylePrefix || '';
        _this.__destroyFn = _this.destroy ? _this.destroy.bind(_this) : function () { };
        var model = _this.model;
        // @ts-ignore
        model.view = _this;
        // Put a sligh delay on debounce in order to execute the update
        // post styleManager.__upProps trigger.
        _this.onValueChange = (0,index_all.debounce)(_this.onValueChange.bind(_this), 10);
        _this.updateStatus = (0,index_all.debounce)(_this.updateStatus.bind(_this), 0);
        _this.listenTo(model, 'destroy remove', _this.remove);
        _this.listenTo(model, 'change:visible', _this.updateVisibility);
        _this.listenTo(model, 'change:name change:className change:full', _this.render);
        _this.listenTo(model, 'change:value', _this.onValueChange);
        _this.listenTo(model, 'change:parentTarget', _this.updateStatus);
        _this.listenTo(em, 'change:device', _this.onValueChange);
        // @ts-ignore
        var init = _this.init && _this.init.bind(_this);
        init && init();
        return _this;
    }
    PropertyView.prototype.events = function () {
        var _a;
        return _a = {
                change: 'inputValueChanged'
            },
            _a["click [".concat(clearProp, "]")] = 'clear',
            _a;
    };
    PropertyView.prototype.template = function (model) {
        var _a = this, pfx = _a.pfx, ppfx = _a.ppfx;
        return "\n      <div class=\"".concat(pfx, "label\" data-sm-label></div>\n      <div class=\"").concat(ppfx, "fields\" data-sm-fields></div>\n    ");
    };
    PropertyView.prototype.templateLabel = function (model) {
        var _a = this, pfx = _a.pfx, em = _a.em;
        var parent = model.parent;
        var _b = model.attributes, _c = _b.icon, icon = _c === void 0 ? '' : _c, _d = _b.info, info = _d === void 0 ? '' : _d;
        var icons = em === null || em === void 0 ? void 0 : em.getConfig().icons;
        var iconClose = (icons === null || icons === void 0 ? void 0 : icons.close) || '';
        return "\n      <span class=\"".concat(pfx, "icon ").concat(icon, "\" title=\"").concat(info, "\">\n        ").concat(model.getLabel(), "\n      </span>\n      ").concat(!parent ? "<div class=\"".concat(pfx, "clear\" style=\"display: none\" ").concat(clearProp, ">").concat(iconClose, "</div>") : '', "\n    ");
    };
    PropertyView.prototype.templateInput = function (model) {
        return "\n      <div class=\"".concat(this.ppfx, "field\">\n        <input placeholder=\"").concat(model.getDefaultValue(), "\"/>\n      </div>\n    ");
    };
    PropertyView.prototype.remove = function () {
        var _this = this;
        common/* View */.G7.prototype.remove.apply(this, arguments);
        // @ts-ignore
        ['em', 'input', '$input', 'view'].forEach(function (i) { return (_this[i] = null); });
        this.__destroyFn(this._getClbOpts());
        return this;
    };
    /**
     * Triggers when the status changes. The status indicates if the value of
     * the proprerty is changed or inherited
     * @private
     */
    PropertyView.prototype.updateStatus = function () {
        var _a;
        var _b = this, model = _b.model, pfx = _b.pfx, ppfx = _b.ppfx, config = _b.config;
        var updatedCls = "".concat(ppfx, "four-color");
        var computedCls = "".concat(ppfx, "color-warn");
        var labelEl = this.$el.children(".".concat(pfx, "label"));
        var clearStyleEl = this.getClearEl();
        var clearStyle = clearStyleEl ? clearStyleEl.style : {};
        labelEl.removeClass("".concat(updatedCls, " ").concat(computedCls));
        clearStyle.display = 'none';
        if (model.hasValue({ noParent: true }) && config.highlightChanged) {
            labelEl.addClass(updatedCls);
            config.clearProperties && (clearStyle.display = '');
        }
        else if (model.hasValue() && config.highlightComputed) {
            labelEl.addClass(computedCls);
        }
        (_a = this.parent) === null || _a === void 0 ? void 0 : _a.updateStatus();
    };
    /**
     * Clear the property from the target
     */
    PropertyView.prototype.clear = function (ev) {
        ev && ev.stopPropagation();
        this.model.clear();
    };
    /**
     * Get clear element
     * @return {HTMLElement}
     */
    PropertyView.prototype.getClearEl = function () {
        if (!this.clearEl) {
            this.clearEl = this.el.querySelector("[".concat(clearProp, "]"));
        }
        return this.clearEl;
    };
    /**
     * Triggers when the value of element input/s is changed, so have to update
     * the value of the model which will propogate those changes to the target
     */
    PropertyView.prototype.inputValueChanged = function (ev) {
        ev && ev.stopPropagation();
        // Skip the default update in case a custom emit method is defined
        if (this.emit)
            return;
        this.model.upValue(ev.target.value);
    };
    PropertyView.prototype.onValueChange = function (m, val, opt) {
        if (opt === void 0) { opt = {}; }
        this.setValue(this.model.getFullValue(undefined, { skipImportant: true }));
        this.updateStatus();
    };
    /**
     * Update the element input.
     * Usually the value is a result of `model.getFullValue()`
     * @param {String} value The value from the model
     * */
    PropertyView.prototype.setValue = function (value) {
        var model = this.model;
        var result = (0,index_all.isUndefined)(value) || value === '' ? model.getDefaultValue() : value;
        if (this.update)
            return this.__update(result);
        this.__setValueInput(result);
    };
    PropertyView.prototype.__setValueInput = function (value) {
        var input = this.getInputEl();
        input && (input.value = value);
    };
    PropertyView.prototype.getInputEl = function () {
        if (!this.input) {
            this.input = this.el.querySelector('input');
        }
        return this.input;
    };
    PropertyView.prototype.updateVisibility = function () {
        this.el.style.display = this.model.isVisible() ? '' : 'none';
    };
    PropertyView.prototype.clearCached = function () {
        delete this.clearEl;
        delete this.input;
        delete this.$input;
    };
    PropertyView.prototype.__unset = function () {
        var unset = this.unset && this.unset.bind(this);
        unset && unset(this._getClbOpts());
    };
    PropertyView.prototype.__update = function (value) {
        var update = this.update && this.update.bind(this);
        update &&
            update(PropertyView_assign(PropertyView_assign({}, this._getClbOpts()), { value: value }));
    };
    PropertyView.prototype.__change = function () {
        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            args[_i] = arguments[_i];
        }
        var emit = this.emit && this.emit.bind(this);
        emit && emit.apply(void 0, PropertyView_spreadArray([this._getClbOpts()], args, false));
    };
    PropertyView.prototype.__updateStyle = function (value, _a) {
        if (_a === void 0) { _a = {}; }
        var complete = _a.complete, partial = _a.partial, opts = PropertyView_rest(_a, ["complete", "partial"]);
        var model = this.model;
        var final = complete !== false && partial !== true;
        if ((0,mixins.isObject)(value)) {
            model.__upTargetsStyle(value, { avoidStore: !final });
        }
        else {
            model.upValue(value, { partial: !final });
        }
    };
    PropertyView.prototype._getClbOpts = function () {
        var _a = this, model = _a.model, el = _a.el, createdEl = _a.createdEl;
        return {
            el: el,
            createdEl: createdEl,
            property: model,
            props: model.attributes,
            change: this.__change,
            updateStyle: this.__updateStyle,
        };
    };
    PropertyView.prototype.render = function () {
        this.clearCached();
        var _a = this, pfx = _a.pfx, model = _a.model, el = _a.el, $el = _a.$el;
        var name = model.getName();
        var type = model.getType();
        var cls = model.get('className') || '';
        var className = "".concat(pfx, "property");
        // Support old integer classname
        var clsType = type === 'number' ? "".concat(pfx).concat(type, " ").concat(pfx, "integer") : "".concat(pfx).concat(type);
        this.createdEl && this.__destroyFn(this._getClbOpts());
        $el.empty().append(this.template(model));
        $el.find('[data-sm-label]').append(this.templateLabel(model));
        var create = this.create && this.create.bind(this);
        this.createdEl = create && create(this._getClbOpts());
        $el.find('[data-sm-fields]').append(this.createdEl || this.templateInput(model));
        el.className = "".concat(className, " ").concat(clsType, " ").concat(className, "__").concat(name, " ").concat(cls).trim();
        el.className += model.isFull() ? " ".concat(className, "--full") : '';
        var onRender = this.onRender && this.onRender.bind(this);
        onRender && onRender();
        this.setValue(model.getValue());
        return this;
    };
    PropertyView.prototype.onRender = function () { };
    return PropertyView;
}(common/* View */.G7));
/* harmony default export */ const view_PropertyView = (PropertyView);

;// CONCATENATED MODULE: ./src/style_manager/view/PropertiesView.ts
var PropertiesView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();


var PropertiesView = /** @class */ (function (_super) {
    PropertiesView_extends(PropertiesView, _super);
    function PropertiesView(o) {
        var _this = _super.call(this, o) || this;
        _this.config = o.config || {};
        _this.pfx = _this.config.stylePrefix || '';
        _this.properties = [];
        _this.parent = o.parent;
        var coll = _this.collection;
        _this.listenTo(coll, 'add', _this.addTo);
        _this.listenTo(coll, 'reset', _this.render);
        return _this;
    }
    PropertiesView.prototype.addTo = function (model, coll, opts) {
        this.add(model, null, opts);
    };
    PropertiesView.prototype.add = function (model, frag, opts) {
        if (opts === void 0) { opts = {}; }
        var _a = this, parent = _a.parent, config = _a.config;
        var appendTo = frag || this.el;
        var view = new model.typeView({ model: model, config: config });
        parent && (view.parent = parent);
        view.render();
        var rendered = view.el;
        this.properties.push(view);
        (0,dom/* appendAtIndex */.$Q)(appendTo, rendered, opts.at);
    };
    PropertiesView.prototype.remove = function () {
        common/* View */.G7.prototype.remove.apply(this, arguments);
        this.clearItems();
        return this;
    };
    PropertiesView.prototype.clearItems = function () {
        this.properties.forEach(function (item) { return item.remove(); });
        this.properties = [];
    };
    PropertiesView.prototype.render = function () {
        var _this = this;
        var _a = this, $el = _a.$el, pfx = _a.pfx;
        this.clearItems();
        var fragment = document.createDocumentFragment();
        this.collection.forEach(function (model) { return _this.add(model, fragment); });
        $el.empty();
        $el.append(fragment);
        $el.attr('class', "".concat(pfx, "properties"));
        return this;
    };
    return PropertiesView;
}(common/* View */.G7));
/* harmony default export */ const view_PropertiesView = (PropertiesView);

;// CONCATENATED MODULE: ./src/style_manager/view/PropertyCompositeView.ts
var PropertyCompositeView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var PropertyCompositeView_assign = (undefined && undefined.__assign) || function () {
    PropertyCompositeView_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return PropertyCompositeView_assign.apply(this, arguments);
};


var PropertyCompositeView = /** @class */ (function (_super) {
    PropertyCompositeView_extends(PropertyCompositeView, _super);
    function PropertyCompositeView() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    PropertyCompositeView.prototype.templateInput = function () {
        var pfx = this.pfx;
        return "\n      <div class=\"".concat(pfx, "field ").concat(pfx, "composite\">\n        <span id=\"").concat(pfx, "input-holder\"></span>\n      </div>\n    ");
    };
    PropertyCompositeView.prototype.remove = function () {
        var _a;
        (_a = this.props) === null || _a === void 0 ? void 0 : _a.remove();
        view_PropertyView.prototype.remove.apply(this, arguments);
        return this;
    };
    PropertyCompositeView.prototype.onValueChange = function () { };
    PropertyCompositeView.prototype.onRender = function () {
        var pfx = this.pfx;
        var model = this.model;
        var props = model.get('properties');
        if (props.length && !this.props) {
            var detached = model.isDetached();
            var propsView = new view_PropertiesView({
                config: PropertyCompositeView_assign(PropertyCompositeView_assign({}, this.config), { highlightComputed: detached, highlightChanged: detached }),
                // @ts-ignore
                collection: props,
                parent: this,
            });
            propsView.render();
            this.$el.find("#".concat(pfx, "input-holder")).append(propsView.el);
            this.props = propsView;
        }
    };
    PropertyCompositeView.prototype.clearCached = function () {
        view_PropertyView.prototype.clearCached.apply(this, arguments);
        delete this.props;
    };
    return PropertyCompositeView;
}(view_PropertyView));
/* harmony default export */ const view_PropertyCompositeView = (PropertyCompositeView);

;// CONCATENATED MODULE: ./src/style_manager/view/LayerView.ts
var LayerView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();


var LayerView = /** @class */ (function (_super) {
    LayerView_extends(LayerView, _super);
    function LayerView() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    LayerView.prototype.events = function () {
        return {
            click: 'select',
            'click [data-close-layer]': 'removeItem',
            'mousedown [data-move-layer]': 'initSorter',
            'touchstart [data-move-layer]': 'initSorter',
        };
    };
    LayerView.prototype.template = function () {
        var _a = this, pfx = _a.pfx, ppfx = _a.ppfx, em = _a.em;
        var icons = em === null || em === void 0 ? void 0 : em.getConfig().icons;
        var iconClose = (icons === null || icons === void 0 ? void 0 : icons.close) || '';
        var iconMove = (icons === null || icons === void 0 ? void 0 : icons.move) || '';
        return "\n      <div class=\"".concat(pfx, "label-wrp\">\n        <div id=\"").concat(pfx, "move\" class=\"").concat(ppfx, "no-touch-actions\" data-move-layer>\n          ").concat(iconMove, "\n        </div>\n        <div id=\"").concat(pfx, "label\" data-label></div>\n        <div id=\"").concat(pfx, "preview-box\" class=\"").concat(pfx, "layer-preview\" style=\"display: none\" data-preview-box>\n          <div id=\"").concat(pfx, "preview\" class=\"").concat(pfx, "layer-preview-cnt\" data-preview></div>\n        </div>\n        <div id=\"").concat(pfx, "close-layer\" class=\"").concat(pfx, "btn-close\" data-close-layer>\n          ").concat(iconClose, "\n        </div>\n      </div>\n      <div id=\"").concat(pfx, "inputs\" data-properties></div>\n    ");
    };
    LayerView.prototype.initialize = function (o) {
        if (o === void 0) { o = {}; }
        var model = this.model;
        var config = o.config || {};
        this.em = config.em;
        this.config = config;
        this.sorter = o.sorter;
        this.pfx = config.stylePrefix || '';
        this.ppfx = config.pStylePrefix || '';
        this.propertyView = o.propertyView;
        var pModel = this.propertyView.model;
        this.listenTo(model, 'destroy remove', this.remove);
        this.listenTo(model, 'change:values', this.updateLabel);
        this.listenTo(pModel, 'change:selectedLayer', this.updateVisibility);
        // For the sorter
        model.view = this;
        // @ts-ignore
        model.set({ droppable: 0, draggable: 1 });
        this.$el.data('model', model);
    };
    LayerView.prototype.initSorter = function () {
        var _a;
        (_a = this.sorter) === null || _a === void 0 ? void 0 : _a.startSort(this.el);
    };
    LayerView.prototype.removeItem = function (ev) {
        ev && ev.stopPropagation();
        this.model.remove();
    };
    LayerView.prototype.select = function () {
        this.model.select();
    };
    LayerView.prototype.getPropertiesWrapper = function () {
        if (!this.propsWrapEl)
            this.propsWrapEl = this.el.querySelector('[data-properties]');
        return this.propsWrapEl;
    };
    LayerView.prototype.getPreviewEl = function () {
        if (!this.previewEl)
            this.previewEl = this.el.querySelector('[data-preview]');
        return this.previewEl;
    };
    LayerView.prototype.getLabelEl = function () {
        if (!this.labelEl)
            this.labelEl = this.el.querySelector('[data-label]');
        return this.labelEl;
    };
    LayerView.prototype.updateLabel = function () {
        var model = this.model;
        var label = model.getLabel();
        this.getLabelEl().innerHTML = label;
        if (model.hasPreview()) {
            var prvEl = this.getPreviewEl();
            var style_1 = model.getStylePreview({ number: { min: -3, max: 3 } });
            var styleStr = (0,index_all.keys)(style_1)
                .map(function (k) { return "".concat(k, ":").concat(style_1[k]); })
                .join(';');
            prvEl.setAttribute('style', styleStr);
        }
    };
    LayerView.prototype.updateVisibility = function () {
        var _a;
        var _b = this, pfx = _b.pfx, model = _b.model, propertyView = _b.propertyView;
        var wrapEl = this.getPropertiesWrapper();
        var isSelected = model.isSelected();
        wrapEl.style.display = isSelected ? '' : 'none';
        this.$el[isSelected ? 'addClass' : 'removeClass']("".concat(pfx, "active"));
        isSelected && wrapEl.appendChild((_a = propertyView.props) === null || _a === void 0 ? void 0 : _a.el);
    };
    LayerView.prototype.render = function () {
        var _a = this, el = _a.el, pfx = _a.pfx, model = _a.model;
        el.innerHTML = this.template();
        el.className = "".concat(pfx, "layer");
        if (model.hasPreview()) {
            el.querySelector('[data-preview-box]').style.display = '';
        }
        this.updateLabel();
        this.updateVisibility();
        return this;
    };
    return LayerView;
}(common/* View */.G7));
/* harmony default export */ const view_LayerView = (LayerView);

;// CONCATENATED MODULE: ./src/style_manager/view/LayersView.ts
var LayersView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();


var LayersView = /** @class */ (function (_super) {
    LayersView_extends(LayersView, _super);
    function LayersView(o) {
        var _this = _super.call(this, o) || this;
        var coll = _this.collection;
        var config = o.config || {};
        var em = config.em;
        var pfx = config.stylePrefix || '';
        var ppfx = config.pStylePrefix || '';
        _this.config = config;
        _this.pfx = pfx;
        _this.ppfx = ppfx;
        _this.propertyView = o.propertyView;
        _this.className = "".concat(pfx, "layers ").concat(ppfx, "field");
        _this.listenTo(coll, 'add', _this.addTo);
        _this.listenTo(coll, 'reset', _this.reset);
        _this.items = [];
        // For the Sorter
        var utils = em === null || em === void 0 ? void 0 : em.Utils;
        _this.sorter = utils
            ? new utils.Sorter({
                // @ts-ignore
                container: _this.el,
                ignoreViewChildren: 1,
                containerSel: ".".concat(pfx, "layers"),
                itemSel: ".".concat(pfx, "layer"),
                pfx: config.pStylePrefix,
                em: em,
            })
            : '';
        // @ts-ignore
        coll.view = _this;
        _this.$el.data('model', coll);
        _this.$el.data('collection', coll);
        return _this;
    }
    LayersView.prototype.addTo = function (model) {
        var i = this.collection.indexOf(model);
        this.addToCollection(model, null, i);
    };
    LayersView.prototype.addToCollection = function (model, fragmentEl, index) {
        var fragment = fragmentEl || null;
        var _a = this, propertyView = _a.propertyView, config = _a.config, sorter = _a.sorter, $el = _a.$el;
        var view = new view_LayerView({
            model: model,
            // @ts-ignore
            config: config,
            sorter: sorter,
            propertyView: propertyView,
        });
        var rendered = view.render().el;
        this.items.push(view);
        if (fragment) {
            fragment.appendChild(rendered);
        }
        else {
            if (typeof index != 'undefined') {
                var method = 'before';
                if ($el.children().length === index) {
                    index--;
                    method = 'after';
                }
                if (index < 0) {
                    $el.append(rendered);
                }
                else {
                    // @ts-ignore
                    $el.children().eq(index)[method](rendered);
                }
            }
            else {
                $el.append(rendered);
            }
        }
        return rendered;
    };
    LayersView.prototype.reset = function (coll, opts) {
        this.clearItems();
        this.render();
    };
    LayersView.prototype.remove = function () {
        this.clearItems();
        common/* View */.G7.prototype.remove.apply(this, arguments);
        return this;
    };
    LayersView.prototype.clearItems = function () {
        this.items.forEach(function (item) { return item.remove(); });
        this.items = [];
    };
    LayersView.prototype.render = function () {
        var _this = this;
        var _a = this, $el = _a.$el, sorter = _a.sorter;
        var frag = document.createDocumentFragment();
        $el.empty();
        this.collection.forEach(function (m) { return _this.addToCollection(m, frag); });
        $el.append(frag);
        $el.attr('class', this.className);
        if (sorter)
            sorter.plh = null;
        return this;
    };
    return LayersView;
}(common/* View */.G7));
/* harmony default export */ const view_LayersView = (LayersView);

;// CONCATENATED MODULE: ./src/style_manager/view/PropertyStackView.ts
var PropertyStackView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var PropertyStackView_assign = (undefined && undefined.__assign) || function () {
    PropertyStackView_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return PropertyStackView_assign.apply(this, arguments);
};



var PropertyStackView = /** @class */ (function (_super) {
    PropertyStackView_extends(PropertyStackView, _super);
    function PropertyStackView() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    PropertyStackView.prototype.events = function () {
        return PropertyStackView_assign(PropertyStackView_assign({}, view_PropertyCompositeView.prototype.events()), { 'click [data-add-layer]': 'addLayer', change: '' });
    };
    PropertyStackView.prototype.templateInput = function () {
        var _a = this, pfx = _a.pfx, em = _a.em;
        var icons = em === null || em === void 0 ? void 0 : em.getConfig().icons;
        var iconPlus = (icons === null || icons === void 0 ? void 0 : icons.plus) || '+';
        return "\n      <div class=\"".concat(pfx, "field ").concat(pfx, "stack\">\n        <button type=\"button\" id=\"").concat(pfx, "add\" data-add-layer>\n          ").concat(iconPlus, "\n        </button>\n        <div data-layers-wrapper></div>\n      </div>\n    ");
    };
    PropertyStackView.prototype.init = function () {
        var model = this.model;
        this.listenTo(model.layers, 'change reset', this.updateStatus);
        this.listenTo(model, 'change:isEmptyValue', this.updateStatus);
    };
    PropertyStackView.prototype.addLayer = function () {
        this.model.addLayer({}, { at: 0 });
    };
    /**
     * There is no need to handle input update by the property itself,
     * this will be done by layers
     * @private
     */
    PropertyStackView.prototype.setValue = function () { };
    PropertyStackView.prototype.remove = function () {
        var _a;
        (_a = this.layersView) === null || _a === void 0 ? void 0 : _a.remove();
        view_PropertyCompositeView.prototype.remove.apply(this, arguments);
        return this;
    };
    PropertyStackView.prototype.clearCached = function () {
        view_PropertyCompositeView.prototype.clearCached.apply(this, arguments);
        delete this.layersView;
    };
    PropertyStackView.prototype.onRender = function () {
        var _a = this, model = _a.model, el = _a.el, config = _a.config;
        var props = model.get('properties');
        if (props.length && !this.props) {
            var propsView = new view_PropertiesView({
                config: PropertyStackView_assign(PropertyStackView_assign({}, config), { highlightComputed: false, highlightChanged: false }),
                // @ts-ignore
                collection: props,
                parent: this,
            });
            propsView.render();
            var layersView = new view_LayersView({
                collection: model.layers,
                // @ts-ignore
                config: config,
                propertyView: this,
            });
            layersView.render();
            var fieldEl = el.querySelector('[data-layers-wrapper]');
            fieldEl.appendChild(layersView.el);
            this.props = propsView;
            this.layersView = layersView;
        }
    };
    return PropertyStackView;
}(view_PropertyCompositeView));
/* harmony default export */ const view_PropertyStackView = (PropertyStackView);

;// CONCATENATED MODULE: ./src/style_manager/view/PropertyFileView.ts
var PropertyFileView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var PropertyFileView_assign = (undefined && undefined.__assign) || function () {
    PropertyFileView_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return PropertyFileView_assign.apply(this, arguments);
};


var PropertyFileView = /** @class */ (function (_super) {
    PropertyFileView_extends(PropertyFileView, _super);
    function PropertyFileView() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    PropertyFileView.prototype.events = function () {
        return PropertyFileView_assign(PropertyFileView_assign({}, view_PropertyView.prototype.events()), { 'click [data-clear-asset]': 'clear', 'click [data-open-assets]': 'openAssetManager' });
    };
    PropertyFileView.prototype.templateInput = function () {
        var _a;
        var _b = this, pfx = _b.pfx, em = _b.em;
        var icons = (_a = this.em) === null || _a === void 0 ? void 0 : _a.getConfig().icons;
        var iconClose = icons === null || icons === void 0 ? void 0 : icons.close;
        return "\n      <div class=\"".concat(pfx, "field ").concat(pfx, "file\">\n        <div id='").concat(pfx, "input-holder'>\n          <div class=\"").concat(pfx, "btn-c\">\n            <button class=\"").concat(pfx, "btn\" id=\"").concat(pfx, "images\" type=\"button\" data-open-assets>\n              ").concat(em.t('styleManager.fileButton'), "\n            </button>\n          </div>\n          <div style=\"clear:both;\"></div>\n        </div>\n        <div id=\"").concat(pfx, "preview-box\" class=\"").concat(pfx, "preview-file\" data-preview-box>\n          <div id=\"").concat(pfx, "preview-file\" class=\"").concat(pfx, "preview-file-cnt\" data-preview></div>\n          <div id=\"").concat(pfx, "close\" class=\"").concat(pfx, "preview-file-close\" data-clear-asset>").concat(iconClose, "</div>\n        </div>\n      </div>\n    ");
    };
    PropertyFileView.prototype.__setValueInput = function (value) {
        var _a = this, model = _a.model, el = _a.el;
        var valueDef = model.getDefaultValue();
        var prvBoxEl = el.querySelector('[data-preview-box]');
        var prvEl = el.querySelector('[data-preview]');
        prvBoxEl.style.display = !value || value === valueDef ? 'none' : '';
        prvEl.style.backgroundImage = value || model.getDefaultValue();
    };
    PropertyFileView.prototype.openAssetManager = function () {
        var _this = this;
        var _a;
        var am = (_a = this.em) === null || _a === void 0 ? void 0 : _a.Assets;
        am === null || am === void 0 ? void 0 : am.open({
            select: function (asset, complete) {
                var url = (0,index_all.isString)(asset) ? asset : asset.get('src');
                _this.model.upValue(url, { partial: !complete });
                complete && am.close();
            },
            types: ['image'],
            accept: 'image/*',
        });
    };
    return PropertyFileView;
}(view_PropertyView));
/* harmony default export */ const view_PropertyFileView = (PropertyFileView);

;// CONCATENATED MODULE: ./src/style_manager/view/PropertyNumberView.ts
var PropertyNumberView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();

var PropertyNumberView = /** @class */ (function (_super) {
    PropertyNumberView_extends(PropertyNumberView, _super);
    function PropertyNumberView() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    PropertyNumberView.prototype.templateInput = function (m) {
        return '';
    };
    PropertyNumberView.prototype.init = function () {
        var model = this.model;
        this.listenTo(model, 'change:unit', this.onValueChange);
        this.listenTo(model, 'change:units', this.render);
    };
    PropertyNumberView.prototype.setValue = function (v) {
        // handled by this.inputInst
    };
    PropertyNumberView.prototype.onRender = function () {
        var _a = this, ppfx = _a.ppfx, model = _a.model, el = _a.el;
        if (!this.inputInst) {
            var input = model.input;
            input.ppfx = ppfx;
            input.render();
            var fields = el.querySelector(".".concat(ppfx, "fields"));
            fields.appendChild(input.el);
            this.input = input.inputEl.get(0);
            this.inputInst = input;
        }
    };
    PropertyNumberView.prototype.clearCached = function () {
        view_PropertyView.prototype.clearCached.apply(this, arguments);
        this.inputInst = null;
    };
    return PropertyNumberView;
}(view_PropertyView));
/* harmony default export */ const view_PropertyNumberView = (PropertyNumberView);

;// CONCATENATED MODULE: ./src/style_manager/view/PropertyColorView.ts
var PropertyColorView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();


var PropertyColorView = /** @class */ (function (_super) {
    PropertyColorView_extends(PropertyColorView, _super);
    function PropertyColorView() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    PropertyColorView.prototype.setValue = function (value) {
        var _a;
        (_a = this.inputInst) === null || _a === void 0 ? void 0 : _a.setValue(value, {
            fromTarget: 1,
            def: this.model.getDefaultValue(),
        });
    };
    PropertyColorView.prototype.remove = function () {
        var _this = this;
        view_PropertyNumberView.prototype.remove.apply(this, arguments);
        var inp = this.inputInst;
        inp && inp.remove && inp.remove();
        // @ts-ignore
        ['inputInst', '$color'].forEach(function (i) { return (_this[i] = null); });
        return this;
    };
    PropertyColorView.prototype.__handleChange = function (value, partial) {
        this.model.upValue(value, { partial: partial });
    };
    PropertyColorView.prototype.onRender = function () {
        var _a;
        if (!this.inputInst) {
            this.__handleChange = this.__handleChange.bind(this);
            var _b = this, ppfx = _b.ppfx, model = _b.model, em = _b.em, el = _b.el;
            var inputColor = new ui_InputColor({
                target: em,
                model: model,
                ppfx: ppfx,
                onChange: this.__handleChange,
            });
            var input = inputColor.render();
            el.querySelector(".".concat(ppfx, "fields")).appendChild(input.el);
            this.input = (_a = input.inputEl) === null || _a === void 0 ? void 0 : _a.get(0);
            this.inputInst = input;
        }
    };
    return PropertyColorView;
}(view_PropertyNumberView));
/* harmony default export */ const view_PropertyColorView = (PropertyColorView);

;// CONCATENATED MODULE: ./src/style_manager/model/PropertySelect.ts
var PropertySelect_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var PropertySelect_assign = (undefined && undefined.__assign) || function () {
    PropertySelect_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return PropertySelect_assign.apply(this, arguments);
};
var PropertySelect_spreadArray = (undefined && undefined.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};



/**
 * @typedef PropertySelect
 * @property {Array<Object>} options Array of option definitions.
 * \n
 * ```js
 * options: [
 *  { id: '100', label: 'Set 100' },
 *  { id: '200', label: 'Set 200' },
 * ]
 * ```
 */
var PropertySelect = /** @class */ (function (_super) {
    PropertySelect_extends(PropertySelect, _super);
    function PropertySelect() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    PropertySelect.prototype.defaults = function () {
        return PropertySelect_assign(PropertySelect_assign({}, model_Property.getDefaults()), { options: [], full: 0 });
    };
    /**
     * Get available options.
     * @returns {Array<Object>} Array of options
     */
    PropertySelect.prototype.getOptions = function () {
        // support old list property
        var _a = this.attributes, options = _a.options, list = _a.list;
        return (options && options.length ? options : list) || [];
    };
    /**
     * Get current selected option or by id.
     * @param {String} [id] Option id.
     * @returns {Object | null}
     */
    PropertySelect.prototype.getOption = function (id) {
        var _this = this;
        var idSel = (0,mixins.isDef)(id) ? id : this.getValue();
        return this.getOptions().filter(function (o) { return _this.getOptionId(o) === idSel; })[0] || null;
    };
    /**
     * Update options.
     * @param {Array<Object>} value New array of options, eg. `[{ id: 'val-1', label: 'Value 1' }]`
     */
    PropertySelect.prototype.setOptions = function (value) {
        if (value === void 0) { value = []; }
        this.set('options', value);
        return this;
    };
    /**
     * Add new option.
     * @param {Object} value Option object, eg. `{ id: 'val-1', label: 'Value 1' }`
     */
    PropertySelect.prototype.addOption = function (value) {
        if (value) {
            var opts = this.getOptions();
            this.setOptions(PropertySelect_spreadArray(PropertySelect_spreadArray([], opts, true), [value], false));
        }
        return this;
    };
    /**
     * Get the option id from the option object.
     * @param {Object} option Option object
     * @returns {String} Option id
     */
    PropertySelect.prototype.getOptionId = function (option) {
        return (0,mixins.isDef)(option.id) ? option.id : option.value;
    };
    /**
     * Get option label.
     * @param {String|Object} id Option id or the option object
     * @param {Object} [opts={}] Options
     * @param {Boolean} [opts.locale=true] Use the locale string from i18n module
     * @returns {String} Option label
     */
    PropertySelect.prototype.getOptionLabel = function (id, opts) {
        var _a;
        if (opts === void 0) { opts = {}; }
        var _b = opts.locale, locale = _b === void 0 ? true : _b;
        var option = ((0,index_all.isString)(id) ? this.getOption(id) : id) || {};
        var optId = this.getOptionId(option);
        var label = option.label || option.name || optId;
        var propId = opts.property || this.getId();
        return (locale && ((_a = this.em) === null || _a === void 0 ? void 0 : _a.t("styleManager.options.".concat(propId, ".").concat(optId)))) || label;
    };
    PropertySelect.prototype.initialize = function () {
        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            args[_i] = arguments[_i];
        }
        model_Property.prototype.initialize.apply(this, args);
        this.listenTo(this, 'change:options', this.__onOptionChange);
    };
    PropertySelect.prototype.__onOptionChange = function () {
        this.set('list', this.get('options'));
    };
    return PropertySelect;
}(model_Property));
/* harmony default export */ const model_PropertySelect = (PropertySelect);

;// CONCATENATED MODULE: ./src/style_manager/view/PropertySelectView.ts
var PropertySelectView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();

var PropertySelectView = /** @class */ (function (_super) {
    PropertySelectView_extends(PropertySelectView, _super);
    function PropertySelectView(o) {
        var _this = _super.call(this, o) || this;
        _this.listenTo(_this.model, 'change:options', _this.updateOptions);
        return _this;
    }
    PropertySelectView.prototype.templateInput = function () {
        var _a = this, pfx = _a.pfx, ppfx = _a.ppfx;
        return "\n      <div class=\"".concat(ppfx, "field ").concat(ppfx, "select\">\n        <span id=\"").concat(pfx, "input-holder\"></span>\n        <div class=\"").concat(ppfx, "sel-arrow\">\n          <div class=\"").concat(ppfx, "d-s-arrow\"></div>\n        </div>\n      </div>\n    ");
    };
    PropertySelectView.prototype.updateOptions = function () {
        delete this.input;
        this.onRender();
    };
    PropertySelectView.prototype.onRender = function () {
        var pfx = this.pfx;
        var model = this.model;
        var options = model.getOptions();
        if (!this.input) {
            var optionsRes_1 = [];
            options.forEach(function (option) {
                var id = model.getOptionId(option);
                var name = model.getOptionLabel(id);
                var style = option.style ? option.style.replace(/"/g, '&quot;') : '';
                var styleAttr = style ? "style=\"".concat(style, "\"") : '';
                var value = id.replace(/"/g, '&quot;');
                optionsRes_1.push("<option value=\"".concat(value, "\" ").concat(styleAttr, ">").concat(name, "</option>"));
            });
            var inputH = this.el.querySelector("#".concat(pfx, "input-holder"));
            inputH.innerHTML = "<select>".concat(optionsRes_1.join(''), "</select>");
            this.input = inputH.firstChild;
        }
    };
    PropertySelectView.prototype.__setValueInput = function (value) {
        var model = this.model;
        var input = this.getInputEl();
        var firstOpt = model.getOptions()[0];
        var firstId = firstOpt ? model.getOptionId(firstOpt) : '';
        input && (input.value = value || firstId);
    };
    return PropertySelectView;
}(view_PropertyView));
/* harmony default export */ const view_PropertySelectView = (PropertySelectView);

;// CONCATENATED MODULE: ./src/style_manager/model/PropertyRadio.ts
var PropertyRadio_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var PropertyRadio_assign = (undefined && undefined.__assign) || function () {
    PropertyRadio_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return PropertyRadio_assign.apply(this, arguments);
};

var PropertyRadio = /** @class */ (function (_super) {
    PropertyRadio_extends(PropertyRadio, _super);
    function PropertyRadio() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    PropertyRadio.prototype.defaults = function () {
        return PropertyRadio_assign(PropertyRadio_assign({}, model_PropertySelect.getDefaults()), { full: 1 });
    };
    return PropertyRadio;
}(model_PropertySelect));
/* harmony default export */ const model_PropertyRadio = (PropertyRadio);

;// CONCATENATED MODULE: ./src/style_manager/view/PropertyRadioView.ts
var PropertyRadioView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();

var PropertyRadioView = /** @class */ (function (_super) {
    PropertyRadioView_extends(PropertyRadioView, _super);
    function PropertyRadioView() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    PropertyRadioView.prototype.templateInput = function () {
        var ppfx = this.ppfx;
        return "<div class=\"".concat(ppfx, "field ").concat(ppfx, "field-radio\"></div>");
    };
    PropertyRadioView.prototype.onRender = function () {
        var _a = this, pfx = _a.pfx, ppfx = _a.ppfx;
        var model = this.model;
        var itemCls = "".concat(ppfx, "radio-item-label");
        var prop = model.getName();
        var options = model.getOptions();
        var clsInput = "".concat(pfx, "radio ").concat(pfx, "radio-").concat(prop);
        var cid = model.cid;
        if (!this.input) {
            var optionsRes_1 = [];
            options.forEach(function (opt) {
                var cls = opt.className ? "".concat(opt.className, " ").concat(pfx, "icon ").concat(itemCls) : '';
                var id = model.getOptionId(opt);
                var elId = "".concat(prop, "-").concat(id, "-").concat(cid);
                var labelEl = cls ? '' : model.getOptionLabel(id);
                var titleAttr = opt.title ? "title=\"".concat(opt.title, "\"") : '';
                var checked = model.getValue() === id ? 'checked' : '';
                optionsRes_1.push("\n          <div class=\"".concat(ppfx, "radio-item\">\n            <input type=\"radio\" class=\"").concat(clsInput, "\" id=\"").concat(elId, "\" name=\"").concat(prop, "-").concat(cid, "\" value=\"").concat(id, "\" ").concat(checked, "/>\n            <label class=\"").concat(cls || itemCls, "\" ").concat(titleAttr, " for=\"").concat(elId, "\">").concat(labelEl, "</label>\n          </div>\n        "));
            });
            var inputHld = this.el.querySelector(".".concat(ppfx, "field"));
            inputHld.innerHTML = "<div class=\"".concat(ppfx, "radio-items\">").concat(optionsRes_1.join(''), "</div>");
            this.input = inputHld.firstChild;
        }
    };
    PropertyRadioView.prototype.__setValueInput = function (value) {
        var _a;
        var model = this.model;
        var id = value || model.getDefaultValue();
        var inputIn = (_a = this.getInputEl()) === null || _a === void 0 ? void 0 : _a.querySelector("[value=\"".concat(id, "\"]"));
        inputIn && (inputIn.checked = true);
    };
    return PropertyRadioView;
}(view_PropertySelectView));
/* harmony default export */ const view_PropertyRadioView = (PropertyRadioView);

;// CONCATENATED MODULE: ./src/style_manager/model/PropertyNumber.ts
var PropertyNumber_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var PropertyNumber_assign = (undefined && undefined.__assign) || function () {
    PropertyNumber_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return PropertyNumber_assign.apply(this, arguments);
};




/**
 * @typedef PropertyNumber
 * @property {Array<String>} units Array of units, eg. `['px', '%']`
 * @property {Number} min Minimum value.
 * @property {Number} max Maximum value.
 * @property {Number} step Step value.
 *
 */
var PropertyNumber = /** @class */ (function (_super) {
    PropertyNumber_extends(PropertyNumber, _super);
    function PropertyNumber() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    PropertyNumber.prototype.defaults = function () {
        return PropertyNumber_assign(PropertyNumber_assign({}, model_Property.getDefaults()), { units: [], unit: '', min: '', max: '', step: 1 });
    };
    /**
     * Get property units.
     * @returns {Array<String>}
     */
    PropertyNumber.prototype.getUnits = function () {
        return this.get('units') || [];
    };
    /**
     * Get property unit value.
     * @returns {String}
     */
    PropertyNumber.prototype.getUnit = function () {
        return this.get('unit');
    };
    /**
     * Get min value.
     * @returns {Number}
     */
    PropertyNumber.prototype.getMin = function () {
        return this.get('min');
    };
    /**
     * Get max value.
     * @returns {Number}
     */
    PropertyNumber.prototype.getMax = function () {
        return this.get('max');
    };
    /**
     * Get step value.
     * @returns {Number}
     */
    PropertyNumber.prototype.getStep = function () {
        return this.get('step');
    };
    /**
     * Update property unit value.
     * The change is also propagated to the selected targets.
     * @param {String} unit New unit value
     * @param {Object} [opts={}] Options
     * @param {Boolean} [opts.noTarget=false] If `true` the change won't be propagated to selected targets.
     * @returns {String}
     */
    PropertyNumber.prototype.upUnit = function (unit, opts) {
        if (opts === void 0) { opts = {}; }
        return this._up({ unit: unit }, opts);
    };
    PropertyNumber.prototype.initialize = function (props, opts) {
        if (props === void 0) { props = {}; }
        if (opts === void 0) { opts = {}; }
        // @ts-ignore
        model_Property.callParentInit(model_Property, this, props, opts);
        var unit = this.get('unit');
        var units = this.getUnits();
        this.input = (0,mixins.hasWin)() ? new ui_InputNumber({ model: this }) : undefined;
        if (units.length && !unit) {
            this.set('unit', units[0], { silent: true });
        }
        // @ts-ignore
        model_Property.callInit(this, props, opts);
    };
    PropertyNumber.prototype.__getClearProps = function () {
        return PropertyNumber_assign(PropertyNumber_assign({}, model_Property.prototype.__getClearProps()), { unit: '' });
    };
    PropertyNumber.prototype.parseValue = function (val, opts) {
        if (opts === void 0) { opts = {}; }
        var parsed = model_Property.prototype.parseValue.apply(this, arguments);
        var _a = this.input.validateInputValue(parsed.value, PropertyNumber_assign({ deepCheck: 1 }, opts)), value = _a.value, unit = _a.unit;
        parsed.value = value;
        parsed.unit = unit;
        return parsed;
    };
    PropertyNumber.prototype.getFullValue = function () {
        var valueProp = this.get('value');
        var unitProp = this.get('unit');
        var value = !(0,index_all.isUndefined)(valueProp) ? "".concat(valueProp) : '';
        var unit = !(0,index_all.isUndefined)(unitProp) && value ? unitProp : '';
        var result = "".concat(value).concat(unit);
        return model_Property.prototype.getFullValue.apply(this, [result]);
    };
    return PropertyNumber;
}(model_Property));
/* harmony default export */ const model_PropertyNumber = (PropertyNumber);

;// CONCATENATED MODULE: ./src/style_manager/model/PropertySlider.ts
var PropertySlider_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var PropertySlider_assign = (undefined && undefined.__assign) || function () {
    PropertySlider_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return PropertySlider_assign.apply(this, arguments);
};

var PropertySlider = /** @class */ (function (_super) {
    PropertySlider_extends(PropertySlider, _super);
    function PropertySlider() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    PropertySlider.prototype.defaults = function () {
        return PropertySlider_assign(PropertySlider_assign({}, model_PropertyNumber.getDefaults()), { showInput: 1 });
    };
    return PropertySlider;
}(model_PropertyNumber));
/* harmony default export */ const model_PropertySlider = (PropertySlider);

;// CONCATENATED MODULE: ./src/style_manager/view/PropertySliderView.ts
var PropertySliderView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var PropertySliderView_assign = (undefined && undefined.__assign) || function () {
    PropertySliderView_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return PropertySliderView_assign.apply(this, arguments);
};

var PropertySliderView = /** @class */ (function (_super) {
    PropertySliderView_extends(PropertySliderView, _super);
    function PropertySliderView() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    PropertySliderView.prototype.events = function () {
        return PropertySliderView_assign(PropertySliderView_assign({}, view_PropertyNumberView.prototype.events()), { 'change [type=range]': 'inputValueChanged', 'input [type=range]': 'inputValueChangedSoft', change: '' });
    };
    PropertySliderView.prototype.templateInput = function (model) {
        var ppfx = this.ppfx;
        return "\n      <div class=\"".concat(ppfx, "field ").concat(ppfx, "field-range\">\n        <input type=\"range\" min=\"").concat(model.get('min'), "\" max=\"").concat(model.get('max'), "\" step=\"").concat(model.get('step'), "\"/>\n      </div>\n    ");
    };
    PropertySliderView.prototype.getSliderEl = function () {
        if (!this.slider) {
            this.slider = this.el.querySelector('input[type=range]');
        }
        return this.slider;
    };
    PropertySliderView.prototype.inputValueChanged = function (ev) {
        ev.stopPropagation();
        this.model.upValue(this.getSliderEl().value);
    };
    PropertySliderView.prototype.inputValueChangedSoft = function (ev) {
        ev.stopPropagation();
        this.model.upValue(this.getSliderEl().value, { partial: true });
    };
    PropertySliderView.prototype.setValue = function (value) {
        var model = this.model;
        var parsed = model.parseValue(value);
        // @ts-ignore
        this.getSliderEl().value = value === '' ? model.getDefaultValue() : parseFloat(parsed.value);
        view_PropertyNumberView.prototype.setValue.apply(this, arguments);
    };
    PropertySliderView.prototype.onRender = function () {
        view_PropertyNumberView.prototype.onRender.apply(this, arguments);
        // @ts-ignore
        if (!this.model.get('showInput')) {
            this.inputInst.el.style.display = 'none';
        }
    };
    PropertySliderView.prototype.clearCached = function () {
        view_PropertyNumberView.prototype.clearCached.apply(this, arguments);
        delete this.slider;
    };
    return PropertySliderView;
}(view_PropertyNumberView));
/* harmony default export */ const view_PropertySliderView = (PropertySliderView);

;// CONCATENATED MODULE: ./src/style_manager/model/Properties.ts


















var Properties_TypeableCollectionExt = common/* Collection */.FE.extend(model_TypeableCollection);
var Properties = Properties_TypeableCollectionExt.extend({
    extendViewApi: 1,
    init: function () {
        var _a = this, opts = _a.opts, em = _a.em;
        var sm = opts.module || (em === null || em === void 0 ? void 0 : em.get('StyleManager'));
        if (sm) {
            sm.__listenAdd(this, sm.events.propertyAdd);
            sm.__listenRemove(this, sm.events.propertyRemove);
        }
    },
    types: [
        {
            id: 'stack',
            model: model_PropertyStack,
            view: view_PropertyStackView,
            isType: function (value) {
                if (value && value.type == 'stack') {
                    return value;
                }
            },
        },
        {
            id: 'composite',
            model: model_PropertyComposite,
            view: view_PropertyCompositeView,
            isType: function (value) {
                if (value && value.type == 'composite') {
                    return value;
                }
            },
        },
        {
            id: 'file',
            model: model_Property,
            view: view_PropertyFileView,
            isType: function (value) {
                if (value && value.type == 'file') {
                    return value;
                }
            },
        },
        {
            id: 'color',
            model: model_Property,
            view: view_PropertyColorView,
            isType: function (value) {
                if (value && value.type == 'color') {
                    return value;
                }
            },
        },
        {
            id: 'select',
            model: model_PropertySelect,
            view: view_PropertySelectView,
            isType: function (value) {
                if (value && value.type == 'select') {
                    return value;
                }
            },
        },
        {
            id: 'radio',
            model: model_PropertyRadio,
            view: view_PropertyRadioView,
            isType: function (value) {
                if (value && value.type == 'radio') {
                    return value;
                }
            },
        },
        {
            id: 'slider',
            model: model_PropertySlider,
            view: view_PropertySliderView,
            isType: function (value) {
                if (value && value.type == 'slider') {
                    return value;
                }
            },
        },
        {
            id: 'integer',
            model: model_PropertyNumber,
            view: view_PropertyNumberView,
            isType: function (value) {
                if (value && value.type == 'integer') {
                    return value;
                }
            },
        },
        {
            id: 'number',
            model: model_PropertyNumber,
            view: view_PropertyNumberView,
            isType: function (value) {
                if (value && value.type == 'number') {
                    return value;
                }
            },
        },
        {
            id: 'base',
            model: model_Property,
            view: view_PropertyView,
            isType: function (value) {
                value.type = 'base';
                return value;
            },
        },
    ],
});
/* harmony default export */ const model_Properties = (Properties);

;// CONCATENATED MODULE: ./src/style_manager/model/Sector.ts
var Sector_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var Sector_assign = (undefined && undefined.__assign) || function () {
    Sector_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return Sector_assign.apply(this, arguments);
};
var Sector_rest = (undefined && undefined.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
var Sector_spreadArray = (undefined && undefined.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};



/**
 *
 * [Property]: property.html
 *
 * @typedef Sector
 * @property {String} id Sector id, eg. `typography`
 * @property {String} name Sector name, eg. `Typography`
 * @property {Boolean} [open=true] Indicates the open state.
 * @property {Array<Object>} [properties=[]] Indicate an array of Property defintions.
 */
var Sector = /** @class */ (function (_super) {
    Sector_extends(Sector, _super);
    /**
     * @hideconstructor
     */
    function Sector(prp, opts) {
        if (opts === void 0) { opts = {}; }
        var _this = _super.call(this, prp) || this;
        var em = opts.em;
        _this.em = em;
        var o = prp || {};
        var builded = _this.buildProperties(o.buildProps);
        var name = _this.get('name') || '';
        var props = [];
        !_this.get('id') && _this.set('id', name.replace(/ /g, '_').toLowerCase());
        if (!builded) {
            props = _this.get('properties')
                .map(function (prop) { return ((0,index_all.isString)(prop) ? _this.buildProperties(prop)[0] : prop); })
                .filter(Boolean);
        }
        else {
            props = _this.extendProperties(builded);
        }
        props = props.map(function (prop) { return _this.checkExtend(prop); });
        var propsModel = new model_Properties(props, { em: em });
        propsModel.sector = _this;
        _this.set('properties', propsModel);
        return _this;
    }
    Sector.prototype.defaults = function () {
        return {
            id: '',
            name: '',
            open: true,
            visible: true,
            extendBuilded: true,
            properties: [],
        };
    };
    Object.defineProperty(Sector.prototype, "properties", {
        get: function () {
            return this.get('properties');
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Get sector id.
     * @returns {String}
     */
    Sector.prototype.getId = function () {
        return this.get('id');
    };
    /**
     * Get sector name.
     * @returns {String}
     */
    Sector.prototype.getName = function () {
        var _a;
        var id = this.getId();
        return ((_a = this.em) === null || _a === void 0 ? void 0 : _a.t("styleManager.sectors.".concat(id))) || this.get('name');
    };
    /**
     * Update sector name.
     * @param {String} value New sector name
     */
    Sector.prototype.setName = function (value) {
        return this.set('name', value);
    };
    /**
     * Check if the sector is open
     * @returns {Boolean}
     */
    Sector.prototype.isOpen = function () {
        return !!this.get('open');
    };
    /**
     * Update Sector open state
     * @param {Boolean} value
     */
    Sector.prototype.setOpen = function (value) {
        return this.set('open', value);
    };
    /**
     * Check if the sector is visible
     * @returns {Boolean}
     */
    Sector.prototype.isVisible = function () {
        return !!this.get('visible');
    };
    /**
     * Get sector properties.
     * @param {Object} [opts={}] Options
     * @param {Boolean} [opts.withValue=false] Get only properties with value
     * @param {Boolean} [opts.withParentValue=false] Get only properties with parent value
     * @returns {Array<[Property]>}
     */
    Sector.prototype.getProperties = function (opts) {
        if (opts === void 0) { opts = {}; }
        var props = this.properties;
        var res = (props.models ? Sector_spreadArray([], props.models, true) : props);
        return res.filter(function (prop) {
            var result = true;
            if (opts.withValue) {
                result = prop.hasValue({ noParent: true });
            }
            if (opts.withParentValue) {
                var hasVal = prop.hasValue({ noParent: true });
                result = !hasVal && prop.hasValue();
            }
            return result;
        });
    };
    Sector.prototype.getProperty = function (id) {
        return this.getProperties().filter(function (prop) { return prop.get('id') === id; })[0] || undefined;
    };
    Sector.prototype.addProperty = function (property, opts) {
        return this.properties.add(this.checkExtend(property), opts);
    };
    /**
     * Extend properties
     * @param {Array<Object>} props Start properties
     * @param {Array<Object>} moProps Model props
     * @param {Boolean} ex Returns the same amount of passed model props
     * @return {Array<Object>} Final props
     * @private
     */
    Sector.prototype.extendProperties = function (props, moProps, ex) {
        if (ex === void 0) { ex = false; }
        var pLen = props.length;
        var mProps = moProps || this.get('properties');
        var ext = this.get('extendBuilded');
        var isolated = [];
        for (var i = 0, len = mProps.length; i < len; i++) {
            var mProp = mProps[i];
            var found = 0;
            for (var j = 0; j < pLen; j++) {
                var prop = props[j];
                if (mProp.property == prop.property || mProp.id == prop.property) {
                    // @ts-ignore Check for nested properties
                    var mPProps = mProp.properties;
                    if (mPProps && mPProps.length) {
                        // @ts-ignore
                        mProp.properties = this.extendProperties(prop.properties || [], mPProps, 1);
                    }
                    props[j] = ext ? (0,index_all.extend)(prop, mProp) : mProp;
                    isolated[j] = props[j];
                    found = 1;
                    continue;
                }
            }
            if (!found) {
                props.push(mProp);
                isolated.push(mProp);
            }
        }
        return ex ? isolated.filter(function (i) { return i; }) : props;
    };
    Sector.prototype.checkExtend = function (prop) {
        var _a = ((0,index_all.isString)(prop) ? { extend: prop } : prop) || {}, extend = _a.extend, rest = Sector_rest(_a, ["extend"]);
        if (extend) {
            return Sector_assign(Sector_assign({}, (this.buildProperties([extend])[0] || {})), rest);
        }
        else {
            return prop;
        }
    };
    /**
     * Build properties
     * @param {Array<string>} propr Array of props as sting
     * @return {Array<Object>}
     * @private
     */
    Sector.prototype.buildProperties = function (props) {
        var _a;
        var buildP = props || [];
        if (!buildP.length)
            return [];
        var builtIn = (_a = this.em) === null || _a === void 0 ? void 0 : _a.Styles.builtIn;
        return builtIn === null || builtIn === void 0 ? void 0 : builtIn.build(buildP);
    };
    return Sector;
}(common/* Model */.Hn));
/* harmony default export */ const model_Sector = (Sector);

;// CONCATENATED MODULE: ./src/style_manager/model/Sectors.ts
var Sectors_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var Sectors_assign = (undefined && undefined.__assign) || function () {
    Sectors_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return Sectors_assign.apply(this, arguments);
};


var Sectors = /** @class */ (function (_super) {
    Sectors_extends(Sectors, _super);
    function Sectors() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Sectors.prototype.initialize = function (prop, opts) {
        if (opts === void 0) { opts = {}; }
        var module = opts.module, em = opts.em;
        this.em = em;
        this.module = module;
        this.listenTo(this, 'reset', this.onReset);
    };
    /** @ts-ignore */
    Sectors.prototype.model = function (props, opts) {
        if (opts === void 0) { opts = {}; }
        // @ts-ignore
        var em = opts.collection.em;
        return new model_Sector(props, Sectors_assign(Sectors_assign({}, opts), { em: em }));
    };
    Sectors.prototype.onReset = function (models, opts) {
        if (opts === void 0) { opts = {}; }
        var prev = opts.previousModels || [];
        // @ts-ignore
        prev.forEach(function (sect) { return sect.get('properties').reset(); });
    };
    return Sectors;
}(common/* Collection */.FE));
/* harmony default export */ const model_Sectors = (Sectors);

;// CONCATENATED MODULE: ./src/style_manager/model/PropertyFactory.ts
var PropertyFactory_assign = (undefined && undefined.__assign) || function () {
    PropertyFactory_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return PropertyFactory_assign.apply(this, arguments);
};
var PropertyFactory_rest = (undefined && undefined.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
var PropertyFactory_spreadArray = (undefined && undefined.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};

var getOptions = function (items) { return items.map(function (item) { return ({ id: item }); }); };
var PropertyFactory = /** @class */ (function () {
    function PropertyFactory() {
        this.props = {};
        this.typeNumber = 'number';
        this.typeColor = 'color';
        this.typeRadio = 'radio';
        this.typeSelect = 'select';
        this.typeFile = 'file';
        this.typeSlider = 'slider';
        this.typeComposite = 'composite';
        this.typeStack = 'stack';
        this.unitsSize = ['px', '%', 'em', 'rem', 'vh', 'vw'];
        this.unitsSizeNoPerc = ['px', 'em', 'rem', 'vh', 'vw'];
        this.unitsTime = ['s', 'ms'];
        this.unitsAngle = ['deg', 'rad', 'grad'];
        this.fixedValues = ['initial', 'inherit', 'auto'];
        var ss = ', sans-serif';
        var optsFlex = ['flex-start', 'flex-end', 'center'];
        var optsFlexAlign = PropertyFactory_spreadArray(PropertyFactory_spreadArray([], optsFlex, true), ['baseline', 'stretch'], false);
        this.optsBgSize = getOptions(['auto', 'cover', 'contain']);
        this.optsBgAttach = getOptions(['scroll', 'fixed', 'local']);
        this.optsBgRepeat = getOptions(['repeat', 'repeat-x', 'repeat-y', 'no-repeat']);
        this.optsWrap = getOptions(['nowrap', 'wrap', 'wrap-reverse']);
        this.optsOverflow = getOptions(['visible', 'hidden', 'scroll', 'auto']);
        this.optsDir = getOptions(['row', 'row-reverse', 'column', 'column-reverse']);
        this.opstDisplay = getOptions(['block', 'inline', 'inline-block', 'flex', 'none']);
        this.optsTransitFn = getOptions(['linear', 'ease', 'ease-in', 'ease-out', 'ease-in-out']);
        this.optsCursor = getOptions(['auto', 'pointer', 'copy', 'crosshair', 'grab', 'grabbing', 'help', 'move', 'text']);
        this.optsFloat = getOptions(['none', 'left', 'right']);
        this.optsPos = getOptions(['static', 'relative', 'absolute', 'fixed']);
        this.optsTextAlign = getOptions(['left', 'center', 'right', 'justify']);
        this.optsFlexAlign = getOptions(optsFlexAlign);
        this.optsJustCont = getOptions(PropertyFactory_spreadArray(PropertyFactory_spreadArray([], optsFlex, true), ['space-between', 'space-around', 'space-evenly'], false));
        this.optsAlignCont = getOptions(PropertyFactory_spreadArray(PropertyFactory_spreadArray([], optsFlex, true), ['space-between', 'space-around', 'stretch'], false));
        this.optsAlignSelf = getOptions(PropertyFactory_spreadArray(['auto'], optsFlexAlign, true));
        this.optsTransitProp = getOptions([
            'all',
            'width',
            'height',
            'background-color',
            'transform',
            'box-shadow',
            'opacity',
        ]);
        this.optsBorderStyle = getOptions([
            'none',
            'solid',
            'dotted',
            'dashed',
            'double',
            'groove',
            'ridge',
            'inset',
            'outset',
        ]);
        this.optsBgPos = getOptions([
            'left top',
            'left center',
            'left bottom',
            'right top',
            'right center',
            'right bottom',
            'center top',
            'center center',
            'center bottom',
        ]);
        this.optsWeight = [
            { id: '100', label: 'Thin' },
            { id: '200', label: 'Extra-Light' },
            { id: '300', label: 'Light' },
            { id: '400', label: 'Normal' },
            { id: '500', label: 'Medium' },
            { id: '600', label: 'Semi-Bold' },
            { id: '700', label: 'Bold' },
            { id: '800', label: 'Extra-Bold' },
            { id: '900', label: 'Ultra-Bold' },
        ];
        this.optsShadowType = [
            { id: '', label: 'Outside' },
            { id: 'inset', label: 'Inside' },
        ];
        this.optsFonts = [
            'Arial, Helvetica' + ss,
            'Arial Black, Gadget' + ss,
            'Brush Script MT' + ss,
            'Comic Sans MS, cursive' + ss,
            'Courier New, Courier, monospace',
            'Georgia, serif',
            'Helvetica' + ss,
            'Impact, Charcoal' + ss,
            'Lucida Sans Unicode, Lucida Grande' + ss,
            'Tahoma, Geneva' + ss,
            'Times New Roman, Times, serif',
            'Trebuchet MS, Helvetica' + ss,
            'Verdana, Geneva' + ss,
        ].map(function (font) {
            return { id: font, label: font.split(',')[0] };
        });
        // Fixed values
        this.fixedFontSizes = [
            'medium',
            'xx-small',
            'x-small',
            'small',
            'large',
            'x-large',
            'xx-large',
            'smaller',
            'larger',
            'length',
            'initial',
            'inherit',
        ];
        this.fixedLetSpace = ['normal', 'initial', 'inherit'];
        this.requireFlex = { display: ['flex'] };
        this.init();
    }
    PropertyFactory.prototype.__sub = function (items) {
        var _this = this;
        return function () {
            return items.map(function (p) {
                if ((0,index_all.isString)(p))
                    return _this.get(p);
                var extend = p.extend, rest = PropertyFactory_rest(p, ["extend"]);
                return PropertyFactory_assign(PropertyFactory_assign({}, _this.get(extend)), rest);
            });
        };
    };
    PropertyFactory.prototype.init = function () {
        var _this = this;
        var _a = this, fixedValues = _a.fixedValues, requireFlex = _a.requireFlex, typeNumber = _a.typeNumber;
        this.props = {};
        // Build default built-in properties (the order, in the array here below, matters)
        // [propertyName, propertyDefinition, extendFromProperty]
        var propsToCreate = [
            // Number types
            ['text-shadow-h', { type: typeNumber, default: '0', units: this.unitsSizeNoPerc }],
            ['top', { default: 'auto', units: this.unitsSize, fixedValues: fixedValues }, 'text-shadow-h'],
            ['right', {}, 'top'],
            ['bottom', {}, 'top'],
            ['left', {}, 'top'],
            ['margin-top', { default: '0' }, 'top'],
            ['margin-right', {}, 'margin-top'],
            ['margin-bottom', {}, 'margin-top'],
            ['margin-left', {}, 'margin-top'],
            ['padding-top', { min: 0 }, 'margin-top'],
            ['padding-right', {}, 'padding-top'],
            ['padding-bottom', {}, 'padding-top'],
            ['padding-left', {}, 'padding-top'],
            ['width', { min: 0 }, 'top'],
            ['min-width', {}, 'width'],
            ['max-width', {}, 'width'],
            ['height', {}, 'width'],
            ['min-height', {}, 'width'],
            ['max-height', {}, 'width'],
            ['flex-basis', { requiresParent: requireFlex }, 'width'],
            ['font-size', { default: 'medium', fixedValues: this.fixedFontSizes }, 'width'],
            ['letter-spacing', { default: 'normal', fixedValues: this.fixedLetSpace }, 'top'],
            ['line-height', {}, 'letter-spacing'],
            ['text-shadow-v', {}, 'text-shadow-h'],
            ['text-shadow-blur', { min: 0 }, 'text-shadow-h'],
            ['border-radius-c', { property: 'border-radius', fixedValues: undefined }, 'padding-top'],
            ['border-top-left-radius', {}, 'border-radius-c'],
            ['border-top-right-radius', {}, 'border-radius-c'],
            ['border-bottom-left-radius', {}, 'border-radius-c'],
            ['border-bottom-right-radius', {}, 'border-radius-c'],
            ['border-width', { units: this.unitsSizeNoPerc }, 'border-radius-c'],
            ['box-shadow-h', {}, 'text-shadow-h'],
            ['box-shadow-v', {}, 'text-shadow-h'],
            ['box-shadow-blur', { default: '5px' }, 'text-shadow-blur'],
            ['box-shadow-spread', {}, 'text-shadow-h'],
            ['transition-duration', { default: '2s', units: this.unitsTime }, 'border-radius-c'],
            ['perspective', {}, 'border-radius-c'],
            ['order', { type: typeNumber, default: '0', requiresParent: requireFlex }],
            ['flex-grow', {}, 'order'],
            ['flex-shrink', { default: '1' }, 'order'],
            // Radio types
            ['float', { type: this.typeRadio, default: 'none', options: this.optsFloat }],
            ['position', { default: 'static', options: this.optsPos }, 'float'],
            ['text-align', { default: 'left', options: this.optsTextAlign }, 'float'],
            // Color types
            ['color', { type: this.typeColor, default: 'black', full: true }],
            ['text-shadow-color', {}, 'color'],
            ['border-color', {}, 'color'],
            ['box-shadow-color', {}, 'color'],
            ['background-color', { default: 'none' }, 'color'],
            // File type
            [
                'background-image',
                {
                    type: this.typeFile,
                    functionName: 'url',
                    default: 'none',
                    full: true,
                },
            ],
            // Slider type
            ['opacity', { type: this.typeSlider, default: '1', min: 0, max: 1, step: 0.01, full: true }],
            // Select types
            ['display', { type: this.typeSelect, default: 'block', options: this.opstDisplay }],
            ['flex-direction', { default: 'row', options: this.optsDir, requires: requireFlex }, 'display'],
            ['flex-wrap', { default: 'nowrap', options: this.optsWrap }, 'flex-direction'],
            ['justify-content', { default: 'flex-start', options: this.optsJustCont }, 'flex-wrap'],
            ['align-items', { default: 'stretch', options: this.optsFlexAlign }, 'flex-wrap'],
            ['align-content', { options: this.optsAlignCont }, 'align-items'],
            [
                'align-self',
                {
                    default: 'auto',
                    options: this.optsAlignSelf,
                    requiresParent: requireFlex,
                },
                'display',
            ],
            ['font-family', { default: 'Arial, Helvetica, sans-serif', options: this.optsFonts }, 'display'],
            ['font-weight', { default: '400', options: this.optsWeight }, 'display'],
            ['border-style', { default: 'solid', options: this.optsBorderStyle }, 'display'],
            ['box-shadow-type', { default: '', options: this.optsShadowType }, 'display'],
            ['background-repeat', { default: 'repeat', options: this.optsBgRepeat }, 'display'],
            ['background-position', { default: 'left top', options: this.optsBgPos }, 'display'],
            ['background-attachment', { default: 'scroll', options: this.optsBgAttach }, 'display'],
            ['background-size', { default: 'auto', options: this.optsBgSize }, 'display'],
            ['transition-property', { default: 'width', options: this.optsTransitProp }, 'display'],
            ['transition-timing-function', { default: 'ease', options: this.optsTransitFn }, 'display'],
            ['cursor', { default: 'auto', options: this.optsCursor }, 'display'],
            ['overflow', { default: 'visible', options: this.optsOverflow }, 'display'],
            ['overflow-x', {}, 'overflow'],
            ['overflow-y', {}, 'overflow'],
            // Composite types
            [
                'margin',
                {
                    type: this.typeComposite,
                    properties: this.__sub([
                        { extend: 'margin-top', id: 'margin-top-sub' },
                        { extend: 'margin-right', id: 'margin-right-sub' },
                        { extend: 'margin-bottom', id: 'margin-bottom-sub' },
                        { extend: 'margin-left', id: 'margin-left-sub' },
                    ]),
                },
            ],
            [
                'padding',
                {
                    properties: this.__sub([
                        { extend: 'padding-top', id: 'padding-top-sub' },
                        { extend: 'padding-right', id: 'padding-right-sub' },
                        { extend: 'padding-bottom', id: 'padding-bottom-sub' },
                        { extend: 'padding-left', id: 'padding-left-sub' },
                    ]),
                },
                'margin',
            ],
            [
                'border',
                {
                    properties: this.__sub([
                        { extend: 'border-width', id: 'border-width-sub' },
                        { extend: 'border-style', id: 'border-style-sub' },
                        { extend: 'border-color', id: 'border-color-sub' },
                    ]),
                },
                'margin',
            ],
            [
                'border-radius',
                {
                    properties: this.__sub([
                        {
                            extend: 'border-top-left-radius',
                            id: 'border-top-left-radius-sub',
                        },
                        {
                            extend: 'border-top-right-radius',
                            id: 'border-top-right-radius-sub',
                        },
                        {
                            extend: 'border-bottom-right-radius',
                            id: 'border-bottom-right-radius-sub',
                        },
                        {
                            extend: 'border-bottom-left-radius',
                            id: 'border-bottom-left-radius-sub',
                        },
                    ]),
                },
                'margin',
            ],
            // Stack types
            [
                'transition',
                {
                    type: this.typeStack,
                    properties: this.__sub([
                        { extend: 'transition-property', id: 'transition-property-sub' },
                        { extend: 'transition-duration', id: 'transition-duration-sub' },
                        {
                            extend: 'transition-timing-function',
                            id: 'transition-timing-function-sub',
                        },
                    ]),
                },
            ],
            [
                'box-shadow',
                {
                    preview: true,
                    layerLabel: function (l, _a) {
                        var values = _a.values;
                        var x = values['box-shadow-h'];
                        var y = values['box-shadow-v'];
                        var blur = values['box-shadow-blur'];
                        var spread = values['box-shadow-spread'];
                        return "".concat(x, " ").concat(y, " ").concat(blur, " ").concat(spread);
                    },
                    properties: this.__sub([
                        'box-shadow-h',
                        'box-shadow-v',
                        'box-shadow-blur',
                        'box-shadow-spread',
                        'box-shadow-color',
                        'box-shadow-type',
                    ]),
                },
                'transition',
            ],
            [
                'text-shadow',
                {
                    default: 'none',
                    layerLabel: function (l, _a) {
                        var values = _a.values;
                        var x = values['text-shadow-h'];
                        var y = values['text-shadow-v'];
                        var blur = values['text-shadow-blur'];
                        return "".concat(x, " ").concat(y, " ").concat(blur);
                    },
                    properties: this.__sub(['text-shadow-h', 'text-shadow-v', 'text-shadow-blur', 'text-shadow-color']),
                },
                'box-shadow',
            ],
            [
                'background',
                {
                    detached: true,
                    layerLabel: function (l, _a) {
                        var values = _a.values;
                        var repeat = values['background-repeat-sub'] || '';
                        var pos = values['background-position-sub'] || '';
                        var att = values['background-attachment-sub'] || '';
                        var size = values['background-size-sub'] || '';
                        return [repeat, pos, att, size].join(' ');
                    },
                    properties: this.__sub([
                        { extend: 'background-image', id: 'background-image-sub' },
                        { extend: 'background-repeat', id: 'background-repeat-sub' },
                        { extend: 'background-position', id: 'background-position-sub' },
                        {
                            extend: 'background-attachment',
                            id: 'background-attachment-sub',
                        },
                        { extend: 'background-size', id: 'background-size-sub' },
                    ]),
                },
                'box-shadow',
            ],
            [
                'transform',
                {
                    type: 'stack',
                    layerSeparator: ' ',
                    fromStyle: function (style, _a) {
                        var property = _a.property, name = _a.name;
                        var filter = (style[name] || '');
                        var sep = property.getLayerSeparator();
                        return filter
                            ? filter.split(sep).map(function (input) {
                                var _a = property.__parseFn(input), name = _a.name, value = _a.value;
                                return {
                                    'transform-type': name,
                                    'transform-value': value,
                                };
                            })
                            : [];
                    },
                    toStyle: function (values, _a) {
                        var _b;
                        var name = _a.name;
                        return _b = {}, _b[name] = "".concat(values['transform-type'], "(").concat(values['transform-value'], ")"), _b;
                    },
                    properties: [
                        {
                            property: 'transform-type',
                            name: 'Type',
                            type: this.typeSelect,
                            default: 'rotateZ',
                            full: true,
                            options: [
                                { id: 'scaleX', propValue: { units: [''], step: 0.01 } },
                                { id: 'scaleY', propValue: { units: [''], step: 0.01 } },
                                { id: 'scaleZ', propValue: { units: [''], step: 0.01 } },
                                {
                                    id: 'rotateX',
                                    propValue: { units: this.unitsAngle, step: 1 },
                                },
                                {
                                    id: 'rotateY',
                                    propValue: { units: this.unitsAngle, step: 1 },
                                },
                                {
                                    id: 'rotateZ',
                                    propValue: { units: this.unitsAngle, step: 1 },
                                },
                                {
                                    id: 'translateX',
                                    propValue: { units: this.unitsSize, step: 1 },
                                },
                                {
                                    id: 'translateY',
                                    propValue: { units: this.unitsSize, step: 1 },
                                },
                            ],
                            onChange: function (_a) {
                                var property = _a.property, to = _a.to;
                                if (to.value) {
                                    var option = property.getOption();
                                    var props = PropertyFactory_assign({}, (option.propValue || {}));
                                    var propToUp = property.getParent().getProperty('transform-value');
                                    var unit = propToUp.getUnit();
                                    if (!unit || (props === null || props === void 0 ? void 0 : props.units.indexOf(unit)) < 0) {
                                        props.unit = (props === null || props === void 0 ? void 0 : props.units[0]) || '';
                                    }
                                    propToUp.up(props);
                                }
                            },
                        },
                        {
                            property: 'transform-value',
                            type: this.typeNumber,
                            default: '0',
                            full: true,
                        },
                    ],
                },
            ],
        ];
        propsToCreate.forEach(function (_a) {
            var prop = _a[0], def = _a[1], from = _a[2];
            _this.add(prop, def || {}, { from: from });
        });
        return this;
    };
    PropertyFactory.prototype.add = function (property, def, opts) {
        if (def === void 0) { def = {}; }
        if (opts === void 0) { opts = {}; }
        var from = opts.from || '';
        var fromRes = this.props[from || property] || {};
        var result = PropertyFactory_assign(PropertyFactory_assign(PropertyFactory_assign({}, fromRes), { property: property }), def);
        if (result.properties && (0,index_all.isFunction)(result.properties)) {
            result.properties = result.properties();
        }
        this.props[property] = result;
        return result;
    };
    PropertyFactory.prototype.get = function (prop) {
        return this.props[prop];
    };
    /**
     * Build props object by their name
     * @param  {Array<string>|string} props Array of properties name
     * @return {Array<Object>}
     */
    PropertyFactory.prototype.build = function (props) {
        var _this = this;
        var result = [];
        var propsArr = (0,index_all.isString)(props) ? [props] : props;
        propsArr.forEach(function (prop) {
            result.push(_this.get(prop) || { property: prop });
        });
        return result;
    };
    return PropertyFactory;
}());
/* harmony default export */ const model_PropertyFactory = (PropertyFactory);

;// CONCATENATED MODULE: ./src/style_manager/view/SectorView.ts
var SectorView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var SectorView_makeTemplateObject = (undefined && undefined.__makeTemplateObject) || function (cooked, raw) {
    if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
    return cooked;
};



var SectorView = /** @class */ (function (_super) {
    SectorView_extends(SectorView, _super);
    function SectorView(o) {
        var _this = _super.call(this, o) || this;
        var config = o.config || {};
        var model = _this.model;
        // @ts-ignore
        var em = config.em;
        _this.config = config;
        _this.em = em;
        _this.pfx = config.stylePrefix || '';
        _this.listenTo(model, 'destroy remove', _this.remove);
        _this.listenTo(model, 'change:open', _this.updateOpen);
        _this.listenTo(model, 'change:visible', _this.updateVisibility);
        return _this;
    }
    SectorView.prototype.template = function (_a) {
        var _b;
        var pfx = _a.pfx, label = _a.label;
        var icons = (_b = this.em) === null || _b === void 0 ? void 0 : _b.getConfig().icons;
        var iconCaret = (icons === null || icons === void 0 ? void 0 : icons.caret) || '';
        var clsPfx = "".concat(pfx, "sector-");
        return html(SectorView_templateObject_1 || (SectorView_templateObject_1 = SectorView_makeTemplateObject(["\n      <div class=\"", "title\" data-sector-title>\n        <div class=\"", "caret\">$", "</div>\n        <div class=\"", "label\">", "</div>\n      </div>\n    "], ["\n      <div class=\"", "title\" data-sector-title>\n        <div class=\"", "caret\">$", "</div>\n        <div class=\"", "label\">", "</div>\n      </div>\n    "])), clsPfx, clsPfx, iconCaret, clsPfx, label);
    };
    SectorView.prototype.events = function () {
        return {
            'click [data-sector-title]': 'toggle',
        };
    };
    SectorView.prototype.updateOpen = function () {
        var _a = this, $el = _a.$el, model = _a.model, pfx = _a.pfx;
        var isOpen = model.isOpen();
        $el[isOpen ? 'addClass' : 'removeClass']("".concat(pfx, "open"));
        this.getPropertiesEl().style.display = isOpen ? '' : 'none';
    };
    SectorView.prototype.updateVisibility = function () {
        this.el.style.display = this.model.isVisible() ? '' : 'none';
    };
    SectorView.prototype.getPropertiesEl = function () {
        var _a = this, $el = _a.$el, pfx = _a.pfx;
        return $el.find(".".concat(pfx, "properties")).get(0);
    };
    SectorView.prototype.toggle = function () {
        var model = this.model;
        model.setOpen(!model.get('open'));
    };
    SectorView.prototype.renderProperties = function () {
        var _a = this, model = _a.model, config = _a.config;
        var objs = model.get('properties');
        if (objs) {
            // @ts-ignore
            var view = new view_PropertiesView({ collection: objs, config: config });
            this.$el.append(view.render().el);
        }
    };
    SectorView.prototype.render = function () {
        var _a = this, pfx = _a.pfx, model = _a.model, $el = _a.$el;
        var id = model.getId();
        var label = model.getName();
        $el.html(this.template({ pfx: pfx, label: label }));
        this.renderProperties();
        $el.attr('class', "".concat(pfx, "sector ").concat(pfx, "sector__").concat(id, " no-select"));
        this.updateOpen();
        return this;
    };
    return SectorView;
}(common/* View */.G7));
/* harmony default export */ const view_SectorView = (SectorView);
var SectorView_templateObject_1;

;// CONCATENATED MODULE: ./src/style_manager/view/SectorsView.ts
var SectorsView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();



var SectorsView = /** @class */ (function (_super) {
    SectorsView_extends(SectorsView, _super);
    function SectorsView(o) {
        if (o === void 0) { o = {}; }
        var _this = 
        // @ts-ignore
        _super.call(this, o) || this;
        var module = o.module, config = o.config;
        var coll = _this.collection;
        _this.pfx = (config === null || config === void 0 ? void 0 : config.stylePrefix) || '';
        _this.ppfx = (config === null || config === void 0 ? void 0 : config.pStylePrefix) || '';
        _this.config = config;
        _this.module = module;
        _this.listenTo(coll, 'add', _this.addTo);
        _this.listenTo(coll, 'reset', _this.render);
        return _this;
    }
    SectorsView.prototype.remove = function () {
        var _this = this;
        common/* View */.G7.prototype.remove.apply(this, arguments);
        ['config', 'module', 'em'].forEach(function (i) {
            // @ts-ignore
            return (_this[i] = {});
        });
        return this;
    };
    SectorsView.prototype.addTo = function (model, c, opts) {
        if (opts === void 0) { opts = {}; }
        this.addToCollection(model, null, opts);
    };
    SectorsView.prototype.addToCollection = function (model, fragmentEl, opts) {
        if (opts === void 0) { opts = {}; }
        var _a = this, config = _a.config, el = _a.el;
        var appendTo = fragmentEl || el;
        var rendered = new view_SectorView({ model: model, config: config }).render().el;
        (0,dom/* appendAtIndex */.$Q)(appendTo, rendered, opts.at);
        return rendered;
    };
    SectorsView.prototype.render = function () {
        var _this = this;
        var _a = this, $el = _a.$el, pfx = _a.pfx, ppfx = _a.ppfx;
        $el.empty();
        var frag = document.createDocumentFragment();
        this.collection.each(function (model) { return _this.addToCollection(model, frag); });
        $el.append(frag);
        $el.addClass("".concat(pfx, "sectors ").concat(ppfx, "one-bg ").concat(ppfx, "two-color"));
        return this;
    };
    return SectorsView;
}(common/* View */.G7));
/* harmony default export */ const view_SectorsView = (SectorsView);

;// CONCATENATED MODULE: ./src/style_manager/index.ts
/**
 * With Style Manager you build categories (called sectors) of CSS properties which could be used to customize the style of components.
 * You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](https://github.com/GrapesJS/grapesjs/blob/master/src/style_manager/config/config.ts)
 * ```js
 * const editor = grapesjs.init({
 *  styleManager: {
 *    // options
 *  }
 * })
 * ```
 *
 * Once the editor is instantiated you can use its API and listen to its events. Before using these methods, you should get the module from the instance.
 *
 * ```js
 * // Listen to events
 * editor.on('style:sector:add', (sector) => { ... });
 *
 * // Use the API
 * const styleManager = editor.StyleManager;
 * styleManager.addSector(...);
 * ```
 * ## Available Events
 * * `style:sector:add` - Sector added. The [Sector] is passed as an argument to the callback.
 * * `style:sector:remove` - Sector removed. The [Sector] is passed as an argument to the callback.
 * * `style:sector:update` - Sector updated. The [Sector] and the object containing changes are passed as arguments to the callback.
 * * `style:property:add` - Property added. The [Property] is passed as an argument to the callback.
 * * `style:property:remove` - Property removed. The [Property] is passed as an argument to the callback.
 * * `style:property:update` - Property updated. The [Property] and the object containing changes are passed as arguments to the callback.
 * * `style:target` - Target selection changed. The target (or `null` in case the target is deselected) is passed as an argument to the callback.
 * <!--
 * * `styleManager:update:target` - The target (Component or CSSRule) is changed
 * * `styleManager:change` - Triggered on style property change from new selected component, the view of the property is passed as an argument to the callback
 * * `styleManager:change:{propertyName}` - As above but for a specific style property
 * -->
 *
 * ## Methods
 * * [getConfig](#getconfig)
 * * [addSector](#addsector)
 * * [getSector](#getsector)
 * * [getSectors](#getsectors)
 * * [removeSector](#removesector)
 * * [addProperty](#addproperty)
 * * [getProperty](#getproperty)
 * * [getProperties](#getproperties)
 * * [removeProperty](#removeproperty)
 * * [select](#select)
 * * [getSelected](#getselected)
 * * [getSelectedAll](#getselectedall)
 * * [getSelectedParents](#getselectedparents)
 * * [addStyleTargets](#addstyletargets)
 * * [getBuiltIn](#getbuiltin)
 * * [getBuiltInAll](#getbuiltinall)
 * * [addBuiltIn](#addbuiltin)
 * * [addType](#addtype)
 * * [getType](#gettype)
 * * [getTypes](#gettypes)
 *
 * [Sector]: sector.html
 * [CssRule]: css_rule.html
 * [Component]: component.html
 * [Property]: property.html
 *
 * @module docsjs.StyleManager
 */
var style_manager_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var style_manager_assign = (undefined && undefined.__assign) || function () {
    style_manager_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return style_manager_assign.apply(this, arguments);
};
var style_manager_spreadArray = (undefined && undefined.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};










var style_manager_evAll = 'style';
var style_manager_evPfx = "".concat(style_manager_evAll, ":");
var evSector = "".concat(style_manager_evPfx, "sector");
var evSectorAdd = "".concat(evSector, ":add");
var evSectorRemove = "".concat(evSector, ":remove");
var evSectorUpdate = "".concat(evSector, ":update");
var evProp = "".concat(style_manager_evPfx, "property");
var evPropAdd = "".concat(evProp, ":add");
var evPropRemove = "".concat(evProp, ":remove");
var evPropUp = "".concat(evProp, ":update");
var evLayerSelect = "".concat(style_manager_evPfx, "layer:select");
var evTarget = "".concat(style_manager_evPfx, "target");
var style_manager_evCustom = "".concat(style_manager_evPfx, "custom");
var propDef = function (value) { return value || value === 0; };
var stylesEvents = {
    all: style_manager_evAll,
    sectorAdd: evSectorAdd,
    sectorRemove: evSectorRemove,
    sectorUpdate: evSectorUpdate,
    propertyAdd: evPropAdd,
    propertyRemove: evPropRemove,
    propertyUpdate: evPropUp,
    layerSelect: evLayerSelect,
    target: evTarget,
    custom: style_manager_evCustom,
};
var StyleManager = /** @class */ (function (_super) {
    style_manager_extends(StyleManager, _super);
    /**
     * Get configuration object
     * @name getConfig
     * @function
     * @return {Object}
     */
    /**
     * Initialize module. Automatically called with a new instance of the editor
     * @param {Object} config Configurations
     * @private
     */
    function StyleManager(em) {
        var _this = _super.call(this, em, 'StyleManager', new model_Sectors([], { em: em }), stylesEvents, style_manager_config_config) || this;
        _this.Sector = model_Sector;
        _this.storageKey = '';
        (0,index_all.bindAll)(_this, '__clearStateTarget');
        var c = _this.config;
        var ppfx = c.pStylePrefix;
        if (ppfx)
            c.stylePrefix = ppfx + c.stylePrefix;
        _this.builtIn = new model_PropertyFactory();
        _this.properties = new model_Properties([], { em: em, module: _this });
        _this.sectors = _this.all; // TODO check if (module: this) is required
        var model = new common/* Model */.Hn({ targets: [] });
        _this.model = model;
        // Triggers for the selection refresh and properties
        var ev = 'component:toggled component:update:classes change:state change:device frame:resized selector:type';
        _this.upAll = (0,index_all.debounce)(function () { return _this.__upSel(); }, 0);
        model.listenTo(em, ev, _this.upAll);
        // Clear state target on any component selection change, without debounce (#4208)
        model.listenTo(em, 'component:toggled', _this.__clearStateTarget);
        // Triggers only for properties (avoid selection refresh)
        var upProps = (0,index_all.debounce)(function () {
            _this.__upProps();
            _this.__trgCustom();
        }, 0);
        model.listenTo(em, 'styleable:change undo redo', upProps);
        // Triggers only custom event
        var trgCustom = (0,index_all.debounce)(function () { return _this.__trgCustom(); }, 0);
        model.listenTo(em, "".concat(evLayerSelect, " ").concat(evTarget), trgCustom);
        // Other listeners
        model.on('change:lastTarget', function () { return em.trigger(evTarget, _this.getSelected()); });
        return _this;
    }
    StyleManager.prototype.__upSel = function () {
        this.select(this.em.getSelectedAll());
    };
    StyleManager.prototype.__trgCustom = function (opts) {
        if (opts === void 0) { opts = {}; }
        this.__ctn = this.__ctn || opts.container;
        this.em.trigger(this.events.custom, { container: this.__ctn });
    };
    StyleManager.prototype.__trgEv = function (event) {
        var _a;
        var data = [];
        for (var _i = 1; _i < arguments.length; _i++) {
            data[_i - 1] = arguments[_i];
        }
        (_a = this.em).trigger.apply(_a, style_manager_spreadArray([event], data, false));
    };
    StyleManager.prototype.__clearStateTarget = function () {
        var _this = this;
        var em = this.em;
        var stateTarget = this.__getStateTarget();
        stateTarget &&
            (em === null || em === void 0 ? void 0 : em.skip(function () {
                em.Css.remove(stateTarget);
                _this.model.set({ stateTarget: null });
            }));
    };
    StyleManager.prototype.onLoad = function () {
        // Use silent as sectors' view will be created and rendered on StyleManager.render
        this.sectors.add(this.config.sectors, { silent: true });
    };
    StyleManager.prototype.postRender = function () {
        this.__appendTo();
    };
    /**
     * Add new sector. If the sector with the same id already exists, that one will be returned.
     * @param {String} id Sector id
     * @param {Object} sector Sector definition. Check the [available properties](sector.html#properties)
     * @param {Object} [options={}] Options
     * @param {Number} [options.at] Position index (by default, will be appended at the end).
     * @returns {[Sector]} Added Sector
     * @example
     * const sector = styleManager.addSector('mySector',{
     *   name: 'My sector',
     *   open: true,
     *   properties: [{ name: 'My property'}]
     * }, { at: 0 });
     * // With `at: 0` we place the new sector at the beginning of the list
     * */
    StyleManager.prototype.addSector = function (id, sector, options) {
        if (options === void 0) { options = {}; }
        var result = this.getSector(id);
        if (!result) {
            sector.id = id;
            result = this.sectors.add(sector, options);
        }
        return result;
    };
    /**
     * Get sector by id.
     * @param {String} id  Sector id
     * @returns {[Sector]|null}
     * @example
     * const sector = styleManager.getSector('mySector');
     * */
    StyleManager.prototype.getSector = function (id, opts) {
        if (opts === void 0) { opts = {}; }
        var res = this.sectors.where({ id: id })[0];
        !res && opts.warn && this._logNoSector(id);
        return res || null;
    };
    /**
     * Get all sectors.
     * @param {Object} [opts={}] Options
     * @param {Boolean} [opts.visible] Returns only visible sectors
     * @returns {Array<[Sector]>}
     * @example
     * const sectors = styleManager.getSectors();
     * */
    StyleManager.prototype.getSectors = function (opts) {
        if (opts === void 0) { opts = {}; }
        var sectors = this.sectors;
        var res = sectors && sectors.models ? (opts.array ? style_manager_spreadArray([], sectors.models, true) : sectors) : [];
        return (opts.visible ? res.filter(function (s) { return s.isVisible(); }) : res);
    };
    /**
     * Remove sector by id.
     * @param  {String} id Sector id
     * @returns {[Sector]} Removed sector
     * @example
     * const removed = styleManager.removeSector('mySector');
     */
    StyleManager.prototype.removeSector = function (id) {
        return this.getSectors().remove(this.getSector(id, { warn: true }));
    };
    /**
     * Add new property to the sector.
     * @param {String} sectorId Sector id.
     * @param {Object} property Property definition. Check the [base available properties](property.html#properties) + others based on the `type` of your property.
     * @param {Object} [opts={}] Options
     * @param {Number} [opts.at] Position index (by default, will be appended at the end).
     * @returns {[Property]|null} Added property or `null` in case the sector doesn't exist.
     * @example
     * const property = styleManager.addProperty('mySector', {
     *   label: 'Minimum height',
     *   property: 'min-height',
     *   type: 'select',
     *   default: '100px',
     *   options: [
     *    { id: '100px', label: '100' },
     *    { id: '200px', label: '200' },
     *   ],
     * }, { at: 0 });
     */
    StyleManager.prototype.addProperty = function (sectorId, property, opts) {
        if (opts === void 0) { opts = {}; }
        var sector = this.getSector(sectorId, { warn: true });
        var prop;
        if (sector)
            prop = sector.addProperty(property, opts);
        return prop;
    };
    /**
     * Get the property.
     * @param {String} sectorId Sector id.
     * @param {String} id Property id.
     * @returns {[Property]|undefined}
     * @example
     * const property = styleManager.getProperty('mySector', 'min-height');
     */
    StyleManager.prototype.getProperty = function (sectorId, id) {
        var sector = this.getSector(sectorId, { warn: true });
        var prop;
        if (sector) {
            prop = sector.properties.filter(function (prop) { return prop.get('property') === id || prop.get('id') === id; })[0];
        }
        return prop;
    };
    /**
     * Get all properties of the sector.
     * @param {String} sectorId Sector id.
     * @returns {Collection<[Property]>|undefined} Collection of properties
     * @example
     * const properties = styleManager.getProperties('mySector');
     */
    StyleManager.prototype.getProperties = function (sectorId) {
        var props;
        var sector = this.getSector(sectorId, { warn: true });
        if (sector)
            props = sector.properties;
        return props;
    };
    /**
     * Remove the property.
     * @param {String} sectorId Sector id.
     * @param {String} id Property id.
     * @returns {[Property]|null} Removed property
     * @example
     * const property = styleManager.removeProperty('mySector', 'min-height');
     */
    StyleManager.prototype.removeProperty = function (sectorId, id) {
        var props = this.getProperties(sectorId);
        return props ? props.remove(this.getProperty(sectorId, id)) : null;
    };
    /**
     * Select new target.
     * The target could be a Component, CSSRule, or a CSS selector string.
     * @param {[Component]|[CSSRule]|String} target
     * @returns {Array<[Component]|[CSSRule]>} Array containing selected Components or CSSRules
     * @example
     * // Select the first button in the current page
     * const wrapperCmp = editor.Pages.getSelected().getMainComponent();
     * const btnCmp = wrapperCmp.find('button')[0];
     * btnCmp && styleManager.select(btnCmp);
     *
     * // Set as a target the CSS selector
     * styleManager.select('.btn > span');
     */
    StyleManager.prototype.select = function (target, opts) {
        var _this = this;
        if (opts === void 0) { opts = {}; }
        var em = this.em;
        var trgs = (0,index_all.isArray)(target) ? target : [target];
        var stylable = opts.stylable;
        var cssc = em.Css;
        var targets = [];
        trgs.filter(Boolean).forEach(function (target) {
            var model = target;
            if ((0,index_all.isString)(target)) {
                var rule = cssc.getRule(target) || cssc.setRule(target);
                !(0,index_all.isUndefined)(stylable) && rule.set({ stylable: stylable });
                model = rule;
            }
            targets.push(model);
        });
        var component = opts.component || targets.filter(function (t) { return (0,mixins.isComponent)(t); }).reverse()[0];
        targets = targets.map(function (t) { return _this.getModelToStyle(t); });
        var state = em.getState();
        var lastTarget = targets.slice().reverse()[0];
        var lastTargetParents = this.getParentRules(lastTarget, {
            state: state,
            // @ts-ignore
            component: component,
        });
        var stateTarget = this.__getStateTarget();
        // Handle the creation and update of the state rule, if enabled.
        em.skip(function () {
            var _a;
            // @ts-ignore
            if (state && ((_a = lastTarget === null || lastTarget === void 0 ? void 0 : lastTarget.getState) === null || _a === void 0 ? void 0 : _a.call(lastTarget))) {
                var style = lastTarget.getStyle();
                if (!stateTarget) {
                    stateTarget = cssc.getAll().add({
                        selectors: 'gjs-selected',
                        style: style,
                        shallow: true,
                        important: true,
                    });
                }
                else {
                    stateTarget.setStyle(style);
                }
            }
            else if (stateTarget) {
                cssc.remove(stateTarget);
                stateTarget = undefined;
            }
        });
        this.model.set({
            targets: targets,
            lastTarget: lastTarget,
            lastTargetParents: lastTargetParents,
            stateTarget: stateTarget,
            component: component,
        });
        this.__upProps(opts);
        return targets;
    };
    /**
     * Get the last selected target.
     * By default, the Style Manager shows styles of the last selected target.
     * @returns {[Component]|[CSSRule]|null}
     */
    StyleManager.prototype.getSelected = function () {
        return this.model.get('lastTarget');
    };
    /**
     * Get the array of selected targets.
     * @returns {Array<[Component]|[CSSRule]>}
     */
    StyleManager.prototype.getSelectedAll = function () {
        return this.model.get('targets');
    };
    /**
     * Get parent rules of the last selected target.
     * @returns {Array<[CSSRule]>}
     */
    StyleManager.prototype.getSelectedParents = function () {
        return this.model.get('lastTargetParents') || [];
    };
    StyleManager.prototype.__getStateTarget = function () {
        return this.model.get('stateTarget');
    };
    /**
     * Update selected targets with a custom style.
     * @param {Object} style Style object
     * @param {Object} [opts={}] Options
     * @example
     * styleManager.addStyleTargets({ color: 'red' });
     */
    StyleManager.prototype.addStyleTargets = function (style, opts) {
        this.getSelectedAll().map(function (t) { return t.addStyle(style, opts); });
        var target = this.getSelected();
        // Trigger style changes on selected components
        target && this.__emitCmpStyleUpdate(style);
        // Update state rule
        var targetState = this.__getStateTarget();
        target && (targetState === null || targetState === void 0 ? void 0 : targetState.setStyle(target.getStyle(), opts));
    };
    /**
     * Return built-in property definition
     * @param {String} prop Property name.
     * @returns {Object|null} Property definition.
     * @example
     * const widthPropDefinition = styleManager.getBuiltIn('width');
     */
    StyleManager.prototype.getBuiltIn = function (prop) {
        return this.builtIn.get(prop);
    };
    /**
     * Get all the available built-in property definitions.
     * @returns {Object}
     */
    StyleManager.prototype.getBuiltInAll = function () {
        return this.builtIn.props;
    };
    /**
     * Add built-in property definition.
     * If the property exists already, it will extend it.
     * @param {String} prop Property name.
     * @param {Object} definition Property definition.
     * @returns {Object} Added property definition.
     * @example
     * const sector = styleManager.addBuiltIn('new-property', {
     *  type: 'select',
     *  default: 'value1',
     *  options: [{ id: 'value1', label: 'Some label' }, ...],
     * })
     */
    StyleManager.prototype.addBuiltIn = function (prop, definition) {
        return this.builtIn.add(prop, definition);
    };
    /**
     * Get what to style inside Style Manager. If you select the component
     * without classes the entity is the Component itself and all changes will
     * go inside its 'style' property. Otherwise, if the selected component has
     * one or more classes, the function will return the corresponding CSS Rule
     * @param  {Model} model
     * @return {Model}
     * @private
     */
    StyleManager.prototype.getModelToStyle = function (model, options) {
        if (options === void 0) { options = {}; }
        var em = this.em;
        var skipAdd = options.skipAdd;
        if (em && (model === null || model === void 0 ? void 0 : model.toHTML)) {
            var config_1 = em.getConfig();
            var um = em.UndoManager;
            var cssC_1 = em.Css;
            var sm = em.Selectors;
            var smConf = sm ? sm.getConfig() : {};
            var state_1 = !config_1.devicePreviewMode ? em.get('state') : '';
            var classes = model.get('classes');
            var valid_1 = classes.getStyleable();
            var hasClasses_1 = valid_1.length;
            var useClasses_1 = !smConf.componentFirst || options.useClasses;
            var addOpts_1 = { noCount: 1 };
            var opts_1 = { state: state_1, addOpts: addOpts_1 };
            // Skipping undo manager here as after adding the CSSRule (generally after
            // selecting the component) and calling undo() it will remove the rule from
            // the collection, therefore updating it in style manager will not affect it
            // #268
            um.skip(function () {
                var rule;
                if (hasClasses_1 && useClasses_1) {
                    var deviceW = em.getCurrentMedia();
                    rule = cssC_1.get(valid_1, state_1, deviceW);
                    if (!rule && !skipAdd) {
                        rule = cssC_1.add(valid_1, state_1, deviceW, {}, addOpts_1);
                    }
                }
                else if (config_1.avoidInlineStyle) {
                    var id = model.getId();
                    rule = cssC_1.getIdRule(id, opts_1);
                    !rule && !skipAdd && (rule = cssC_1.setIdRule(id, {}, opts_1));
                    if (model.is('wrapper')) {
                        // @ts-ignore
                        rule.set('wrapper', 1, addOpts_1);
                    }
                }
                rule && (model = rule);
            });
        }
        return model;
    };
    StyleManager.prototype.getParentRules = function (target, _a) {
        var _b = _a === void 0 ? {} : _a, state = _b.state, component = _b.component;
        var em = this.em;
        var result = [];
        if (em && target) {
            var sel = component;
            var cssC_2 = em.Css;
            var cssGen = em.CodeManager.getGenerator('css');
            // @ts-ignore
            var cmp = target.toHTML ? target : target.getComponent();
            var optsSel = { array: true };
            var cmpRules = [];
            var otherRules = [];
            var rules = [];
            var rulesBySelectors = function (values) {
                return !values.length
                    ? []
                    : cssC_2.getRules().filter(function (rule) {
                        var rSels = rule.getSelectors().map(function (s) { return s.getFullName(); });
                        return !!rSels.length && rSels.every(function (rSel) { return values.indexOf(rSel) >= 0; });
                    });
            };
            // Componente related rule
            if (cmp) {
                cmpRules = cssC_2.getRules("#".concat(cmp.getId()));
                otherRules = sel ? rulesBySelectors(sel.getSelectors().getFullName(optsSel)) : [];
                rules = otherRules.concat(cmpRules);
            }
            else {
                cmpRules = sel ? cssC_2.getRules("#".concat(sel.getId())) : [];
                otherRules = rulesBySelectors(target.getSelectors().getFullName(optsSel));
                rules = cmpRules.concat(otherRules);
            }
            var all = rules
                .filter(function (rule) { return (!(0,index_all.isUndefined)(state) ? rule.get('state') === state : 1); })
                .sort(cssGen.sortRules)
                .reverse();
            // Slice removes rules not related to the current device
            result = all.slice(all.indexOf(target) + 1);
        }
        return result;
    };
    /**
     * Add new property type
     * @param {string} id Type ID
     * @param {Object} definition Definition of the type.
     * @example
     * styleManager.addType('my-custom-prop', {
     *    // Create UI
     *    create({ props, change }) {
     *      const el = document.createElement('div');
     *      el.innerHTML = '<input type="range" class="my-input" min="10" max="50"/>';
     *      const inputEl = el.querySelector('.my-input');
     *      inputEl.addEventListener('change', event => change({ event }));
     *      inputEl.addEventListener('input', event => change({ event, partial: true }));
     *      return el;
     *    },
     *    // Propagate UI changes up to the targets
     *    emit({ props, updateStyle }, { event, partial }) {
     *      const { value } = event.target;
     *      updateStyle(`${value}px`, { partial });
     *    },
     *    // Update UI (eg. when the target is changed)
     *    update({ value, el }) {
     *      el.querySelector('.my-input').value = parseInt(value, 10);
     *    },
     *    // Clean the memory from side effects if necessary (eg. global event listeners, etc.)
     *    destroy() {}
     *})
     */
    StyleManager.prototype.addType = function (id, definition) {
        this.properties.addType(id, definition);
    };
    /**
     * Get type
     * @param {string} id Type ID
     * @return {Object} Type definition
     */
    StyleManager.prototype.getType = function (id) {
        return this.properties.getType(id);
    };
    /**
     * Get all types
     * @return {Array}
     */
    StyleManager.prototype.getTypes = function () {
        return this.properties.getTypes();
    };
    /**
     * Create new UI property from type (Experimental)
     * @param {string} id Type ID
     * @param  {Object} [options={}] Options
     * @param  {Object} [options.model={}] Custom model object
     * @param  {Object} [options.view={}] Custom view object
     * @return {PropertyView}
     * @private
     * @example
     * const propView = styleManager.createType('number', {
     *  model: {units: ['px', 'rem']}
     * });
     * propView.render();
     * propView.model.on('change:value', ...);
     * someContainer.appendChild(propView.el);
     */
    StyleManager.prototype.createType = function (id, _a) {
        var _b = _a === void 0 ? {} : _a, _c = _b.model, model = _c === void 0 ? {} : _c, _d = _b.view, view = _d === void 0 ? {} : _d;
        var config = this.config;
        var type = this.getType(id);
        if (type) {
            return new type.view(style_manager_assign({ model: new type.model(model), config: config }, view));
        }
    };
    /**
     * Render sectors and properties
     * @return  {HTMLElement}
     * @private
     * */
    StyleManager.prototype.render = function () {
        var _a = this, config = _a.config, em = _a.em, SectView = _a.SectView;
        var el = SectView && SectView.el;
        this.SectView = new view_SectorsView({
            el: el,
            em: em,
            config: config,
            module: this,
            collection: this.sectors,
        });
        return this.SectView.render().el;
    };
    StyleManager.prototype._logNoSector = function (sectorId) {
        var em = this.em;
        em && em.logWarning("'".concat(sectorId, "' sector not found"));
    };
    StyleManager.prototype.__emitCmpStyleUpdate = function (style, opts) {
        if (opts === void 0) { opts = {}; }
        var em = this.em;
        // Ignore partial updates
        if (!style.__p) {
            var allSel_1 = this.getSelectedAll();
            var cmp = opts.components || em.getSelectedAll();
            var cmps = Array.isArray(cmp) ? cmp : [cmp];
            var newStyles_1 = style_manager_assign({}, style);
            delete newStyles_1.__p;
            cmps.forEach(function (cmp) {
                // if cmp is part of selected, the event should already been triggered
                return !allSel_1.includes(cmp) && cmp.__onStyleChange(newStyles_1);
            });
        }
    };
    StyleManager.prototype.__upProps = function (opts) {
        var _this = this;
        if (opts === void 0) { opts = {}; }
        var lastTarget = this.getSelected();
        if (!lastTarget)
            return;
        var sectors = this.sectors;
        var component = this.model.get('component');
        var lastTargetParents = this.getSelectedParents();
        var style = lastTarget.getStyle();
        var parentStyles = lastTargetParents.map(function (p) { return ({
            target: p,
            style: p.getStyle(),
        }); });
        sectors.map(function (sector) {
            sector.getProperties().map(function (prop) {
                _this.__upProp(prop, style, parentStyles, opts);
            });
        });
        // Update sectors/properties visibility
        sectors.forEach(function (sector) {
            var props = sector.getProperties();
            props.forEach(function (prop) {
                var isVisible = prop.__checkVisibility({
                    target: lastTarget,
                    component: component,
                    // @ts-ignore
                    sectors: sectors,
                });
                prop.set('visible', isVisible);
            });
            var sectorVisible = props.some(function (p) { return p.isVisible(); });
            sector.set('visible', sectorVisible);
        });
    };
    StyleManager.prototype.__upProp = function (prop, style, parentStyles, opts) {
        var _this = this;
        var name = prop.getName();
        var value = style[name];
        var hasVal = propDef(value);
        var isStack = prop.getType() === 'stack';
        var isComposite = prop.getType() === 'composite';
        var opt = style_manager_assign(style_manager_assign({}, opts), { __up: true });
        var canUpdate = !isComposite && !isStack;
        var propStack = prop;
        var propComp = prop;
        var newLayers = isStack ? propStack.__getLayersFromStyle(style) : [];
        var newProps = isComposite ? propComp.__getPropsFromStyle(style) : {};
        var newValue = hasVal ? value : null;
        var parentTarget = null;
        if ((isStack && newLayers === null) || (isComposite && newProps === null)) {
            var method_1 = isStack ? '__getLayersFromStyle' : '__getPropsFromStyle';
            var parentItem = parentStyles.filter(function (p) { return propStack[method_1](p.style) !== null; })[0];
            if (parentItem) {
                newValue = parentItem.style[name];
                parentTarget = parentItem.target;
                var val = propStack[method_1](parentItem.style);
                if (isStack) {
                    newLayers = val;
                }
                else {
                    newProps = val;
                }
            }
        }
        else if (!hasVal) {
            newValue = null;
            var parentItem = parentStyles.filter(function (p) { return propDef(p.style[name]); })[0];
            if (parentItem) {
                newValue = parentItem.style[name];
                parentTarget = parentItem.target;
            }
        }
        prop.__setParentTarget(parentTarget);
        canUpdate && prop.__getFullValue() !== newValue && prop.upValue(newValue, opt);
        if (isStack) {
            propStack.__setLayers(newLayers || [], {
                isEmptyValue: propStack.isEmptyValueStyle(style),
            });
        }
        if (isComposite) {
            var props = propComp.getProperties();
            // Detached has to be treathed as separate properties
            if (propComp.isDetached()) {
                var newStyle_1 = propComp.__getPropsFromStyle(style, { byName: true }) || {};
                var newParentStyles_1 = parentStyles.map(function (p) { return (style_manager_assign(style_manager_assign({}, p), { style: propComp.__getPropsFromStyle(p.style, { byName: true }) || {} })); });
                props.map(function (pr) { return _this.__upProp(pr, newStyle_1, newParentStyles_1, opts); });
            }
            else {
                propComp.__setProperties(newProps || {}, opt);
                propComp.getProperties().map(function (pr) { return pr.__setParentTarget(parentTarget); });
            }
        }
    };
    StyleManager.prototype.destroy = function () {
        var _a;
        [this.properties, this.sectors].forEach(function (coll) {
            coll.reset();
            coll.stopListening();
        });
        (_a = this.SectView) === null || _a === void 0 ? void 0 : _a.remove();
        this.model.stopListening();
        this.upAll.cancel();
    };
    return StyleManager;
}(ItemManagerModule));
/* harmony default export */ const style_manager = (StyleManager);

;// CONCATENATED MODULE: ./src/editor/model/Editor.ts
var Editor_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var Editor_assign = (undefined && undefined.__assign) || function () {
    Editor_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return Editor_assign.apply(this, arguments);
};
var Editor_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var Editor_generator = (undefined && undefined.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var Editor_rest = (undefined && undefined.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
var Editor_spreadArray = (undefined && undefined.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};






























(backbone_default()).$ = cash_dom["default"];
var deps = [
    utils,
    i18n,
    keymaps,
    undo_manager,
    storage_manager,
    device_manager,
    parser,
    style_manager,
    selector_manager,
    modal_dialog,
    code_manager,
    panels,
    rich_text_editor,
    trait_manager,
    src_navigator,
    canvas,
    commands,
    block_manager,
];
var storableDeps = [
    asset_manager,
    css_composer,
    pages,
    dom_components,
];
extender({ $: cash_dom["default"] });
var logs = {
    debug: console.log,
    info: console.info,
    warning: console.warn,
    error: console.error,
};
var EditorModel = /** @class */ (function (_super) {
    Editor_extends(EditorModel, _super);
    function EditorModel(conf) {
        if (conf === void 0) { conf = {}; }
        var _this = _super.call(this) || this;
        _this.__skip = false;
        _this.defaultRunning = false;
        _this.destroyed = false;
        _this._config = conf;
        var config = _this.config;
        _this.set('Config', conf);
        _this.set('modules', []);
        _this.set('toLoad', []);
        _this.set('storables', []);
        _this.set('selected', new model_Selected());
        _this.set('dmode', config.dragMode);
        var el = config.el, log = config.log;
        var toLog = log === true ? (0,index_all.keys)(logs) : (0,index_all.isArray)(log) ? log : [];
        (0,index_all.bindAll)(_this, 'initBaseColorPicker');
        if (el && config.fromElement) {
            config.components = el.innerHTML;
        }
        _this.attrsOrig = el
            ? (0,index_all.toArray)(el.attributes).reduce(function (res, next) {
                res[next.nodeName] = next.nodeValue;
                return res;
            }, {})
            : '';
        // Move components to pages
        if (config.components && !config.pageManager) {
            config.pageManager = { pages: [{ component: config.components }] };
        }
        // Load modules
        deps.forEach(function (constr) { return _this.loadModule(constr); });
        storableDeps.forEach(function (constr) { return _this.loadStorableModule(constr); });
        _this.on('change:componentHovered', _this.componentHovered, _this);
        _this.on('change:changesCount', _this.updateChanges, _this);
        _this.on('change:readyLoad change:readyCanvas', _this._checkReady, _this);
        toLog.forEach(function (e) { return _this.listenLog(e); });
        // Deprecations
        [{ from: 'change:selectedComponent', to: 'component:toggled' }].forEach(function (event) {
            var eventFrom = event.from;
            var eventTo = event.to;
            _this.listenTo(_this, eventFrom, function () {
                var args = [];
                for (var _i = 0; _i < arguments.length; _i++) {
                    args[_i] = arguments[_i];
                }
                _this.trigger.apply(_this, Editor_spreadArray([eventTo], args, false));
                _this.logWarning("The event '".concat(eventFrom, "' is deprecated, replace it with '").concat(eventTo, "'"));
            });
        });
        return _this;
    }
    EditorModel.prototype.defaults = function () {
        return {
            editing: 0,
            selected: 0,
            clipboard: null,
            dmode: 0,
            componentHovered: null,
            previousModel: null,
            changesCount: 0,
            storables: [],
            modules: [],
            toLoad: [],
            opened: {},
            device: '',
        };
    };
    Object.defineProperty(EditorModel.prototype, "storables", {
        get: function () {
            return this.get('storables');
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(EditorModel.prototype, "modules", {
        get: function () {
            return this.get('modules');
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(EditorModel.prototype, "toLoad", {
        get: function () {
            return this.get('toLoad');
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(EditorModel.prototype, "selected", {
        get: function () {
            return this.get('selected');
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(EditorModel.prototype, "shallow", {
        get: function () {
            return this.get('shallow');
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(EditorModel.prototype, "I18n", {
        get: function () {
            return this.get('I18n');
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(EditorModel.prototype, "Utils", {
        get: function () {
            return this.get('Utils');
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(EditorModel.prototype, "Commands", {
        get: function () {
            return this.get('Commands');
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(EditorModel.prototype, "Keymaps", {
        get: function () {
            return this.get('Keymaps');
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(EditorModel.prototype, "Modal", {
        get: function () {
            return this.get('Modal');
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(EditorModel.prototype, "Panels", {
        get: function () {
            return this.get('Panels');
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(EditorModel.prototype, "CodeManager", {
        get: function () {
            return this.get('CodeManager');
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(EditorModel.prototype, "UndoManager", {
        get: function () {
            return this.get('UndoManager');
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(EditorModel.prototype, "RichTextEditor", {
        get: function () {
            return this.get('RichTextEditor');
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(EditorModel.prototype, "Canvas", {
        get: function () {
            return this.get('Canvas');
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(EditorModel.prototype, "Editor", {
        get: function () {
            return this.get('Editor');
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(EditorModel.prototype, "Components", {
        get: function () {
            return this.get('DomComponents');
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(EditorModel.prototype, "Css", {
        get: function () {
            return this.get('CssComposer');
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(EditorModel.prototype, "Blocks", {
        get: function () {
            return this.get('BlockManager');
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(EditorModel.prototype, "Selectors", {
        get: function () {
            return this.get('SelectorManager');
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(EditorModel.prototype, "Storage", {
        get: function () {
            return this.get('StorageManager');
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(EditorModel.prototype, "Traits", {
        get: function () {
            return this.get('TraitManager');
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(EditorModel.prototype, "Parser", {
        get: function () {
            return this.get('Parser');
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(EditorModel.prototype, "Layers", {
        get: function () {
            return this.get('LayerManager');
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(EditorModel.prototype, "Assets", {
        get: function () {
            return this.get('AssetManager');
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(EditorModel.prototype, "Devices", {
        get: function () {
            return this.get('DeviceManager');
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(EditorModel.prototype, "Pages", {
        get: function () {
            return this.get('PageManager');
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(EditorModel.prototype, "Styles", {
        get: function () {
            return this.get('StyleManager');
        },
        enumerable: false,
        configurable: true
    });
    EditorModel.prototype._checkReady = function () {
        if (this.get('readyLoad') && this.get('readyCanvas') && !this.get('ready')) {
            this.set('ready', true);
        }
    };
    EditorModel.prototype.getContainer = function () {
        return this.config.el;
    };
    EditorModel.prototype.listenLog = function (event) {
        //@ts-ignore
        this.listenTo(this, "log:".concat(event), logs[event]);
    };
    Object.defineProperty(EditorModel.prototype, "config", {
        get: function () {
            return this._config;
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Get configurations
     * @param  {string} [prop] Property name
     * @return {any} Returns the configuration object or
     *  the value of the specified property
     */
    EditorModel.prototype.getConfig = function (prop) {
        var config = this.config;
        // @ts-ignore
        return (0,index_all.isUndefined)(prop) ? config : config[prop];
    };
    /**
     * Should be called once all modules and plugins are loaded
     * @private
     */
    EditorModel.prototype.loadOnStart = function () {
        var _this = this;
        var _a = this.config, projectData = _a.projectData, headless = _a.headless;
        var sm = this.Storage;
        // In `onLoad`, the module will try to load the data from its configurations.
        this.toLoad.reverse().forEach(function (mdl) { return mdl.onLoad(); });
        // Stuff to do post load
        var postLoad = function () {
            _this.modules.forEach(function (mdl) { return mdl.postLoad && mdl.postLoad(_this); });
            _this.set('readyLoad', 1);
        };
        if (headless) {
            projectData && this.loadData(projectData);
            postLoad();
        }
        else {
            // Defer for storage load events.
            this._storageTimeout = setTimeout(function () { return Editor_awaiter(_this, void 0, void 0, function () {
                var error_1;
                return Editor_generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            if (!projectData) return [3 /*break*/, 1];
                            this.loadData(projectData);
                            return [3 /*break*/, 5];
                        case 1:
                            if (!(sm === null || sm === void 0 ? void 0 : sm.canAutoload())) return [3 /*break*/, 5];
                            _a.label = 2;
                        case 2:
                            _a.trys.push([2, 4, , 5]);
                            return [4 /*yield*/, this.load()];
                        case 3:
                            _a.sent();
                            return [3 /*break*/, 5];
                        case 4:
                            error_1 = _a.sent();
                            this.logError(error_1);
                            return [3 /*break*/, 5];
                        case 5:
                            postLoad();
                            return [2 /*return*/];
                    }
                });
            }); });
        }
        // Create shallow editor.
        // Here we can create components/styles without altering/triggering the main EditorModel
        var shallow = new EditorModel({
            noticeOnUnload: false,
            storageManager: false,
            undoManager: false,
        });
        // We only need to load a few modules
        shallow.Pages.onLoad();
        shallow.Canvas.postLoad();
        this.set('shallow', shallow);
    };
    /**
     * Set the alert before unload in case it's requested
     * and there are unsaved changes
     * @private
     */
    EditorModel.prototype.updateChanges = function (m, v, opts) {
        var _this = this;
        var stm = this.Storage;
        var changes = this.getDirtyCount();
        if (!opts.isClear) {
            this.updateItr && clearTimeout(this.updateItr);
            this.updateItr = setTimeout(function () { return _this.trigger('update'); });
        }
        if (this.config.noticeOnUnload) {
            window.onbeforeunload = changes ? function () { return true; } : null;
        }
        if (stm.isAutosave() && changes >= stm.getStepsBeforeSave()) {
            this.store().catch(function (err) { return _this.logError(err); });
        }
    };
    /**
     * Load generic module
     */
    EditorModel.prototype.loadModule = function (InitModule) {
        var Mod = new InitModule(this);
        this.set(Mod.name, Mod);
        Mod.onLoad && this.toLoad.push(Mod);
        this.modules.push(Mod);
        return Mod;
    };
    EditorModel.prototype.loadStorableModule = function (InitModule) {
        var Mod = this.loadModule(InitModule);
        this.storables.push(Mod);
        return Mod;
    };
    /**
     * Initialize editor model and set editor instance
     * @param {Editor} editor Editor instance
     * @return {this}
     * @public
     */
    EditorModel.prototype.init = function (editor, opts) {
        if (opts === void 0) { opts = {}; }
        if (this.destroyed) {
            this.initialize(opts);
            this.destroyed = false;
        }
        this.set('Editor', editor);
    };
    EditorModel.prototype.getEditor = function () {
        return this.get('Editor');
    };
    /**
     * This method handles updates on the editor and tries to store them
     * if requested and if the changesCount is exceeded
     * @param  {Object} model
     * @param  {any} val  Value
     * @param  {Object} opt  Options
     * @private
     * */
    EditorModel.prototype.handleUpdates = function (model, val, opt) {
        var _this = this;
        if (opt === void 0) { opt = {}; }
        // Component has been added temporarily - do not update storage or record changes
        if (this.__skip || opt.temporary || opt.noCount || opt.avoidStore || !this.get('ready')) {
            return;
        }
        this.timedInterval && clearTimeout(this.timedInterval);
        this.timedInterval = setTimeout(function () {
            var curr = _this.getDirtyCount() || 0;
            var unset = opt.unset, opts = Editor_rest(opt, ["unset"]);
            _this.set('changesCount', curr + 1, opts);
        }, 0);
    };
    EditorModel.prototype.changesUp = function (opts) {
        this.handleUpdates(0, 0, opts);
    };
    /**
     * Callback on component hover
     * @param   {Object}   Model
     * @param   {Mixed}   New value
     * @param   {Object}   Options
     * @private
     * */
    EditorModel.prototype.componentHovered = function (editor, component, options) {
        var prev = this.previous('componentHovered');
        prev && this.trigger('component:unhovered', prev, options);
        component && this.trigger('component:hovered', component, options);
    };
    /**
     * Returns model of the selected component
     * @return {Component|null}
     * @public
     */
    EditorModel.prototype.getSelected = function () {
        return this.selected.lastComponent();
    };
    /**
     * Returns an array of all selected components
     * @return {Array}
     * @public
     */
    EditorModel.prototype.getSelectedAll = function () {
        return this.selected.allComponents();
    };
    /**
     * Select a component
     * @param  {Component} el Component to select
     * @param  {Object} [opts={}] Options, optional
     * @public
     */
    EditorModel.prototype.setSelected = function (el, opts) {
        var _this = this;
        if (opts === void 0) { opts = {}; }
        var event = opts.event;
        var ctrlKey = event && (event.ctrlKey || event.metaKey);
        var shiftKey = (event || {}).shiftKey;
        var models = ((0,index_all.isArray)(el) ? el : [el])
            .map(function (cmp) { var _a, _b; return ((_b = (_a = cmp === null || cmp === void 0 ? void 0 : cmp.delegate) === null || _a === void 0 ? void 0 : _a.select) === null || _b === void 0 ? void 0 : _b.call(_a, cmp)) || cmp; })
            .filter(Boolean);
        var selected = this.getSelectedAll();
        var mltSel = this.getConfig().multipleSelection;
        var multiple = (0,index_all.isArray)(el);
        if (multiple || !el) {
            this.removeSelected(selected.filter(function (s) { return !(0,index_all.contains)(models, s); }));
        }
        models.forEach(function (model) {
            if (model) {
                _this.trigger('component:select:before', model, opts);
                // Check for valid selectable
                if (!model.get('selectable') || opts.abort) {
                    if (opts.useValid) {
                        var parent_1 = model.parent();
                        while (parent_1 && !parent_1.get('selectable'))
                            parent_1 = parent_1.parent();
                        model = parent_1;
                    }
                    else {
                        return;
                    }
                }
            }
            // Hanlde multiple selection
            if (ctrlKey && mltSel) {
                return _this.toggleSelected(model);
            }
            else if (shiftKey && mltSel) {
                _this.clearSelection(_this.Canvas.getWindow());
                var coll_1 = model.collection;
                var index_1 = model.index();
                var min_1, max_1;
                // Fin min and max siblings
                _this.getSelectedAll().forEach(function (sel) {
                    var selColl = sel.collection;
                    var selIndex = sel.index();
                    if (selColl === coll_1) {
                        if (selIndex < index_1) {
                            // First model BEFORE the selected one
                            min_1 = (0,index_all.isUndefined)(min_1) ? selIndex : Math.max(min_1, selIndex);
                        }
                        else if (selIndex > index_1) {
                            // First model AFTER the selected one
                            max_1 = (0,index_all.isUndefined)(max_1) ? selIndex : Math.min(max_1, selIndex);
                        }
                    }
                });
                if (!(0,index_all.isUndefined)(min_1)) {
                    while (min_1 !== index_1) {
                        _this.addSelected(coll_1.at(min_1));
                        min_1++;
                    }
                }
                if (!(0,index_all.isUndefined)(max_1)) {
                    while (max_1 !== index_1) {
                        _this.addSelected(coll_1.at(max_1));
                        max_1--;
                    }
                }
                return _this.addSelected(model);
            }
            !multiple && _this.removeSelected(selected.filter(function (s) { return s !== model; }));
            _this.addSelected(model, opts);
        });
    };
    /**
     * Add component to selection
     * @param  {Component|Array<Component>} component Component to select
     * @param  {Object} [opts={}] Options, optional
     * @public
     */
    EditorModel.prototype.addSelected = function (component, opts) {
        var _this = this;
        if (opts === void 0) { opts = {}; }
        var models = (0,index_all.isArray)(component) ? component : [component];
        models.forEach(function (model) {
            var selected = _this.selected;
            if (!model ||
                !model.get('selectable') ||
                // Avoid selecting children of selected components
                model.parents().some(function (parent) { return selected.hasComponent(parent); })) {
                return;
            }
            opts.forceChange && _this.removeSelected(model, opts);
            // Remove from selection, children of the component to select
            var toDeselect = selected.allComponents().filter(function (cmp) { return (0,index_all.contains)(cmp.parents(), model); });
            toDeselect.forEach(function (cmp) { return _this.removeSelected(cmp, opts); });
            selected.addComponent(model, opts);
            _this.trigger('component:select', model, opts);
            _this.Canvas.addSpot({
                type: CanvasSpot/* CanvasSpotBuiltInTypes */.q.Select,
                component: model,
            });
        });
    };
    /**
     * Remove component from selection
     * @param  {Component|Array<Component>} component Component to select
     * @param  {Object} [opts={}] Options, optional
     * @public
     */
    EditorModel.prototype.removeSelected = function (component, opts) {
        var _this = this;
        if (opts === void 0) { opts = {}; }
        this.selected.removeComponent(component, opts);
        var cmps = (0,index_all.isArray)(component) ? component : [component];
        cmps.forEach(function (component) {
            return _this.Canvas.removeSpots({
                type: CanvasSpot/* CanvasSpotBuiltInTypes */.q.Select,
                component: component,
            });
        });
    };
    /**
     * Toggle component selection
     * @param  {Component|Array<Component>} component Component to select
     * @param  {Object} [opts={}] Options, optional
     * @public
     */
    EditorModel.prototype.toggleSelected = function (component, opts) {
        var _this = this;
        if (opts === void 0) { opts = {}; }
        var models = (0,index_all.isArray)(component) ? component : [component];
        models.forEach(function (model) {
            if (_this.selected.hasComponent(model)) {
                _this.removeSelected(model, opts);
            }
            else {
                _this.addSelected(model, opts);
            }
        });
    };
    /**
     * Hover a component
     * @param  {Component|Array<Component>} cmp Component to select
     * @param  {Object} [opts={}] Options, optional
     * @private
     */
    EditorModel.prototype.setHovered = function (cmp, opts) {
        var _this = this;
        if (opts === void 0) { opts = {}; }
        var upHovered = function (cmp, opts) {
            var _a = _this, config = _a.config, Canvas = _a.Canvas;
            var current = _this.getHovered();
            var selectedAll = _this.getSelectedAll();
            var typeHover = CanvasSpot/* CanvasSpotBuiltInTypes */.q.Hover;
            var typeSpacing = CanvasSpot/* CanvasSpotBuiltInTypes */.q.Spacing;
            _this.set('componentHovered', cmp || null, opts);
            if (current) {
                Canvas.removeSpots({ type: typeHover, component: current });
                Canvas.removeSpots({ type: typeSpacing, component: current });
            }
            if (cmp) {
                Canvas.addSpot({ type: typeHover, component: cmp });
                if (!selectedAll.includes(cmp) || config.showOffsetsSelected) {
                    Canvas.addSpot({ type: typeSpacing, component: cmp });
                }
            }
        };
        if (!cmp) {
            return upHovered();
        }
        var ev = 'component:hover';
        opts.forceChange && upHovered();
        this.trigger("".concat(ev, ":before"), cmp, opts);
        // Check for valid hoverable
        if (!cmp.get('hoverable')) {
            if (opts.useValid && !opts.abort) {
                var parent_2 = cmp.parent();
                while (parent_2 && !parent_2.get('hoverable'))
                    parent_2 = parent_2.parent();
                cmp = parent_2;
            }
            else {
                return;
            }
        }
        if (!opts.abort) {
            upHovered(cmp, opts);
            this.trigger(ev, cmp, opts);
        }
    };
    EditorModel.prototype.getHovered = function () {
        return this.get('componentHovered');
    };
    /**
     * Set components inside editor's canvas. This method overrides actual components
     * @param {Object|string} components HTML string or components model
     * @param {Object} opt the options object to be used by the [setComponents]{@link setComponents} method
     * @return {this}
     * @public
     */
    EditorModel.prototype.setComponents = function (components, opt) {
        if (opt === void 0) { opt = {}; }
        return this.Components.setComponents(components, opt);
    };
    /**
     * Returns components model from the editor's canvas
     * @return {Components}
     * @private
     */
    EditorModel.prototype.getComponents = function () {
        var cmp = this.Components;
        var cm = this.CodeManager;
        if (!cmp || !cm)
            return;
        var wrp = cmp.getComponents();
        return cm.getCode(wrp, 'json');
    };
    /**
     * Set style inside editor's canvas. This method overrides actual style
     * @param {Object|string} style CSS string or style model
     * @param {Object} opt the options object to be used by the `CssRules.add` method
     * @return {this}
     * @public
     */
    EditorModel.prototype.setStyle = function (style, opt) {
        if (opt === void 0) { opt = {}; }
        var cssc = this.Css;
        cssc.clear(opt);
        cssc.getAll().add(style, opt);
        return this;
    };
    /**
     * Add styles to the editor
     * @param {Array<Object>|Object|string} style CSS string or style model
     * @returns {Array<CssRule>}
     * @public
     */
    EditorModel.prototype.addStyle = function (style, opts) {
        if (opts === void 0) { opts = {}; }
        var res = this.getStyle().add(style, opts);
        return (0,index_all.isArray)(res) ? res : [res];
    };
    /**
     * Returns rules/style model from the editor's canvas
     * @return {Rules}
     * @private
     */
    EditorModel.prototype.getStyle = function () {
        return this.Css.getAll();
    };
    /**
     * Change the selector state
     * @param {String} value State value
     * @returns {this}
     */
    EditorModel.prototype.setState = function (value) {
        this.set('state', value);
        return this;
    };
    /**
     * Get the current selector state
     * @returns {String}
     */
    EditorModel.prototype.getState = function () {
        return this.get('state') || '';
    };
    /**
     * Returns HTML built inside canvas
     * @param {Object} [opts={}] Options
     * @returns {string} HTML string
     * @public
     */
    EditorModel.prototype.getHtml = function (opts) {
        if (opts === void 0) { opts = {}; }
        var config = this.config;
        var optsHtml = config.optsHtml;
        var js = config.jsInHtml ? this.getJs(opts) : '';
        var cmp = opts.component || this.Components.getComponent();
        var html = cmp
            ? this.CodeManager.getCode(cmp, 'html', Editor_assign(Editor_assign({}, optsHtml), opts))
            : '';
        html += js ? "<script>".concat(js, "</script>") : '';
        return html;
    };
    /**
     * Returns CSS built inside canvas
     * @param {Object} [opts={}] Options
     * @returns {string} CSS string
     * @public
     */
    EditorModel.prototype.getCss = function (opts) {
        if (opts === void 0) { opts = {}; }
        var config = this.config;
        var optsCss = config.optsCss;
        var avoidProt = opts.avoidProtected;
        var keepUnusedStyles = !(0,index_all.isUndefined)(opts.keepUnusedStyles) ? opts.keepUnusedStyles : config.keepUnusedStyles;
        var cssc = this.Css;
        var wrp = opts.component || this.Components.getComponent();
        var protCss = !avoidProt ? config.protectedCss : '';
        var css = wrp &&
            this.CodeManager.getCode(wrp, 'css', Editor_assign(Editor_assign({ cssc: cssc, keepUnusedStyles: keepUnusedStyles }, optsCss), opts));
        return wrp ? (opts.json ? css : protCss + css) : '';
    };
    /**
     * Returns JS of all components
     * @return {string} JS string
     * @public
     */
    EditorModel.prototype.getJs = function (opts) {
        if (opts === void 0) { opts = {}; }
        var wrp = opts.component || this.Components.getWrapper();
        return wrp ? this.CodeManager.getCode(wrp, 'js').trim() : '';
    };
    /**
     * Store data to the current storage.
     * @public
     */
    EditorModel.prototype.store = function (options) {
        return Editor_awaiter(this, void 0, void 0, function () {
            var data;
            return Editor_generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        data = this.storeData();
                        return [4 /*yield*/, this.Storage.store(data, options)];
                    case 1:
                        _a.sent();
                        this.clearDirtyCount();
                        return [2 /*return*/, data];
                }
            });
        });
    };
    /**
     * Load data from the current storage.
     * @public
     */
    EditorModel.prototype.load = function (options, loadOptions) {
        if (loadOptions === void 0) { loadOptions = {}; }
        return Editor_awaiter(this, void 0, void 0, function () {
            var result;
            return Editor_generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.Storage.load(options)];
                    case 1:
                        result = _a.sent();
                        this.loadData(result);
                        // Wait in order to properly update the dirty counter (#5385)
                        return [4 /*yield*/, (0,mixins.wait)()];
                    case 2:
                        // Wait in order to properly update the dirty counter (#5385)
                        _a.sent();
                        if (loadOptions.clear) {
                            this.UndoManager.clear();
                            this.clearDirtyCount();
                        }
                        return [2 /*return*/, result];
                }
            });
        });
    };
    EditorModel.prototype.storeData = function () {
        var result = {};
        // Sync content if there is an active RTE
        var editingCmp = this.getEditing();
        editingCmp && editingCmp.trigger('sync:content', { noCount: true });
        this.storables.forEach(function (m) {
            result = Editor_assign(Editor_assign({}, result), m.store(1));
        });
        return JSON.parse(JSON.stringify(result));
    };
    EditorModel.prototype.loadData = function (data) {
        if (data === void 0) { data = {}; }
        if (!(0,mixins.isEmptyObj)(data)) {
            this.storables.forEach(function (module) { return module.clear(); });
            this.storables.forEach(function (module) { return module.load(data); });
        }
        return data;
    };
    /**
     * Returns device model by name
     * @return {Device|null}
     * @private
     */
    EditorModel.prototype.getDeviceModel = function () {
        var name = this.get('device');
        return this.Devices.get(name);
    };
    /**
     * Run default command if setted
     * @param {Object} [opts={}] Options
     * @private
     */
    EditorModel.prototype.runDefault = function (opts) {
        if (opts === void 0) { opts = {}; }
        var command = this.get('Commands').get(this.config.defaultCommand);
        if (!command || this.defaultRunning)
            return;
        command.stop(this, this, opts);
        command.run(this, this, opts);
        this.defaultRunning = true;
    };
    /**
     * Stop default command
     * @param {Object} [opts={}] Options
     * @private
     */
    EditorModel.prototype.stopDefault = function (opts) {
        if (opts === void 0) { opts = {}; }
        var commands = this.get('Commands');
        var command = commands.get(this.config.defaultCommand);
        if (!command || !this.defaultRunning)
            return;
        command.stop(this, this, opts);
        this.defaultRunning = false;
    };
    /**
     * Update canvas dimensions and refresh data useful for tools positioning
     * @public
     */
    EditorModel.prototype.refreshCanvas = function (opts) {
        if (opts === void 0) { opts = {}; }
        this.Canvas.refresh({ spots: opts.tools });
    };
    /**
     * Clear all selected stuf inside the window, sometimes is useful to call before
     * doing some dragging opearation
     * @param {Window} win If not passed the current one will be used
     * @private
     */
    EditorModel.prototype.clearSelection = function (win) {
        var _a;
        var w = win || window;
        (_a = w.getSelection()) === null || _a === void 0 ? void 0 : _a.removeAllRanges();
    };
    /**
     * Get the current media text
     * @return {string}
     */
    EditorModel.prototype.getCurrentMedia = function () {
        var config = this.config;
        var device = this.getDeviceModel();
        var condition = config.mediaCondition;
        var preview = config.devicePreviewMode;
        var width = device && device.get('widthMedia');
        return device && width && !preview ? "(".concat(condition, ": ").concat(width, ")") : '';
    };
    /**
     * Return the component wrapper
     * @return {Component}
     */
    EditorModel.prototype.getWrapper = function () {
        return this.Components.getWrapper();
    };
    EditorModel.prototype.setCurrentFrame = function (frameView) {
        return this.set('currentFrame', frameView);
    };
    EditorModel.prototype.getCurrentFrame = function () {
        return this.get('currentFrame');
    };
    EditorModel.prototype.getCurrentFrameModel = function () {
        var _a;
        return (_a = (this.getCurrentFrame() || {})) === null || _a === void 0 ? void 0 : _a.model;
    };
    EditorModel.prototype.getIcon = function (icon) {
        var icons = this.config.icons || {};
        return icons[icon] || '';
    };
    /**
     * Return the count of changes made to the content and not yet stored.
     * This count resets at any `store()`
     * @return {number}
     */
    EditorModel.prototype.getDirtyCount = function () {
        return this.get('changesCount');
    };
    EditorModel.prototype.clearDirtyCount = function () {
        return this.set({ changesCount: 0 }, { isClear: true });
    };
    EditorModel.prototype.getZoomDecimal = function () {
        return this.Canvas.getZoomDecimal();
    };
    EditorModel.prototype.getZoomMultiplier = function () {
        return this.Canvas.getZoomMultiplier();
    };
    EditorModel.prototype.setDragMode = function (value) {
        return this.set('dmode', value);
    };
    EditorModel.prototype.getDragMode = function (component) {
        var mode = (component === null || component === void 0 ? void 0 : component.getDragMode()) || this.get('dmode');
        return mode || '';
    };
    EditorModel.prototype.t = function () {
        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            args[_i] = arguments[_i];
        }
        var i18n = this.get('I18n');
        return i18n === null || i18n === void 0 ? void 0 : i18n.t.apply(i18n, args);
    };
    /**
     * Returns true if the editor is in absolute mode
     * @returns {Boolean}
     */
    EditorModel.prototype.inAbsoluteMode = function (component) {
        return this.getDragMode(component) === 'absolute';
    };
    /**
     * Destroy editor
     */
    EditorModel.prototype.destroyAll = function () {
        var _this = this;
        var _a = this, config = _a.config, view = _a.view;
        var editor = this.getEditor();
        // @ts-ignore
        var _b = (config.grapesjs || {}).editors, editors = _b === void 0 ? [] : _b;
        var shallow = this.get('shallow');
        this._storageTimeout && clearTimeout(this._storageTimeout);
        shallow === null || shallow === void 0 ? void 0 : shallow.destroyAll();
        this.stopListening();
        this.stopDefault();
        this.modules
            .slice()
            .reverse()
            .forEach(function (mod) { return mod.destroy(); });
        view && view.remove();
        this.clear({ silent: true });
        this.destroyed = true;
        ['_config', 'view', '_previousAttributes', '_events', '_listeners'].forEach(
        //@ts-ignore
        function (i) { return (_this[i] = {}); });
        editors.splice(editors.indexOf(editor), 1);
        //@ts-ignore
        (0,mixins.hasWin)() && (0,cash_dom["default"])(config.el).empty().attr(this.attrsOrig);
    };
    EditorModel.prototype.getEditing = function () {
        var res = this.get('editing');
        return (res && res.model) || undefined;
    };
    EditorModel.prototype.setEditing = function (value) {
        this.set('editing', value);
        return this;
    };
    EditorModel.prototype.isEditing = function () {
        return !!this.get('editing');
    };
    EditorModel.prototype.log = function (msg, opts) {
        if (opts === void 0) { opts = {}; }
        var ns = opts.ns, _a = opts.level, level = _a === void 0 ? 'debug' : _a;
        this.trigger('log', msg, opts);
        level && this.trigger("log:".concat(level), msg, opts);
        if (ns) {
            var logNs = "log-".concat(ns);
            this.trigger(logNs, msg, opts);
            level && this.trigger("".concat(logNs, ":").concat(level), msg, opts);
        }
    };
    EditorModel.prototype.logInfo = function (msg, opts) {
        this.log(msg, Editor_assign(Editor_assign({}, opts), { level: 'info' }));
    };
    EditorModel.prototype.logWarning = function (msg, opts) {
        this.log(msg, Editor_assign(Editor_assign({}, opts), { level: 'warning' }));
    };
    EditorModel.prototype.logError = function (msg, opts) {
        this.log(msg, Editor_assign(Editor_assign({}, opts), { level: 'error' }));
    };
    EditorModel.prototype.initBaseColorPicker = function (el, opts) {
        if (opts === void 0) { opts = {}; }
        var config = this.config;
        var _a = config.colorPicker, colorPicker = _a === void 0 ? {} : _a;
        var elToAppend = config.el;
        var ppfx = config.stylePrefix;
        //@ts-ignore
        return (0,cash_dom["default"])(el).spectrum(Editor_assign(Editor_assign({ containerClassName: "".concat(ppfx, "one-bg ").concat(ppfx, "two-color"), appendTo: elToAppend || 'body', maxSelectionSize: 8, showPalette: true, palette: [], showAlpha: true, chooseText: 'Ok', cancelText: '⨯' }, opts), colorPicker));
    };
    /**
     * Execute actions without triggering the storage and undo manager.
     * @param  {Function} clb
     * @private
     */
    EditorModel.prototype.skip = function (clb) {
        this.__skip = true;
        var um = this.UndoManager;
        um ? um.skip(clb) : clb();
        this.__skip = false;
    };
    /**
     * Set/get data from the HTMLElement
     * @param  {HTMLElement} el
     * @param  {string} name Data name
     * @param  {any} value Date value
     * @return {any}
     * @private
     */
    EditorModel.prototype.data = function (el, name, value) {
        var varName = '_gjs-data';
        if (!el[varName]) {
            el[varName] = {};
        }
        if ((0,index_all.isUndefined)(value)) {
            return el[varName][name];
        }
        else {
            el[varName][name] = value;
        }
    };
    return EditorModel;
}(common/* Model */.Hn));
/* harmony default export */ const model_Editor = (EditorModel);

;// CONCATENATED MODULE: ./src/editor/view/EditorView.ts
var view_EditorView_extends = (undefined && undefined.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();


var EditorView_EditorView = /** @class */ (function (_super) {
    view_EditorView_extends(EditorView, _super);
    function EditorView(model) {
        var _this = _super.call(this, { model: model }) || this;
        //const { model } = this;
        var _a = model.attributes, Panels = _a.Panels, UndoManager = _a.UndoManager;
        model.view = _this;
        model.once('change:ready', function () {
            Panels.active();
            Panels.disableButtons();
            UndoManager.clear();
            setTimeout(function () {
                model.trigger('load', model.get('Editor'));
                model.clearDirtyCount();
            });
        });
        return _this;
    }
    EditorView.prototype.render = function () {
        var _this = this;
        var _a = this, $el = _a.$el, model = _a.model;
        var _b = model.attributes, Panels = _b.Panels, Canvas = _b.Canvas;
        var config = model.config, modules = model.modules;
        var pfx = config.stylePrefix;
        var classNames = ["".concat(pfx, "editor")];
        !config.customUI && classNames.push("".concat(pfx, "one-bg ").concat(pfx, "two-color"));
        // @ts-ignore
        var contEl = (0,cash_dom["default"])(config.el || "body ".concat(config.container));
        config.cssIcons && (0,mixins.appendStyles)(config.cssIcons, { unique: true, prepand: true });
        $el.empty();
        // @ts-ignore
        if (config.width)
            contEl.css('width', config.width);
        // @ts-ignore
        if (config.height)
            contEl.css('height', config.height);
        $el.append(Canvas.render());
        $el.append(Panels.render());
        // Load shallow editor
        var shallow = model.get('shallow');
        var shallowCanvasEl = shallow.get('Canvas').render();
        shallowCanvasEl.style.display = 'none';
        $el.append(shallowCanvasEl);
        $el.attr('class', classNames.join(' '));
        // @ts-ignore
        contEl.addClass("".concat(pfx, "editor-cont")).empty().append($el);
        modules.forEach(function (md) { return md.postRender && md.postRender(_this); });
        return this;
    };
    return EditorView;
}(common/* View */.G7));
/* harmony default export */ const view_EditorView = (EditorView_EditorView);

;// CONCATENATED MODULE: ./src/editor/index.ts
var editor_assign = (undefined && undefined.__assign) || function () {
    editor_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return editor_assign.apply(this, arguments);
};
var editor_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var editor_generator = (undefined && undefined.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var editor_spreadArray = (undefined && undefined.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};




var Editor = /** @class */ (function () {
    function Editor(config, opts) {
        if (config === void 0) { config = {}; }
        if (opts === void 0) { opts = {}; }
        var _a;
        /**
         * Print safe HTML by using ES6 tagged template strings.
         * @param {Array<String>} literals
         * @param  {Array<String>} substs
         * @returns {String}
         * @example
         * const unsafeStr = '<script>....</script>';
         * const safeStr = '<b>Hello</b>';
         * // Use `$${var}` to avoid escaping
         * const strHtml = editor.html`Escaped ${unsafeStr} unescaped $${safeStr}`;
         */
        this.html = html;
        this.config = editor_assign(editor_assign(editor_assign({}, config_config), config), { pStylePrefix: (_a = config.stylePrefix) !== null && _a !== void 0 ? _a : config_config.stylePrefix });
        this.em = new model_Editor(this.config);
        this.$ = opts.$;
        this.em.init(this);
        this.editor = this.em;
    }
    Object.defineProperty(Editor.prototype, "Config", {
        get: function () {
            return this.em.config;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Editor.prototype, "I18n", {
        get: function () {
            return this.em.I18n;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Editor.prototype, "Utils", {
        get: function () {
            return this.em.Utils;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Editor.prototype, "Commands", {
        get: function () {
            return this.em.Commands;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Editor.prototype, "Keymaps", {
        get: function () {
            return this.em.Keymaps;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Editor.prototype, "Modal", {
        get: function () {
            return this.em.Modal;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Editor.prototype, "Panels", {
        get: function () {
            return this.em.Panels;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Editor.prototype, "Canvas", {
        get: function () {
            return this.em.Canvas;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Editor.prototype, "Parser", {
        get: function () {
            return this.em.Parser;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Editor.prototype, "CodeManager", {
        get: function () {
            return this.em.CodeManager;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Editor.prototype, "UndoManager", {
        get: function () {
            return this.em.UndoManager;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Editor.prototype, "RichTextEditor", {
        get: function () {
            return this.em.RichTextEditor;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Editor.prototype, "Pages", {
        get: function () {
            return this.em.Pages;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Editor.prototype, "Components", {
        get: function () {
            return this.em.Components;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Editor.prototype, "DomComponents", {
        get: function () {
            return this.em.Components;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Editor.prototype, "Layers", {
        get: function () {
            return this.em.Layers;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Editor.prototype, "LayerManager", {
        get: function () {
            return this.em.Layers;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Editor.prototype, "Css", {
        get: function () {
            return this.em.Css;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Editor.prototype, "CssComposer", {
        get: function () {
            return this.em.Css;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Editor.prototype, "Storage", {
        get: function () {
            return this.em.Storage;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Editor.prototype, "StorageManager", {
        get: function () {
            return this.em.Storage;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Editor.prototype, "Assets", {
        get: function () {
            return this.em.Assets;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Editor.prototype, "AssetManager", {
        get: function () {
            return this.em.Assets;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Editor.prototype, "Blocks", {
        get: function () {
            return this.em.Blocks;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Editor.prototype, "BlockManager", {
        get: function () {
            return this.em.Blocks;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Editor.prototype, "Traits", {
        get: function () {
            return this.em.Traits;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Editor.prototype, "TraitManager", {
        get: function () {
            return this.em.Traits;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Editor.prototype, "Selectors", {
        get: function () {
            return this.em.Selectors;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Editor.prototype, "SelectorManager", {
        get: function () {
            return this.em.Selectors;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Editor.prototype, "Styles", {
        get: function () {
            return this.em.Styles;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Editor.prototype, "StyleManager", {
        get: function () {
            return this.em.Styles;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Editor.prototype, "Devices", {
        get: function () {
            return this.em.Devices;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Editor.prototype, "DeviceManager", {
        get: function () {
            return this.em.Devices;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Editor.prototype, "EditorModel", {
        get: function () {
            return this.em;
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Returns configuration object
     * @returns {any} Returns the configuration object or the value of the specified property
     */
    Editor.prototype.getConfig = function (prop) {
        return this.em.getConfig(prop);
    };
    /**
     * Returns HTML built inside canvas
     * @param {Object} [opts={}] Options
     * @param {Component} [opts.component] Return the HTML of a specific Component
     * @param {Boolean} [opts.cleanId=false] Remove unnecessary IDs (eg. those created automatically)
     * @returns {string} HTML string
     */
    Editor.prototype.getHtml = function (opts) {
        return this.em.getHtml(opts);
    };
    /**
     * Returns CSS built inside canvas
     * @param {Object} [opts={}] Options
     * @param {Component} [opts.component] Return the CSS of a specific Component
     * @param {Boolean} [opts.json=false] Return an array of CssRules instead of the CSS string
     * @param {Boolean} [opts.avoidProtected=false] Don't include protected CSS
     * @param {Boolean} [opts.onlyMatched=false] Return only rules matched by the passed component.
     * @param {Boolean} [opts.keepUnusedStyles=false] Force keep all defined rules. Toggle on in case output looks different inside/outside of the editor.
     * @returns {String|Array<CssRule>} CSS string or array of CssRules
     */
    Editor.prototype.getCss = function (opts) {
        return this.em.getCss(opts);
    };
    /**
     * Returns JS of all components
     * @param {Object} [opts={}] Options
     * @param {Component} [opts.component] Get the JS of a specific component
     * @returns {String} JS string
     */
    Editor.prototype.getJs = function (opts) {
        return this.em.getJs(opts);
    };
    /**
     * Return the complete tree of components. Use `getWrapper` to include also the wrapper
     * @return {Components}
     */
    Editor.prototype.getComponents = function () {
        return this.Components.getComponents();
    };
    /**
     * Return the wrapper and its all components
     * @return {Component}
     */
    Editor.prototype.getWrapper = function () {
        return this.Components.getWrapper();
    };
    /**
     * Set components inside editor's canvas. This method overrides actual components
     * @param {Array<Object>|Object|string} components HTML string or components model
     * @param {Object} opt the options object to be used by the [setComponents]{@link em#setComponents} method
     * @return {this}
     * @example
     * editor.setComponents('<div class="cls">New component</div>');
     * // or
     * editor.setComponents({
     *  type: 'text',
     *   classes:['cls'],
     *   content: 'New component'
     * });
     */
    Editor.prototype.setComponents = function (components, opt) {
        if (opt === void 0) { opt = {}; }
        this.em.setComponents(components, opt);
        return this;
    };
    /**
     * Add components
     * @param {Array<Object>|Object|string} components HTML string or components model
     * @param {Object} opts Options
     * @param {Boolean} [opts.avoidUpdateStyle=false] If the HTML string contains styles,
     * by default, they will be created and, if already exist, updated. When this option
     * is true, styles already created will not be updated.
     * @return {Array<Component>}
     * @example
     * editor.addComponents('<div class="cls">New component</div>');
     * // or
     * editor.addComponents({
     *  type: 'text',
     *   classes:['cls'],
     *   content: 'New component'
     * });
     */
    Editor.prototype.addComponents = function (components, opts) {
        return this.getWrapper().append(components, opts);
    };
    /**
     * Returns style in JSON format object
     * @return {Object}
     */
    Editor.prototype.getStyle = function () {
        return this.em.Css.getAll();
    };
    /**
     * Set style inside editor's canvas. This method overrides actual style
     * @param {Array<Object>|Object|string} style CSS string or style model
     * @return {this}
     * @example
     * editor.setStyle('.cls{color: red}');
     * //or
     * editor.setStyle({
     *   selectors: ['cls'],
     *   style: { color: 'red' }
     * });
     */
    Editor.prototype.setStyle = function (style, opt) {
        if (opt === void 0) { opt = {}; }
        this.em.setStyle(style, opt);
        return this;
    };
    /**
     * Add styles to the editor
     * @param {Array<Object>|Object|string} style CSS string or style model
     * @returns {Array<CssRule>} Array of created CssRule instances
     * @example
     * editor.addStyle('.cls{color: red}');
     */
    Editor.prototype.addStyle = function (style, opts) {
        if (opts === void 0) { opts = {}; }
        return this.em.addStyle(style, opts);
    };
    /**
     * Returns the last selected component, if there is one
     * @return {Model}
     */
    Editor.prototype.getSelected = function () {
        return this.em.getSelected();
    };
    /**
     * Returns an array of all selected components
     * @return {Array}
     */
    Editor.prototype.getSelectedAll = function () {
        return this.em.getSelectedAll();
    };
    /**
     * Get a stylable entity from the selected component.
     * If you select a component without classes the entity is the Component
     * itself and all changes will go inside its 'style' attribute. Otherwise,
     * if the selected component has one or more classes, the function will
     * return the corresponding CSS Rule
     * @return {Model}
     */
    Editor.prototype.getSelectedToStyle = function () {
        var selected = this.em.getSelected();
        if (selected) {
            return this.StyleManager.getModelToStyle(selected);
        }
    };
    /**
     * Select a component
     * @param  {Component|HTMLElement} el Component to select
     * @param  {Object} [opts] Options
     * @param  {Boolean} [opts.scroll] Scroll canvas to the selected element
     * @return {this}
     * @example
     * // Select dropped block
     * editor.on('block:drag:stop', function(model) {
     *  editor.select(model);
     * });
     */
    Editor.prototype.select = function (el, opts) {
        this.em.setSelected(el, opts);
        return this;
    };
    /**
     * Add component to selection
     * @param  {Component|HTMLElement|Array} el Component to select
     * @return {this}
     * @example
     * editor.selectAdd(model);
     */
    // selectAdd(el: Parameters<EditorModel['addSelected']>[0]) {
    Editor.prototype.selectAdd = function (el) {
        this.em.addSelected(el);
        return this;
    };
    /**
     * Remove component from selection
     * @param  {Component|HTMLElement|Array} el Component to select
     * @return {this}
     * @example
     * editor.selectRemove(model);
     */
    Editor.prototype.selectRemove = function (el) {
        this.em.removeSelected(el);
        return this;
    };
    /**
     * Toggle component selection
     * @param  {Component|HTMLElement|Array} el Component to select
     * @return {this}
     * @example
     * editor.selectToggle(model);
     */
    Editor.prototype.selectToggle = function (el) {
        this.em.toggleSelected(el);
        return this;
    };
    /**
     * Returns, if active, the Component enabled in rich text editing mode.
     * @returns {Component|null}
     * @example
     * const textComp = editor.getEditing();
     * if (textComp) {
     *  console.log('HTML: ', textComp.toHTML());
     * }
     */
    Editor.prototype.getEditing = function () {
        return this.em.getEditing();
    };
    /**
     * Set device to the editor. If the device exists it will
     * change the canvas to the proper width
     * @param {string} name Name of the device
     * @return {this}
     * @example
     * editor.setDevice('Tablet');
     */
    Editor.prototype.setDevice = function (name) {
        this.em.set('device', name);
        return this;
    };
    /**
     * Return the actual active device
     * @return {string} Device name
     * @example
     * var device = editor.getDevice();
     * console.log(device);
     * // 'Tablet'
     */
    Editor.prototype.getDevice = function () {
        return this.em.get('device');
    };
    /**
     * Execute command
     * @param {string} id Command ID
     * @param {Object} options Custom options
     * @return {*} The return is defined by the command
     * @example
     * editor.runCommand('myCommand', {someValue: 1});
     */
    Editor.prototype.runCommand = function (id, options) {
        if (options === void 0) { options = {}; }
        return this.Commands.run(id, options);
    };
    /**
     * Stop the command if stop method was provided
     * @param {string} id Command ID
     * @param {Object} options Custom options
     * @return {*} The return is defined by the command
     * @example
     * editor.stopCommand('myCommand', {someValue: 1});
     */
    Editor.prototype.stopCommand = function (id, options) {
        if (options === void 0) { options = {}; }
        return this.Commands.stop(id, options);
    };
    /**
     * Store data to the current storage.
     * This will reset the counter of changes (`editor.getDirtyCount()`).
     * @param {Object} [options] Storage options.
     * @returns {Object} Stored data.
     * @example
     * const storedData = await editor.store();
     */
    Editor.prototype.store = function (options) {
        return editor_awaiter(this, void 0, void 0, function () {
            return editor_generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.em.store(options)];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    /**
     * Load data from the current storage.
     * @param {Object} [options] Storage options.
     * @param {Object} [loadOptions={}] Load options.
     * @param {Boolean} [loadOptions.clear=false] Clear the editor state (eg. dirty counter, undo manager, etc.).
     * @returns {Object} Loaded data.
     * @example
     * const data = await editor.load();
     */
    Editor.prototype.load = function (options, loadOptions) {
        if (loadOptions === void 0) { loadOptions = {}; }
        return editor_awaiter(this, void 0, void 0, function () {
            return editor_generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.em.load(options, loadOptions)];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    /**
     * Get the JSON project data, which could be stored and loaded back with `editor.loadProjectData(json)`
     * @returns {Object}
     * @example
     * console.log(editor.getProjectData());
     * // { pages: [...], styles: [...], ... }
     */
    Editor.prototype.getProjectData = function () {
        return this.em.storeData();
    };
    /**
     * Load data from the JSON project
     * @param {Object} data Project to load
     * @example
     * editor.loadProjectData({ pages: [...], styles: [...], ... })
     */
    Editor.prototype.loadProjectData = function (data) {
        return this.em.loadData(data);
    };
    Editor.prototype.storeData = function () {
        return this.em.storeData();
    };
    Editor.prototype.loadData = function (data) {
        return this.em.loadData(data);
    };
    /**
     * Returns container element. The one which was indicated as 'container'
     * on init method
     * @return {HTMLElement}
     */
    Editor.prototype.getContainer = function () {
        return this.config.el;
    };
    /**
     * Return the count of changes made to the content and not yet stored.
     * This count resets at any `store()`
     * @return {number}
     */
    Editor.prototype.getDirtyCount = function () {
        return this.em.getDirtyCount();
    };
    /**
     * Reset the counter of changes.
     */
    Editor.prototype.clearDirtyCount = function () {
        return this.em.clearDirtyCount();
    };
    /**
     * Update editor dimension offsets
     *
     * This method could be useful when you update, for example, some position
     * of the editor element (eg. canvas, panels, etc.) with CSS, where without
     * refresh you'll get misleading position of tools
     * @param {Object} [options] Options
     * @param {Boolean} [options.tools=false] Update the position of tools (eg. rich text editor, component highlighter, etc.)
     */
    Editor.prototype.refresh = function (opts) {
        this.em.refreshCanvas(opts);
    };
    /**
     * Replace the built-in Rich Text Editor with a custom one.
     * @param {Object} obj Custom RTE Interface
     * @example
     * editor.setCustomRte({
     *   // Function for enabling custom RTE
     *   // el is the HTMLElement of the double clicked Text Component
     *   // rte is the same instance you have returned the first time you call
     *   // enable(). This is useful if need to check if the RTE is already enabled so
     *   // ion this case you'll need to return the RTE and the end of the function
     *   enable: function(el, rte) {
     *     rte = new MyCustomRte(el, {}); // this depends on the Custom RTE API
     *     ...
     *     return rte; // return the RTE instance
     *   }
     *
     *   // Disable the editor, called for example when you unfocus the Text Component
     *  disable: function(el, rte) {
     *     rte.blur(); // this depends on the Custom RTE API
     *  }
     *
     * // Called when the Text Component is focused again. If you returned the RTE instance
     * // from the enable function, the enable won't be called again instead will call focus,
     * // in this case to avoid double binding of the editor
     *  focus: function (el, rte) {
     *   rte.focus(); // this depends on the Custom RTE API
     *  }
     * });
     */
    Editor.prototype.setCustomRte = function (obj) {
        this.RichTextEditor.customRte = obj;
    };
    /**
     * Replace the default CSS parser with a custom one.
     * The parser function receives a CSS string as a parameter and expects
     * an array of CSSRule objects as a result. If you need to remove the
     * custom parser, pass `null` as the argument
     * @param {Function|null} parser Parser function
     * @return {this}
     * @example
     * editor.setCustomParserCss(css => {
     *  const result = [];
     *  // ... parse the CSS string
     *  result.push({
     *    selectors: '.someclass, div .otherclass',
     *    style: { color: 'red' }
     *  })
     *  // ...
     *  return result;
     * });
     */
    Editor.prototype.setCustomParserCss = function (parser) {
        this.Parser.getConfig().parserCss = parser;
        return this;
    };
    /**
     * Change the global drag mode of components.
     * To get more about this feature read: https://github.com/GrapesJS/grapesjs/issues/1936
     * @param {String} value Drag mode, options: 'absolute' | 'translate'
     * @returns {this}
     */
    Editor.prototype.setDragMode = function (value) {
        this.em.setDragMode(value);
        return this;
    };
    /**
     * Trigger event log message
     * @param  {*} msg Message to log
     * @param  {Object} [opts={}] Custom options
     * @param  {String} [opts.ns=''] Namespace of the log (eg. to use in plugins)
     * @param  {String} [opts.level='debug'] Level of the log, `debug`, `info`, `warning`, `error`
     * @return {this}
     * @example
     * editor.log('Something done!', { ns: 'from-plugin-x', level: 'info' });
     * // This will trigger following events
     * // `log`, `log:info`, `log-from-plugin-x`, `log-from-plugin-x:info`
     * // Callbacks of those events will always receive the message and
     * // options, as arguments, eg:
     * // editor.on('log:info', (msg, opts) => console.info(msg, opts))
     */
    Editor.prototype.log = function (msg, opts) {
        if (opts === void 0) { opts = {}; }
        this.em.log(msg, opts);
        return this;
    };
    /**
     * Translate label
     * @param {String} key Label to translate
     * @param {Object} [opts] Options for the translation
     * @param {Object} [opts.params] Params for the translation
     * @param {Boolean} [opts.noWarn] Avoid warnings in case of missing resources
     * @returns {String}
     * @example
     * editor.t('msg');
     * // use params
     * editor.t('msg2', { params: { test: 'hello' } });
     * // custom local
     * editor.t('msg2', { params: { test: 'hello' } l: 'it' });
     */
    Editor.prototype.t = function () {
        var _a;
        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            args[_i] = arguments[_i];
        }
        return (_a = this.em).t.apply(_a, args);
    };
    /**
     * Attach event
     * @param  {string} event Event name
     * @param  {Function} callback Callback function
     * @return {this}
     */
    Editor.prototype.on = function (event, callback) {
        this.em.on(event, callback);
        return this;
    };
    /**
     * Attach event and detach it after the first run
     * @param  {string} event Event name
     * @param  {Function} callback Callback function
     * @return {this}
     */
    Editor.prototype.once = function (event, callback) {
        this.em.once(event, callback);
        return this;
    };
    /**
     * Detach event
     * @param  {string} event Event name
     * @param  {Function} callback Callback function
     * @return {this}
     */
    Editor.prototype.off = function (event, callback) {
        this.em.off(event, callback);
        return this;
    };
    /**
     * Trigger event
     * @param  {string} event Event to trigger
     * @return {this}
     */
    Editor.prototype.trigger = function (event) {
        var args = [];
        for (var _i = 1; _i < arguments.length; _i++) {
            args[_i - 1] = arguments[_i];
        }
        this.em.trigger.apply(this.em, editor_spreadArray([event], args, true));
        return this;
    };
    /**
     * Destroy the editor
     */
    Editor.prototype.destroy = function () {
        if (!this.em)
            return;
        this.em.destroyAll();
        this.editorView = undefined;
    };
    /**
     * Returns editor element
     * @return {HTMLElement}
     * @private
     */
    Editor.prototype.getEl = function () {
        var _a;
        return (_a = this.editorView) === null || _a === void 0 ? void 0 : _a.el;
    };
    /**
     * Returns editor model
     * @return {Model}
     * @private
     */
    Editor.prototype.getModel = function () {
        return this.em;
    };
    /**
     * Render editor
     * @return {HTMLElement}
     */
    Editor.prototype.render = function () {
        var _a;
        (_a = this.editorView) === null || _a === void 0 ? void 0 : _a.remove();
        this.editorView = new view_EditorView(this.em);
        return this.editorView.render().el;
    };
    /**
     * Trigger a callback once the editor is loaded and rendered.
     * The callback will be executed immediately if the method is called on the already rendered editor.
     * @param  {Function} clb Callback to trigger
     * @example
     * editor.onReady(() => {
     *   // perform actions
     * });
     */
    Editor.prototype.onReady = function (clb) {
        this.em.get('ready') ? clb(this) : this.em.on('load', clb);
    };
    return Editor;
}());
/* harmony default export */ const src_editor = (Editor);

;// CONCATENATED MODULE: ./src/plugin_manager/index.ts


var getPluginById = function (pluginId, plugins) {
    var result = plugins.get(pluginId);
    // Try to search in global context
    if (!result) {
        var wplg = (0,mixins.getGlobal)()[pluginId];
        result = (wplg === null || wplg === void 0 ? void 0 : wplg.default) || wplg;
    }
    return result;
};
var getPlugin = function (plugin, plugins) {
    return (0,index_all.isString)(plugin)
        ? getPluginById(plugin, plugins)
        : (plugin === null || plugin === void 0 ? void 0 : plugin.default) || plugin;
};
var logPluginWarn = function (editor, plugin) {
    editor.getModel().logWarning("Plugin ".concat(plugin, " not found"), {
        context: 'plugins',
        plugin: plugin,
    });
};
var PluginManager = /** @class */ (function () {
    function PluginManager() {
        this.plugins = {};
    }
    /**
     * Add new plugin. Plugins could not be overwritten
     * @param {string} id Plugin ID
     * @param {Function} plugin Function which contains all plugin logic
     * @return {Function} The plugin function
     * @deprecated Don't use named plugins, create plugins as simple functions. More about [Plugins](https://grapesjs.com/docs/modules/Plugins.html)
     * @example
     * PluginManager.add('some-plugin', function(editor) {
     *   editor.Commands.add('new-command', {
     *     run:  function(editor, senderBtn){
     *       console.log('Executed new-command');
     *     }
     *   })
     * });
     */
    PluginManager.prototype.add = function (id, plugin) {
        var plg = this.get(id);
        if (plg) {
            return plg;
        }
        // @ts-ignore
        this.plugins[id] = plugin;
        return plugin;
    };
    /**
     * Returns plugin by ID
     * @param  {string} id Plugin ID
     * @return {Function|undefined} Plugin
     * @example
     * var plugin = PluginManager.get('some-plugin');
     * plugin(editor);
     */
    PluginManager.prototype.get = function (id) {
        return this.plugins[id];
    };
    /**
     * Returns object with all plugins
     */
    PluginManager.prototype.getAll = function () {
        return this.plugins;
    };
    return PluginManager;
}());
/* harmony default export */ const plugin_manager = (PluginManager);

;// CONCATENATED MODULE: ./src/utils/polyfills.ts
/**
 * File made for IE/Edge support
 * https://github.com/GrapesJS/grapesjs/issues/214
 */

/* harmony default export */ const polyfills = (function () {
    /**
     * Check if IE/Edge
     * @return {Boolean}
     */
    var isIE = function () {
        var match;
        var agent = window.navigator.userAgent;
        var rules = [
            ['edge', /Edge\/([0-9\._]+)/],
            ['ie', /MSIE\s(7\.0)/],
            ['ie', /MSIE\s([0-9\.]+);.*Trident\/[4-7].0/],
            ['ie', /Trident\/7\.0.*rv\:([0-9\.]+).*\).*Gecko$/],
        ];
        for (var i = 0; i < rules.length; i++) {
            var rule = rules[i];
            match = rule[1].exec(agent);
            if (match)
                break;
        }
        return !!match;
    };
    if ((0,mixins.hasWin)() && isIE()) {
        var originalCreateHTMLDocument_1 = DOMImplementation.prototype.createHTMLDocument;
        DOMImplementation.prototype.createHTMLDocument = function (title) {
            if (!title)
                title = '';
            return originalCreateHTMLDocument_1.apply(document.implementation, [title]);
        };
    }
});

;// CONCATENATED MODULE: ./src/index.ts
var src_assign = (undefined && undefined.__assign) || function () {
    src_assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return src_assign.apply(this, arguments);
};





polyfills();
var plugins = new plugin_manager();
var editors = [];
var usePlugin = function (plugin, opts) {
    var pluginResult = getPlugin(plugin, plugins);
    return function (editor) {
        if (pluginResult) {
            pluginResult(editor, opts || {});
        }
        else {
            logPluginWarn(editor, plugin);
        }
    };
};
var grapesjs = {
    $: cash_dom["default"],
    editors: editors,
    plugins: plugins,
    usePlugin: usePlugin,
    // @ts-ignore Will be replaced on build
    version: '0.21.10',
    /**
     * Initialize the editor with passed options
     * @param {Object} config Configuration object
     * @param {string|HTMLElement} config.container Selector which indicates where render the editor
     * @param {Boolean} [config.autorender=true] If true, auto-render the content
     * @param {Array} [config.plugins=[]] Array of plugins to execute on start
     * @param {Object} [config.pluginsOpts={}] Custom options for plugins
     * @param {Boolean} [config.headless=false] Init headless editor
     * @return {Editor} Editor instance
     * @example
     * var editor = grapesjs.init({
     *   container: '#myeditor',
     *   components: '<article class="hello">Hello world</article>',
     *   style: '.hello{color: red}',
     * })
     */
    init: function (config) {
        if (config === void 0) { config = {}; }
        var headless = config.headless;
        var els = config.container;
        if (!els && !headless)
            throw new Error("'container' is required");
        var initConfig = src_assign(src_assign({ autorender: true, plugins: [], pluginsOpts: {} }, config), { grapesjs: this, el: headless ? undefined : (0,index_all.isElement)(els) ? els : document.querySelector(els) });
        var editor = new src_editor(initConfig, { $: cash_dom["default"] });
        var em = editor.getModel();
        // Load plugins
        initConfig.plugins.forEach(function (pluginId) {
            var plugin = getPlugin(pluginId, plugins);
            var plgOptions = initConfig.pluginsOpts[pluginId] || {};
            if (plugin) {
                plugin(editor, plgOptions);
            }
            else {
                logPluginWarn(editor, pluginId);
            }
        });
        // Execute `onLoad` on modules once all plugins are initialized.
        // A plugin might have extended/added some custom type so this
        // is a good point to load stuff like components, css rules, etc.
        em.loadOnStart();
        initConfig.autorender && !headless && editor.render();
        editors.push(editor);
        return editor;
    },
};
/* harmony default export */ const src_0 = (grapesjs);

})();

var __webpack_exports__default = __webpack_exports__.ZP;
var __webpack_exports__grapesjs = __webpack_exports__.kr;
var __webpack_exports__usePlugin = __webpack_exports__.j7;
export { __webpack_exports__default as default, __webpack_exports__grapesjs as grapesjs, __webpack_exports__usePlugin as usePlugin };

//# sourceMappingURL=grapes.mjs.map