diff --git a/dist/grapes.js b/dist/grapes.js index afe644c2b..243d4d62e 100644 --- a/dist/grapes.js +++ b/dist/grapes.js @@ -3704,7 +3704,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de var Backbone = __webpack_require__(0); var Components = __webpack_require__(49); var Selectors = __webpack_require__(10); -var Traits = __webpack_require__(148); +var Traits = __webpack_require__(151); var escapeRegExp = function escapeRegExp(str) { return str.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&'); @@ -3862,6 +3862,7 @@ module.exports = Backbone.Model.extend(_Styleable2.default).extend({ this.set('attributes', this.get('attributes') || {}); this.listenTo(this, 'change:script', this.scriptUpdated); this.listenTo(this, 'change:traits', this.traitsUpdated); + this.listenTo(this, 'change:tagName', this.tagUpdated); this.loadTraits(); this.initClasses(); this.initComponents(); @@ -3884,6 +3885,17 @@ module.exports = Backbone.Model.extend(_Styleable2.default).extend({ }, + /** + * Once the tag is updated I have to remove the node and replace it + */ + tagUpdated: function tagUpdated() { + var coll = this.collection; + var at = coll.indexOf(this); + coll.remove(this); + coll.add(this, { at: at }); + }, + + /** * Update attributes of the model * @param {Object} attrs Key value attributes @@ -16181,7 +16193,7 @@ var Property = __webpack_require__(12); module.exports = __webpack_require__(0).Collection.extend(_TypeableCollection2.default).extend({ types: [{ id: 'stack', - model: __webpack_require__(117), + model: __webpack_require__(120), view: __webpack_require__(34), isType: function isType(value) { if (value && value.type == 'stack') { @@ -16191,7 +16203,7 @@ module.exports = __webpack_require__(0).Collection.extend(_TypeableCollection2.d }, { id: 'composite', model: __webpack_require__(33), - view: __webpack_require__(18), + view: __webpack_require__(17), isType: function isType(value) { if (value && value.type == 'composite') { return value; @@ -16235,8 +16247,8 @@ module.exports = __webpack_require__(0).Collection.extend(_TypeableCollection2.d } }, { id: 'slider', - model: __webpack_require__(123), - view: __webpack_require__(124), + model: __webpack_require__(126), + view: __webpack_require__(127), isType: function isType(value) { if (value && value.type == 'slider') { return value; @@ -16457,7 +16469,7 @@ var PropertyRadioView = __webpack_require__(36); var PropertySelectView = __webpack_require__(37); var PropertyColorView = __webpack_require__(38); var PropertyFileView = __webpack_require__(40); -var PropertyCompositeView = __webpack_require__(18); +var PropertyCompositeView = __webpack_require__(17); var PropertyStackView = __webpack_require__(34); module.exports = Backbone.View.extend({ @@ -16522,7 +16534,7 @@ module.exports = Backbone.View.extend({ "use strict"; /* WEBPACK VAR INJECTION */(function(Backbone) { -var InputNumber = __webpack_require__(19); +var InputNumber = __webpack_require__(18); var $ = Backbone.$; module.exports = __webpack_require__(5).extend({ @@ -16662,308 +16674,6 @@ module.exports = g; /* 17 */ /***/ (function(module, exports, __webpack_require__) { -// keymaster.js -// (c) 2011-2013 Thomas Fuchs -// keymaster.js may be freely distributed under the MIT license. - -;(function(global){ - 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. 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. 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 the handlers globally on document - addEvent(document, 'keydown', function(event) { dispatch(event) }); // Passing _scope to a callback to ensure it remains the same by execution. Fixes #48 - addEvent(document, 'keyup', clearModifier); - - // reset modifiers to false whenever the window is (re)focused. - addEvent(window, 'focus', resetModifiers); - - // store previously defined key - var previousKey = global.key; - - // restore previously defined key and return reference to our key object - function noConflict() { - var k = global.key; - global.key = previousKey; - return k; - } - - // set window.key and window.key.set/get/deleteScope, and the default filter - global.key = assignKey; - global.key.setScope = setScope; - global.key.getScope = getScope; - global.key.deleteScope = deleteScope; - global.key.filter = filter; - global.key.isPressed = isPressed; - global.key.getPressedKeyCodes = getPressedKeyCodes; - global.key.noConflict = noConflict; - global.key.unbind = unbindKey; - - if(true) module.exports = assignKey; - -})(this); - - -/***/ }), -/* 18 */ -/***/ (function(module, exports, __webpack_require__) { - "use strict"; /* WEBPACK VAR INJECTION */(function(Backbone) { @@ -17090,7 +16800,7 @@ module.exports = PropertyView.extend({ /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0))) /***/ }), -/* 19 */ +/* 18 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -17381,7 +17091,7 @@ module.exports = Input.extend({ /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(1))) /***/ }), -/* 20 */ +/* 19 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -17446,7 +17156,7 @@ module.exports = Component.extend({ }); /***/ }), -/* 21 */ +/* 20 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -17563,7 +17273,7 @@ module.exports = Component.extend({ }); /***/ }), -/* 22 */ +/* 21 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -17577,9 +17287,9 @@ var _underscore = __webpack_require__(1); var _mixins = __webpack_require__(2); -var ToolbarView = __webpack_require__(184); -var Toolbar = __webpack_require__(186); -var key = __webpack_require__(17); +var ToolbarView = __webpack_require__(187); +var Toolbar = __webpack_require__(189); +var key = __webpack_require__(23); var Backbone = __webpack_require__(0); var showOffsets = void 0; var $ = Backbone.$; @@ -18196,7 +17906,7 @@ module.exports = { }; /***/ }), -/* 23 */ +/* 22 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -18436,6 +18146,308 @@ module.exports = _.extend({}, SelectPosition, { }); /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0), __webpack_require__(1))) +/***/ }), +/* 23 */ +/***/ (function(module, exports, __webpack_require__) { + +// keymaster.js +// (c) 2011-2013 Thomas Fuchs +// keymaster.js may be freely distributed under the MIT license. + +;(function(global){ + 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. 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. 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 the handlers globally on document + addEvent(document, 'keydown', function(event) { dispatch(event) }); // Passing _scope to a callback to ensure it remains the same by execution. Fixes #48 + addEvent(document, 'keyup', clearModifier); + + // reset modifiers to false whenever the window is (re)focused. + addEvent(window, 'focus', resetModifiers); + + // store previously defined key + var previousKey = global.key; + + // restore previously defined key and return reference to our key object + function noConflict() { + var k = global.key; + global.key = previousKey; + return k; + } + + // set window.key and window.key.set/get/deleteScope, and the default filter + global.key = assignKey; + global.key.setScope = setScope; + global.key.getScope = getScope; + global.key.deleteScope = deleteScope; + global.key.filter = filter; + global.key.isPressed = isPressed; + global.key.getPressedKeyCodes = getPressedKeyCodes; + global.key.noConflict = noConflict; + global.key.unbind = unbindKey; + + if(true) module.exports = assignKey; + +})(this); + + /***/ }), /* 24 */ /***/ (function(module, exports, __webpack_require__) { @@ -18447,7 +18459,7 @@ Object.defineProperty(exports, "__esModule", { value: true }); -var _promisePolyfill = __webpack_require__(73); +var _promisePolyfill = __webpack_require__(76); var _promisePolyfill2 = _interopRequireDefault(_promisePolyfill); @@ -19606,7 +19618,7 @@ module.exports = Backbone.Model.extend({ var Backbone = __webpack_require__(0); -var Button = __webpack_require__(107); +var Button = __webpack_require__(110); module.exports = Backbone.Collection.extend({ @@ -19795,7 +19807,7 @@ module.exports = Backbone.View.extend({ /* WEBPACK VAR INJECTION */(function(_) { var Backbone = __webpack_require__(0); -var ButtonView = __webpack_require__(109); +var ButtonView = __webpack_require__(112); module.exports = Backbone.View.extend({ initialize: function initialize(o) { @@ -19912,10 +19924,10 @@ var _extends = Object.assign || function (target) { for (var i = 1; i < argument */ module.exports = function () { var c = {}, - defaults = __webpack_require__(114), - Sectors = __webpack_require__(115), + defaults = __webpack_require__(117), + Sectors = __webpack_require__(118), Properties = __webpack_require__(11), - SectorsView = __webpack_require__(126); + SectorsView = __webpack_require__(129); var properties = void 0; var sectors, SectView; @@ -20482,8 +20494,8 @@ module.exports = Property.extend({ "use strict"; -var PropertyCompositeView = __webpack_require__(18); -var LayersView = __webpack_require__(121); +var PropertyCompositeView = __webpack_require__(17); +var LayersView = __webpack_require__(124); module.exports = PropertyCompositeView.extend({ templateInput: function templateInput() { @@ -20901,7 +20913,7 @@ module.exports = __webpack_require__(14).extend({ "use strict"; /* WEBPACK VAR INJECTION */(function(Backbone) { -__webpack_require__(120); +__webpack_require__(123); var Input = __webpack_require__(35); var $ = Backbone.$; @@ -21178,7 +21190,7 @@ module.exports = Property.extend({ var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var Property = __webpack_require__(12); -var InputNumber = __webpack_require__(19); +var InputNumber = __webpack_require__(18); module.exports = Property.extend({ @@ -22388,13 +22400,14 @@ module.exports = ComponentView.extend({ var content = this.getChildrenContainer().innerHTML; var comps = model.get('components'); comps.length && comps.reset(); + model.set('content', ''); // If there is a custom RTE the content is just baked staticly // inside 'content' if (rte.customRte) { // Avoid double content by removing its children components // and force to trigger change - model.set('content', '').set('content', content); + model.set('content', content); } else { var clean = function clean(model) { model.set({ @@ -22411,7 +22424,7 @@ module.exports = ComponentView.extend({ }; // Avoid re-render on reset with silent option - model.set('content', '').trigger('change:content', model); + model.trigger('change:content', model); comps.add(content); comps.each(function (model) { return clean(model); @@ -22568,7 +22581,7 @@ module.exports = { /* WEBPACK VAR INJECTION */(function(_) { var Backbone = __webpack_require__(0); -var CreateComponent = __webpack_require__(23); +var CreateComponent = __webpack_require__(22); module.exports = _.extend({}, CreateComponent, { init: function init() { @@ -22620,8 +22633,6 @@ module.exports = _.extend({}, CreateComponent, { if (!model) return; - if (this.em) this.em.editor.initChildrenComp(model); - this.afterInsert(model, this); }, @@ -23174,7 +23185,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de module.exports = function () { var defaultConfig = __webpack_require__(60); var Editor = __webpack_require__(61); - var PluginManager = __webpack_require__(218); + var PluginManager = __webpack_require__(219); var plugins = new PluginManager(); var editors = []; @@ -23187,7 +23198,7 @@ module.exports = function () { plugins: plugins, // Will be replaced on build - version: '0.12.52', + version: '0.12.53', /** * Initializes an editor based on passed options @@ -23271,9 +23282,6 @@ module.exports = { // Enable/Disable the possibility to copy(ctrl + c) & paste(ctrl + v) components copyPaste: true, - // Enable/Disable undo manager - undoManager: true, - // Storage Manager storageManager: {}, @@ -23301,7 +23309,7 @@ module.exports = function (config) { var c = config || {}, defaults = __webpack_require__(62), EditorModel = __webpack_require__(63), - EditorView = __webpack_require__(217); + EditorView = __webpack_require__(218); for (var name in defaults) { if (!(name in c)) c[name] = defaults[name]; @@ -23809,9 +23817,12 @@ module.exports = function (config) { * @return {HTMLElement} */ render: function render() { + var _this = this; + // Do post render stuff after the iframe is loaded otherwise it'll // be empty during tests em.on('loaded', function () { + _this.UndoManager.clear(); em.get('modules').forEach(function (module) { module.postRender && module.postRender(editorView); }); @@ -23874,6 +23885,8 @@ module.exports = function (config) { * * `stop:{commandName}` - Triggered when some command is called to stop (eg. editor.stopCommand('preview')) * ## General * * `canvasScroll` - Triggered when the canvas is scrolle + * * `undo` - Undo executed + * * `redo` - Redo executed * * `load` - When the editor is loaded * * @param {Object} config Configurations @@ -23924,9 +23937,6 @@ module.exports = { // Show an alert before unload the page with unsaved changes noticeOnUnload: true, - // Enable/Disable undo manager - undoManager: true, - // Show paddings and margins showOffsets: false, @@ -23993,6 +24003,9 @@ module.exports = { // Dom element el: '', + // Configurations for Undo Manager + undoManager: {}, + //Configurations for Asset Manager assetManager: {}, @@ -24099,14 +24112,12 @@ var _extends = Object.assign || function (target) { for (var i = 1; i < argument var _underscore = __webpack_require__(1); -var deps = [__webpack_require__(64), __webpack_require__(68), __webpack_require__(69), __webpack_require__(77), __webpack_require__(82), __webpack_require__(85), __webpack_require__(89), __webpack_require__(93), __webpack_require__(105), __webpack_require__(111), __webpack_require__(31), __webpack_require__(128), __webpack_require__(134), __webpack_require__(139), __webpack_require__(146), __webpack_require__(174), __webpack_require__(180), __webpack_require__(206)]; +var deps = [__webpack_require__(64), __webpack_require__(68), __webpack_require__(69), __webpack_require__(72), __webpack_require__(80), __webpack_require__(85), __webpack_require__(88), __webpack_require__(92), __webpack_require__(96), __webpack_require__(108), __webpack_require__(114), __webpack_require__(31), __webpack_require__(131), __webpack_require__(137), __webpack_require__(142), __webpack_require__(149), __webpack_require__(177), __webpack_require__(183), __webpack_require__(209)]; var Backbone = __webpack_require__(0); -var UndoManager = __webpack_require__(214); -var key = __webpack_require__(17); var timedInterval = void 0; -__webpack_require__(216)({ +__webpack_require__(217)({ Backbone: Backbone, $: Backbone.$ }); @@ -24129,6 +24140,8 @@ module.exports = Backbone.Model.extend({ }, initialize: function initialize() { + var _this = this; + var c = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; this.config = c; @@ -24139,11 +24152,8 @@ module.exports = Backbone.Model.extend({ // Load modules deps.forEach(function (name) { - this.loadModule(name); - }, this); - - this.initUndoManager(); - + return _this.loadModule(name); + }); this.on('change:selectedComponent', this.componentSelected, this); this.on('change:changesCount', this.updateChanges, this); }, @@ -24167,7 +24177,7 @@ module.exports = Backbone.Model.extend({ * @private */ loadOnStart: function loadOnStart() { - var _this = this; + var _this2 = this; var clb = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; @@ -24179,15 +24189,11 @@ module.exports = Backbone.Model.extend({ module.onLoad(); }); - // Stuff to do post load (eg. init undo manager for loaded components) + // Stuff to do post load var postLoad = function postLoad() { - // I've initialized undo manager in initialize() because otherwise the - // editor will unable to fetch the instance via 'editor.UndoManager' but - // I need to cleare the stack now as it was dirtied by 'onLoad' method - _this.um.clear(); - _this.initUndoManager(); - _this.get('modules').forEach(function (module) { - return module.postLoad && module.postLoad(_this); + var modules = _this2.get('modules'); + modules.forEach(function (module) { + return module.postLoad && module.postLoad(_this2); }); clb && clb(); }; @@ -24238,20 +24244,20 @@ module.exports = Backbone.Model.extend({ // Check if module is storable var sm = this.get('StorageManager'); + if (Mod.storageKey && Mod.store && Mod.load && sm) { cfg.stm = sm; var storables = this.get('storables'); storables.push(Mod); this.set('storables', storables); } + cfg.em = this; Mod.init(_extends({}, cfg)); // Bind the module to the editor model if public - if (!Mod.private) this.set(Mod.name, Mod); - - if (Mod.onLoad) this.get('toLoad').push(Mod); - + !Mod.private && this.set(Mod.name, Mod); + Mod.onLoad && this.get('toLoad').push(Mod); this.get('modules').push(Mod); return this; }, @@ -24271,31 +24277,6 @@ module.exports = Backbone.Model.extend({ }, - /** - * Listen for new rules - * @param {Object} collection - * @private - */ - listenRules: function listenRules(collection) { - this.stopListening(collection, 'add remove', this.listenRule); - this.listenTo(collection, 'add remove', this.listenRule); - collection.each(function (model) { - this.listenRule(model); - }, this); - }, - - - /** - * Listen for rule changes - * @param {Object} model - * @private - */ - listenRule: function listenRule(model) { - this.stopListening(model, 'change:style', this.handleUpdates); - this.listenTo(model, 'change:style', this.handleUpdates); - }, - - /** * This method handles updates on the editor and tries to store them * if requested and if the changesCount is exceeded @@ -24305,7 +24286,7 @@ module.exports = Backbone.Model.extend({ * @private * */ handleUpdates: function handleUpdates(model, val) { - var _this2 = this; + var _this3 = this; var opt = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; @@ -24317,90 +24298,12 @@ module.exports = Backbone.Model.extend({ timedInterval && clearInterval(timedInterval); timedInterval = setTimeout(function () { if (!opt.avoidStore) { - _this2.set('changesCount', _this2.get('changesCount') + 1, opt); + _this3.set('changesCount', _this3.get('changesCount') + 1, opt); } }, 0); }, - /** - * Initialize Undo manager - * @private - * */ - initUndoManager: function initUndoManager() { - var canvas = this.get('Canvas'); - - if (this.um) { - return; - } - - var cmp = this.get('DomComponents'); - if (cmp && this.config.undoManager) { - var that = this; - this.um = new UndoManager({ - register: [cmp.getComponents(), this.get('CssComposer').getAll()], - track: true - }); - this.UndoManager = this.um; - this.set('UndoManager', this.um); - - key('⌘+z, ctrl+z', function () { - if (canvas.isInputFocused()) { - return; - } - - that.um.undo(true); - that.trigger('component:update'); - }); - - key('⌘+shift+z, ctrl+shift+z', function () { - if (canvas.isInputFocused()) { - return; - } - that.um.redo(true); - that.trigger('component:update'); - }); - - var beforeCache; - var customUndoType = { - on: function on(model, value, opts) { - var opt = opts || {}; - if (!beforeCache) { - beforeCache = model.previousAttributes(); - } - if (opt && opt.avoidStore) { - return; - } else { - var obj = { - object: model, - before: beforeCache, - after: model.toJSON() - }; - beforeCache = null; - return obj; - } - }, - undo: function undo(model, bf, af, opt) { - model.set(bf); - // Update also inputs inside Style Manager - that.trigger('change:selectedComponent'); - }, - redo: function redo(model, bf, af, opt) { - model.set(af); - // Update also inputs inside Style Manager - that.trigger('change:selectedComponent'); - } - }; - - UndoManager.removeUndoType("change"); - UndoManager.addUndoType("change:style", customUndoType); - UndoManager.addUndoType("change:attributes", customUndoType); - UndoManager.addUndoType("change:content", customUndoType); - UndoManager.addUndoType("change:src", customUndoType); - } - }, - - /** * Callback on component selection * @param {Object} Model @@ -24418,67 +24321,6 @@ module.exports = Backbone.Model.extend({ }, - /** - * Triggered when components are updated - * @param {Object} model - * @param {Mixed} val Value - * @param {Object} opt Options - * @private - * */ - updateComponents: function updateComponents(model, val, opt) { - var comps = model.get('components'), - classes = model.get('classes'), - avSt = opt ? opt.avoidStore : 0; - - // Observe component with Undo Manager - if (this.um) this.um.register(comps); - - // Call stopListening for not creating nested listeners - this.stopListening(comps, 'add', this.updateComponents); - this.stopListening(comps, 'remove', this.rmComponents); - this.listenTo(comps, 'add', this.updateComponents); - this.listenTo(comps, 'remove', this.rmComponents); - - this.stopListening(classes, 'add remove', this.handleUpdates); - this.listenTo(classes, 'add remove', this.handleUpdates); - - var evn = 'change:style change:content change:attributes change:src'; - this.stopListening(model, evn, this.handleUpdates); - this.listenTo(model, evn, this.handleUpdates); - - if (!avSt) this.handleUpdates(model, val, opt); - }, - - - /** - * Init stuff like storage for already existing elements - * @param {Object} model - * @private - */ - initChildrenComp: function initChildrenComp(model) { - var comps = model.get('components'); - this.updateComponents(model, null, { avoidStore: 1 }); - comps.each(function (md) { - this.initChildrenComp(md); - if (this.um) this.um.register(md); - }, this); - }, - - - /** - * Triggered when some component is removed updated - * @param {Object} model - * @param {Mixed} val Value - * @param {Object} opt Options - * @private - * */ - rmComponents: function rmComponents(model, val, opt) { - var avSt = opt ? opt.avoidStore : 0; - - if (!avSt) this.handleUpdates(model, val, opt); - }, - - /** * Returns model of the selected component * @return {Component|null} @@ -24623,7 +24465,7 @@ module.exports = Backbone.Model.extend({ * @private */ store: function store(clb) { - var _this3 = this; + var _this4 = this; var sm = this.get('StorageManager'); var store = {}; @@ -24639,8 +24481,8 @@ module.exports = Backbone.Model.extend({ sm.store(store, function () { clb && clb(); - _this3.set('changesCount', 0); - _this3.trigger('storage:store', store); + _this4.set('changesCount', 0); + _this4.trigger('storage:store', store); }); return store; @@ -24653,12 +24495,12 @@ module.exports = Backbone.Model.extend({ * @private */ load: function load() { - var _this4 = this; + var _this5 = this; var clb = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; this.getCacheLoad(1, function (res) { - _this4.get('storables').forEach(function (module) { + _this5.get('storables').forEach(function (module) { return module.load(res); }); clb && clb(res); @@ -24674,7 +24516,7 @@ module.exports = Backbone.Model.extend({ * @private */ getCacheLoad: function getCacheLoad(force, clb) { - var _this5 = this; + var _this6 = this; var f = force ? 1 : 0; if (this.cacheLoad && !f) return this.cacheLoad; @@ -24693,9 +24535,9 @@ module.exports = Backbone.Model.extend({ }); sm.load(load, function (res) { - _this5.cacheLoad = res; + _this6.cacheLoad = res; clb && clb(res); - _this5.trigger('storage:load', res); + _this6.trigger('storage:load', res); }); }, @@ -26776,12 +26618,24 @@ var _extends = Object.assign || function (target) { for (var i = 1; i < argument var _underscore = __webpack_require__(1); -var keymaster = __webpack_require__(17); +var keymaster = __webpack_require__(23); module.exports = function () { + var em = void 0; var config = void 0; - var configDef = {}; var keymaps = {}; + var configDef = { + defaults: { + 'core:undo': { + keys: '⌘+z, ctrl+z', + handler: 'core:undo' + }, + 'core:redo': { + keys: '⌘+shift+z, ctrl+shift+z', + handler: 'core:redo' + } + } + }; return { @@ -26806,10 +26660,19 @@ module.exports = function () { init: function init() { var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - config = _extends({}, opts, configDef); - this.em = config.em; + config = _extends({}, configDef, opts); + em = config.em; + this.em = em; return this; }, + onLoad: function onLoad() { + var defKeys = config.defaults; + + for (var id in defKeys) { + var value = defKeys[id]; + this.add(id, value.keys, value.handler); + } + }, /** @@ -26907,244 +26770,256 @@ module.exports = function () { "use strict"; -/** - * Before using methods you should get first the module from the editor instance, in this way: - * - * ```js - * var storageManager = editor.StorageManager; - * ``` - */ -module.exports = function () { - var c = {}, - defaults = __webpack_require__(70), - LocalStorage = __webpack_require__(71), - RemoteStorage = __webpack_require__(72); +var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; /** + * This module allows to manage the stack of changes applied in canvas + * + * You can access the module in this way + * ```js + * const um = editor.UndoManager; + * ``` + * + */ - var storages = {}; - var defaultStorages = {}; + +var _backboneUndo = __webpack_require__(70); + +var _backboneUndo2 = _interopRequireDefault(_backboneUndo); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +module.exports = function () { + var em = void 0; + var um = void 0; + var config = void 0; + var beforeCache = void 0; + var configDef = {}; return { - /** - * Name of the module - * @type {String} - * @private - */ - name: 'StorageManager', + name: 'UndoManager', /** - * Initialize module. Automatically called with a new instance of the editor + * Initialize module * @param {Object} config Configurations - * @param {string} [config.id='gjs-'] The prefix for the fields, useful to differentiate storing/loading - * with multiple editors on the same page. For example, in local storage, the item of HTML will be saved like 'gjs-html' - * @param {Boolean} [config.autosave=true] Indicates if autosave mode is enabled, works in conjunction with stepsBeforeSave - * @param {number} [config.stepsBeforeSave=1] If autosave enabled, indicates how many steps/changes are necessary - * before autosave is triggered - * @param {string} [config.type='local'] Default storage type. Available: 'local' | 'remote' | ''(do not store) * @private - * @example - * ... - * { - * autosave: false, - * type: 'remote', - * } - * ... */ - init: function init(config) { - c = config || {}; + init: function init() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - for (var name in defaults) { - if (!(name in c)) c[name] = defaults[name]; - } + config = _extends({}, opts, configDef); + em = config.em; + this.em = em; + um = new _backboneUndo2.default({ track: true, register: [] }); + um.changeUndoType('change', { condition: false }); + var customUndoType = { + on: function on(object, value) { + var opt = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + + !beforeCache && (beforeCache = object.previousAttributes()); + + if (opt.avoidStore) { + return; + } else { + var result = { + object: object, + before: beforeCache, + after: object.toJSON() + }; + beforeCache = null; + return result; + } + }, + undo: function undo(model, bf, af, opt) { + model.set(bf); + }, + redo: function redo(model, bf, af, opt) { + model.set(af); + } + }; + + var events = ['style', 'attributes', 'content', 'src']; + events.forEach(function (ev) { + return um.addUndoType('change:' + ev, customUndoType); + }); + um.on('undo redo', function () { + return em.trigger('change:selectedComponent change:canvasOffset'); + }); + ['undo', 'redo'].forEach(function (ev) { + return um.on(ev, function () { + return em.trigger(ev); + }); + }); - defaultStorages.remote = new RemoteStorage(c); - defaultStorages.local = new LocalStorage(c); - c.currentStorage = c.type; - this.loadDefaultProviders().setCurrent(c.type); return this; }, /** - * Checks if autosave is enabled - * @return {Boolean} - * */ - isAutosave: function isAutosave() { - return !!c.autosave; + * Get module configurations + * @return {Object} Configuration object + * @example + * const config = um.getConfig(); + * // { ... } + */ + getConfig: function getConfig() { + return config; }, /** - * Set autosave value - * @param {Boolean} v + * 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} - * */ - setAutosave: function setAutosave(v) { - c.autosave = !!v; + * @example + * um.add(someModelOrCollection); + */ + add: function add(entity) { + um.register(entity); return this; }, /** - * Returns number of steps required before trigger autosave - * @return {number} - * */ - getStepsBeforeSave: function getStepsBeforeSave() { - return c.stepsBeforeSave; + * Remove and stop tracking the entity (Model/Collection) + * @param {Model|Collection} entity Entity to remove + * @return {this} + * @example + * um.remove(someModelOrCollection); + */ + remove: function remove(entity) { + um.unregister(entity); + return this; }, /** - * Set steps required before trigger autosave - * @param {number} v + * Remove all entities * @return {this} - * */ - setStepsBeforeSave: function setStepsBeforeSave(v) { - c.stepsBeforeSave = v; + * @example + * um.removeAll(); + */ + removeAll: function removeAll() { + um.unregisterAll(); return this; }, /** - * Add new storage - * @param {string} id Storage ID - * @param {Object} storage Storage wrapper - * @param {Function} storage.load Load method - * @param {Function} storage.store Store method + * Start/resume tracking changes * @return {this} * @example - * storageManager.add('local2', { - * load: function(keys, clb) { - * var res = {}; - * for (var i = 0, len = keys.length; i < len; i++){ - * var v = localStorage.getItem(keys[i]); - * if(v) res[keys[i]] = v; - * } - * clb(res); // might be called inside some async method - * }, - * store: function(data, clb) { - * for(var key in data) - * localStorage.setItem(key, data[key]); - * clb(); // might be called inside some async method - * } - * }); - * */ - add: function add(id, storage) { - storages[id] = storage; + * um.start(); + */ + start: function start() { + um.startTracking(); return this; }, /** - * Returns storage by id - * @param {string} id Storage ID - * @return {Object|null} - * */ - get: function get(id) { - return storages[id] || null; + * Stop tracking changes + * @return {this} + * @example + * um.stop(); + */ + stop: function stop() { + um.stopTracking(); + return this; }, /** - * Returns all storages - * @return {Array} - * */ - getStorages: function getStorages() { - return storages; + * Undo last change + * @return {this} + * @example + * um.undo(); + */ + undo: function undo() { + if (!em.get('Canvas').isInputFocused()) um.undo(1); + return this; }, /** - * Returns current storage type - * @return {string} - * */ - getCurrent: function getCurrent() { - return c.currentStorage; + * Undo all changes + * @return {this} + * @example + * um.undoAll(); + */ + undoAll: function undoAll() { + um.undoAll(); + return this; }, /** - * Set current storage type - * @param {string} id Storage ID + * Redo last change * @return {this} - * */ - setCurrent: function setCurrent(id) { - c.currentStorage = id; + * @example + * um.redo(); + */ + redo: function redo() { + if (!em.get('Canvas').isInputFocused()) um.redo(1); return this; }, /** - * Store key-value resources in the current storage - * @param {Object} data Data in key-value format, eg. {item1: value1, item2: value2} - * @param {Function} clb Callback function - * @return {Object|null} + * Redo all changes + * @return {this} * @example - * storageManager.store({item1: value1, item2: value2}); - * */ - store: function store(data, clb) { - var st = this.get(this.getCurrent()); - var dataF = {}; - - for (var key in data) { - dataF[c.id + key] = data[key]; - }return st ? st.store(dataF, clb) : null; + * um.redoAll(); + */ + redoAll: function redoAll() { + um.redoAll(); + return this; }, /** - * Load resource from the current storage by keys - * @param {string|Array} keys Keys to load - * @param {Function} clb Callback function + * Checks if exists an available undo + * @return {Boolean} * @example - * storageManager.load(['item1', 'item2'], res => { - * // res -> {item1: value1, item2: value2} - * }); - * storageManager.load('item1', res => { - * // res -> {item1: value1} - * }); - * */ - load: function load(keys, clb) { - var st = this.get(this.getCurrent()); - var keysF = []; - var result = {}; - - if (typeof keys === 'string') keys = [keys]; + * um.hasUndo(); + */ + hasUndo: function hasUndo() { + return um.isAvailable('undo'); + }, - for (var i = 0, len = keys.length; i < len; i++) { - keysF.push(c.id + keys[i]); - }st && st.load(keysF, function (res) { - // Restore keys name - for (var itemKey in res) { - var reg = new RegExp('^' + c.id + ''); - var itemKeyR = itemKey.replace(reg, ''); - result[itemKeyR] = res[itemKey]; - } - clb && clb(result); - }); + /** + * Checks if exists an available redo + * @return {Boolean} + * @example + * um.hasRedo(); + */ + hasRedo: function hasRedo() { + return um.isAvailable('redo'); }, /** - * Load default storages - * @return {this} - * @private - * */ - loadDefaultProviders: function loadDefaultProviders() { - for (var id in defaultStorages) { - this.add(id, defaultStorages[id]); - }return this; + * Get stack of changes + * @return {Collection} + * @example + * const stack = um.getStack(); + * stack.each(item => ...); + */ + getStack: function getStack() { + return um.stack; }, /** - * Get configuration object - * @return {Object} - * @private - * */ - getConfig: function getConfig() { - return c; + * Clear the stack + * @return {this} + * @example + * um.clear(); + */ + clear: function clear() { + um.clear(); + return this; } }; }; @@ -27153,8817 +27028,8425 @@ module.exports = function () { /* 70 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; - - -module.exports = { - // Prefix identifier that will be used inside storing and loading - id: 'gjs-', - - // Enable/Disable autosaving - autosave: 1, - - // Indicates if load data inside editor after init - autoload: 1, - - // Indicates which storage to use. Available: local | remote - type: 'local', - - // If autosave enabled, indicates how many steps (general changes to structure) - // need to be done before save. Useful with remoteStorage to reduce remote calls - stepsBeforeSave: 1, +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 + */ - //Enable/Disable components model (JSON format) - storeComponents: 1, - //Enable/Disable styles model (JSON format) - storeStyles: 1, +(function (factory) { + if (true) { + // AMD support + !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(1), __webpack_require__(71)], __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 if (typeof exports !== 'undefined') { + // CommonJS support + module.exports = factory( + require("underscore"), + require("backbone") + ); + } else { + // Non-modular execution + factory(_, Backbone); + } +})(function (_, Backbone) { - //Enable/Disable saving HTML template - storeHtml: 1, + var core_slice = Array.prototype.slice; - //Enable/Disable saving CSS template - storeCss: 1, + /** + * 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); + } - // ONLY FOR LOCAL STORAGE - // If enabled, checks if browser supports Local Storage - checkLocal: 1, + /** + * 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); + } - // ONLY FOR REMOTE STORAGE - // Custom parameters to pass with the remote storage request, eg. csrf token - params: {}, + /** + * 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; + }); + } - // Custom headers for the remote storage request - headers: {}, + /** + * 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: - // Endpoint where to save all stuff - urlStore: '', + 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; + } + })(); - // Endpoint where to fetch data - urlLoad: '', + /** + * 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); + } + } - //Callback before request - beforeSend: function beforeSend(jqXHR, settings) {}, + /** + * 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); + } + } - //Callback after request - onComplete: function onComplete(jqXHR, status) {}, + /** + * 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); + } - // set contentType paramater of $.ajax - // true: application/json; charset=utf-8' - // false: 'x-www-form-urlencoded' - contentTypeJson: false + /** + * 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--; + } + } + } + } -/***/ }), -/* 71 */ -/***/ (function(module, exports, __webpack_require__) { -"use strict"; + /** + * 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) + }; + } + } + }; -var Backbone = __webpack_require__(0); + /** + * 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; -module.exports = Backbone.Model.extend({ + /** + * 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); + } + }) + } - defaults: { - checkLocal: true - }, + 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; + } - /** - * @private - */ - store: function store(data, clb) { - this.checkStorageEnvironment(); + /** + * 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(); - for (var key in data) { - localStorage.setItem(key, data[key]); - }if (typeof clb == 'function') { - clb(); - } - }, + // 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(); + } - /** - * @private - */ - load: function load(keys, clb) { - this.checkStorageEnvironment(); - var result = {}; + // 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); + }, - for (var i = 0, len = keys.length; i < len; i++) { - var value = localStorage.getItem(keys[i]); - if (value) result[keys[i]] = value; - } + /** + * Undoes all actions ever tracked by the undo manager + * @return {undefined} + */ + undoAll: function () { + managerUndoRedo("undo", this, this.stack, false, true); + }, - if (typeof clb == 'function') { - clb(result); - } + /** + * 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); + }, - return result; - }, + /** + * 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); + }, - /** - * @private - */ - remove: function remove(keys) { - this.checkStorageEnvironment(); + /** + * Removes all actions from the stack. + * @return {undefined} + */ + clear: function() { + this.stack.reset(); + this.stack.pointer = -1; + } + }); - for (var i = 0, len = keys.length; i < len; i++) { - localStorage.removeItem(keys[i]); - } - }, + _.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; - /** - * Check storage environment - * @private - * */ - checkStorageEnvironment: function checkStorageEnvironment() { - if (this.get('checkLocal') && !localStorage) console.warn("Your browser doesn't support localStorage"); - } }); + /***/ }), -/* 72 */ +/* 71 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; - +/* WEBPACK VAR INJECTION */(function(global) {var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// Backbone.js 1.2.1 -var _fetch = __webpack_require__(24); +// (c) 2010-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors +// Backbone may be freely distributed under the MIT license. +// For all details and documentation: +// http://backbonejs.org -var _fetch2 = _interopRequireDefault(_fetch); +(function(factory) { -var _underscore = __webpack_require__(1); + // 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 global == 'object' && global.global == global && global); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + // Set up Backbone appropriately for the environment. Start with AMD. + if (true) { + !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(1), __webpack_require__(8), 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__)); -module.exports = __webpack_require__(0).Model.extend({ + // Next for Node.js or CommonJS. jQuery may not be needed as a module. + } else if (typeof exports !== 'undefined') { + var _ = require('underscore'), $; + try { $ = require('jquery'); } catch(e) {} + factory(root, exports, _, $); - fetch: _fetch2.default, + // Finally, as a browser global. + } else { + root.Backbone = factory(root, {}, root._, (root.jQuery || root.Zepto || root.ender || root.$)); + } - defaults: { - urlStore: '', - urlLoad: '', - params: {}, - beforeSend: function beforeSend() {}, - onComplete: function onComplete() {}, +}(function(root, Backbone, _, $) { - contentTypeJson: false - }, + // Initial Setup + // ------------- - /** - * Triggered before the request is started - * @private - */ - onStart: function onStart() { - var em = this.get('em'); - var before = this.get('beforeSend'); - before && before(); - em && em.trigger('storage:start'); - }, + // 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 = [].slice; - /** - * Triggered on request error - * @param {Object} err Error - * @private - */ - onError: function onError(err) { - var em = this.get('em'); - console.error(err); - em && em.trigger('storage:error', err); - this.onEnd(err); - }, + // Current version of the library. Keep in sync with `package.json`. + Backbone.VERSION = '1.2.1'; + // For Backbone's purposes, jQuery, Zepto, Ender, or My Library (kidding) owns + // the `$` variable. + Backbone.$ = $; - /** - * Triggered after the request is ended - * @param {Object|string} res End result - * @private - */ - onEnd: function onEnd(res) { - var em = this.get('em'); - em && em.trigger('storage:end', res); - }, + // 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; - /** - * Triggered on request response - * @param {string} text Response text - * @private - */ - onResponse: function onResponse(text, clb) { - var em = this.get('em'); - var complete = this.get('onComplete'); - var typeJson = this.get('contentTypeJson'); - var res = typeJson && typeof text === 'string' ? JSON.parse(text) : text; - complete && complete(res); - clb && clb(res); - em && em.trigger('storage:response', res); - this.onEnd(text); - }, - store: function store(data, clb) { - var body = {}; + // 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; - for (var key in data) { - body[key] = data[key]; + // Proxy Underscore methods to a Backbone class' prototype using a + // particular attribute as the data argument + var addMethod = function(length, method, attribute) { + switch (length) { + case 1: return function() { + return _[method](this[attribute]); + }; + case 2: return function(value) { + return _[method](this[attribute], value); + }; + case 3: return function(iteratee, context) { + return _[method](this[attribute], iteratee, context); + }; + case 4: return function(iteratee, defaultVal, context) { + return _[method](this[attribute], iteratee, defaultVal, context); + }; + default: return function() { + var args = slice.call(arguments); + args.unshift(this[attribute]); + return _[method].apply(_, args); + }; } + }; + var addUnderscoreMethods = function(Class, methods, attribute) { + _.each(methods, function(length, method) { + if (_[method]) Class.prototype[method] = addMethod(length, method, attribute); + }); + }; - this.request(this.get('urlStore'), { body: body }, clb); - }, - load: function load(keys, clb) { - this.request(this.get('urlLoad'), { method: 'get' }, clb); - }, - - - /** - * Execute remote request - * @param {string} url Url - * @param {Object} [opts={}] Options - * @param {[type]} [clb=null] Callback - * @private - */ - request: function request(url) { - var _this = this; + // Backbone.Events + // --------------- - var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - var clb = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; + // A module that can be mixed in to *any object* in order to provide it with + // custom events. You may bind with `on` or remove with `off` callback + // functions to an event; `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 = {}; - var typeJson = this.get('contentTypeJson'); - var headers = this.get('headers') || {}; - var params = this.get('params'); - var reqHead = 'X-Requested-With'; - var typeHead = 'Content-Type'; - var bodyObj = opts.body || {}; - var fetchOptions = void 0; - var body = void 0; + // Regular expression used to split event strings. + var eventSplitter = /\s+/; - for (var param in params) { - bodyObj[param] = params[param]; + // 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}`), reducing them by manipulating `memo`. + // Passes a normalized single event name and callback, as well as any + // optional `opts`. + var eventsApi = function(iteratee, memo, 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++) { + memo = iteratee(memo, names[i], name[names[i]], opts); + } + } else if (name && eventSplitter.test(name)) { + // Handle space separated event names. + for (names = name.split(eventSplitter); i < names.length; i++) { + memo = iteratee(memo, names[i], callback, opts); + } + } else { + memo = iteratee(memo, name, callback, opts); } + return memo; + }; - if ((0, _underscore.isUndefined)(headers[reqHead])) { - headers[reqHead] = 'XMLHttpRequest'; - } + // Bind an event to a `callback` function. Passing `"all"` will bind + // the callback to all events fired. + Events.on = function(name, callback, context) { + return internalOn(this, name, callback, context); + }; - // With `fetch`, have to send FormData without any 'Content-Type' - // https://stackoverflow.com/questions/39280438/fetch-missing-boundary-in-multipart-form-data-post + // An internal use `on` function, used to guard the `listening` argument from + // the public API. + var internalOn = function(obj, name, callback, context, listening) { + obj._events = eventsApi(onApi, obj._events || {}, name, callback, { + context: context, + ctx: obj, + listening: listening + }); - if ((0, _underscore.isUndefined)(headers[typeHead]) && typeJson) { - headers[typeHead] = 'application/json; charset=utf-8'; + if (listening) { + var listeners = obj._listeners || (obj._listeners = {}); + listeners[listening.id] = listening; } - if (typeJson) { - body = JSON.stringify(bodyObj); - } else { - body = new FormData(); + return obj; + }; - for (var bodyKey in bodyObj) { - body.append(bodyKey, bodyObj[bodyKey]); - } - } - fetchOptions = { - method: opts.method || 'post', - credentials: 'include', - headers: headers - }; + // 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. + 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 = listeningTo[id]; - // Body should only be included on POST method - if (fetchOptions.method === 'post') { - fetchOptions.body = body; + // This object is not listening to any other events on `obj` yet. + // Setup the necessary references to track the listening callbacks. + if (!listening) { + var thisId = this._listenId || (this._listenId = _.uniqueId('l')); + listening = listeningTo[id] = {obj: obj, objId: id, id: thisId, listeningTo: listeningTo, count: 0}; } - this.onStart(); - this.fetch(url, fetchOptions).then(function (res) { - return (res.status / 200 | 0) == 1 ? res.text() : res.text().then(function (text) { - return Promise.reject(text); - }); - }).then(function (text) { - return _this.onResponse(text, clb); - }).catch(function (err) { - return _this.onError(err); - }); - } -}); - -/***/ }), -/* 73 */ -/***/ (function(module, exports, __webpack_require__) { - -/* WEBPACK VAR INJECTION */(function(setImmediate) {(function (root) { - - // Store setTimeout reference so promise-polyfill will be unaffected by - // other code modifying setTimeout (like sinon.useFakeTimers()) - var setTimeoutFunc = setTimeout; - - function noop() {} - - // Polyfill for Function.prototype.bind - function bind(fn, thisArg) { - return function () { - fn.apply(thisArg, arguments); - }; - } - - function Promise(fn) { - if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new'); - if (typeof fn !== 'function') throw new TypeError('not a function'); - this._state = 0; - this._handled = false; - this._value = undefined; - this._deferreds = []; + // Bind callbacks on obj, and keep track of them on listening. + internalOn(obj, name, callback, this, listening); + return this; + }; - doResolve(fn, 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++; - function handle(self, deferred) { - while (self._state === 3) { - self = self._value; - } - if (self._state === 0) { - self._deferreds.push(deferred); - return; + handlers.push({ callback: callback, context: context, ctx: context || ctx, listening: listening }); } - self._handled = true; - 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); - }); - } + return events; + }; - 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 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); - } - } + // 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; + }; - function reject(self, newValue) { - self._state = 2; - self._value = newValue; - finale(self); - } + // 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; - function finale(self) { - if (self._state === 2 && self._deferreds.length === 0) { - Promise._immediateFn(function() { - if (!self._handled) { - Promise._unhandledRejectionFn(self._value); - } - }); - } + var ids = obj ? [obj._listenId] : _.keys(listeningTo); - for (var i = 0, len = self._deferreds.length; i < len; i++) { - handle(self, self._deferreds[i]); - } - self._deferreds = null; - } + for (var i = 0; i < ids.length; i++) { + var listening = listeningTo[ids[i]]; - function Handler(onFulfilled, onRejected, promise) { - this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null; - this.onRejected = typeof onRejected === 'function' ? onRejected : null; - this.promise = promise; - } + // If listening doesn't exist, this object is not currently + // listening to obj. Break out early. + if (!listening) break; - /** - * 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); + listening.obj.off(name, callback, this); } - } + if (_.isEmpty(listeningTo)) this._listeningTo = void 0; - Promise.prototype['catch'] = function (onRejected) { - return this.then(null, onRejected); + return this; }; - Promise.prototype.then = function (onFulfilled, onRejected) { - var prom = new (this.constructor)(noop); + // The reducing API that removes a callback from the `events` object. + var offApi = function(events, name, callback, options) { + // No events to consider. + if (!events) return; - handle(this, new Handler(onFulfilled, onRejected, prom)); - return prom; - }; + var i = 0, listening; + var context = options.context, listeners = options.listeners; - Promise.all = function (arr) { - var args = Array.prototype.slice.call(arr); + // Delete all events listeners and "drop" events. + if (!name && !callback && !context) { + var ids = _.keys(listeners); + for (; i < ids.length; i++) { + listening = listeners[ids[i]]; + delete listeners[listening.id]; + delete listening.listeningTo[listening.objId]; + } + return; + } - return new Promise(function (resolve, reject) { - if (args.length === 0) return resolve([]); - var remaining = args.length; + var names = name ? [name] : _.keys(events); + for (; i < names.length; i++) { + name = names[i]; + var handlers = events[name]; - 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); + // Bail out if there are no events stored. + if (!handlers) break; + + // Replace events if there are any remaining. Otherwise, clean up. + 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 { + listening = handler.listening; + if (listening && --listening.count === 0) { + delete listeners[listening.id]; + delete listening.listeningTo[listening.objId]; } - } catch (ex) { - reject(ex); } } - for (var i = 0; i < args.length; i++) { - res(i, args[i]); + // Update tail event if the list has any events. Otherwise, clean up. + if (remaining.length) { + events[name] = remaining; + } else { + delete events[name]; } - }); - }; - - Promise.resolve = function (value) { - if (value && typeof value === 'object' && value.constructor === Promise) { - return value; } + if (_.size(events)) return events; + }; - return new Promise(function (resolve) { - resolve(value); - }); + // Bind an event to only be triggered a single time. After the first time + // the callback is invoked, it will be removed. When multiple events are + // passed in using the space-separated syntax, the event will fire once for every + // event you passed in, 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, _.bind(this.off, this)); + return this.on(events, void 0, context); }; - Promise.reject = function (value) { - return new Promise(function (resolve, reject) { - reject(value); - }); + // 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, _.bind(this.stopListening, this, obj)); + return this.listenTo(obj, events); }; - Promise.race = function (values) { - return new Promise(function (resolve, reject) { - for (var i = 0, len = values.length; i < len; i++) { - values[i].then(resolve, reject); - } - }); + // 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; }; - // Use polyfill for setImmediate for performance gains - Promise._immediateFn = (typeof setImmediate === 'function' && function (fn) { setImmediate(fn); }) || - function (fn) { - setTimeoutFunc(fn, 0); - }; + // 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; - Promise._unhandledRejectionFn = function _unhandledRejectionFn(err) { - if (typeof console !== 'undefined' && console) { - console.warn('Possible Unhandled Promise Rejection:', err); // eslint-disable-line no-console - } + 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; }; - /** - * Set the immediate function to execute callbacks - * @param fn {function} Function to execute - * @deprecated - */ - Promise._setImmediateFn = function _setImmediateFn(fn) { - Promise._immediateFn = fn; + // Handles triggering the appropriate event callbacks. + var triggerApi = function(objEvents, name, cb, 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; }; - /** - * Change the function to execute on unhandled rejection - * @param {function} fn Function to execute on unhandled rejection - * @deprecated - */ - Promise._setUnhandledRejectionFn = function _setUnhandledRejectionFn(fn) { - Promise._unhandledRejectionFn = fn; + // 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; + } }; - - if (typeof module !== 'undefined' && module.exports) { - module.exports = Promise; - } else if (!root.Promise) { - root.Promise = Promise; - } -})(this); + // Aliases for backwards compatibility. + Events.bind = Events.on; + Events.unbind = Events.off; -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(74).setImmediate)) + // Allow the `Backbone` object to serve as a global event bus, for folks who + // want global "pubsub" in a convenient place. + _.extend(Backbone, Events); -/***/ }), -/* 74 */ -/***/ (function(module, exports, __webpack_require__) { + // Backbone.Model + // -------------- -var apply = Function.prototype.apply; + // 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. -// DOM APIs, for completeness + // 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.cid = _.uniqueId(this.cidPrefix); + this.attributes = {}; + if (options.collection) this.collection = options.collection; + if (options.parse) attrs = this.parse(attrs, options) || {}; + attrs = _.defaults({}, attrs, _.result(this, 'defaults')); + this.set(attrs, options); + this.changed = {}; + this.initialize.apply(this, arguments); + }; -exports.setTimeout = function() { - return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout); -}; -exports.setInterval = function() { - return new Timeout(apply.call(setInterval, window, arguments), clearInterval); -}; -exports.clearTimeout = -exports.clearInterval = function(timeout) { - if (timeout) { - timeout.close(); - } -}; + // Attach all inheritable methods to the Model prototype. + _.extend(Model.prototype, Events, { -function Timeout(id, clearFn) { - this._id = id; - this._clearFn = clearFn; -} -Timeout.prototype.unref = Timeout.prototype.ref = function() {}; -Timeout.prototype.close = function() { - this._clearFn.call(window, this._id); -}; + // A hash of attributes whose current and previous value differ. + changed: null, -// Does not start the time, just sets up the members needed. -exports.enroll = function(item, msecs) { - clearTimeout(item._idleTimeoutId); - item._idleTimeout = msecs; -}; + // The value returned during the last failed validation. + validationError: null, -exports.unenroll = function(item) { - clearTimeout(item._idleTimeoutId); - item._idleTimeout = -1; -}; + // The default name for the JSON `id` attribute is `"id"`. MongoDB and + // CouchDB users may want to set this to `"_id"`. + idAttribute: 'id', -exports._unrefActive = exports.active = function(item) { - clearTimeout(item._idleTimeoutId); + // 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', - var msecs = item._idleTimeout; - if (msecs >= 0) { - item._idleTimeoutId = setTimeout(function onTimeout() { - if (item._onTimeout) - item._onTimeout(); - }, msecs); - } -}; + // Initialize is an empty function by default. Override it with your own + // initialization logic. + initialize: function(){}, -// setimmediate attaches itself to the global object -__webpack_require__(75); -exports.setImmediate = setImmediate; -exports.clearImmediate = clearImmediate; + // 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]; + }, -/***/ }), -/* 75 */ -/***/ (function(module, exports, __webpack_require__) { + // Get the HTML-escaped value of an attribute. + escape: function(attr) { + return _.escape(this.get(attr)); + }, -/* WEBPACK VAR INJECTION */(function(global, process) {(function (global, undefined) { - "use strict"; + // Returns `true` if the attribute contains a value that is not null + // or undefined. + has: function(attr) { + return this.get(attr) != null; + }, - if (global.setImmediate) { - return; - } + // Special-cased proxy to underscore's `_.matches` method. + matches: function(attrs) { + return !!_.iteratee(attrs, this)(this.attributes); + }, - var nextHandle = 1; // Spec says greater than zero - var tasksByHandle = {}; - var currentlyRunningATask = false; - var doc = global.document; - var registerImmediate; + // 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; - function setImmediate(callback) { - // Callback can either be a function or a string - if (typeof callback !== "function") { - callback = new Function("" + callback); - } - // Copy function arguments - var args = new Array(arguments.length - 1); - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i + 1]; + // Handle both `"key", value` and `{key: value}` -style arguments. + var attrs; + if (typeof key === 'object') { + attrs = key; + options = val; + } else { + (attrs = {})[key] = val; } - // Store and register the task - var task = { callback: callback, args: args }; - tasksByHandle[nextHandle] = task; - registerImmediate(nextHandle); - return nextHandle++; - } - function clearImmediate(handle) { - delete tasksByHandle[handle]; - } + options || (options = {}); - function run(task) { - var callback = task.callback; - var args = task.args; - switch (args.length) { - case 0: - callback(); - break; - case 1: - callback(args[0]); - break; - case 2: - callback(args[0], args[1]); - break; - case 3: - callback(args[0], args[1], args[2]); - break; - default: - callback.apply(undefined, args); - break; - } - } - - function runIfPresent(handle) { - // From the spec: "Wait until any invocations of this algorithm started before this one have completed." - // So if we're currently running a task, we'll need to delay this invocation. - if (currentlyRunningATask) { - // Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a - // "too much recursion" error. - setTimeout(runIfPresent, 0, handle); - } else { - var task = tasksByHandle[handle]; - if (task) { - currentlyRunningATask = true; - try { - run(task); - } finally { - clearImmediate(handle); - currentlyRunningATask = false; - } - } - } - } + // Run validation. + if (!this._validate(attrs, options)) return false; - function installNextTickImplementation() { - registerImmediate = function(handle) { - process.nextTick(function () { runIfPresent(handle); }); - }; - } + // Extract attributes and options. + var unset = options.unset; + var silent = options.silent; + var changes = []; + var changing = this._changing; + this._changing = true; - function canUsePostMessage() { - // The test against `importScripts` prevents this implementation from being installed inside a web worker, - // where `global.postMessage` means something completely different and can't be used for this purpose. - if (global.postMessage && !global.importScripts) { - var postMessageIsAsynchronous = true; - var oldOnMessage = global.onmessage; - global.onmessage = function() { - postMessageIsAsynchronous = false; - }; - global.postMessage("", "*"); - global.onmessage = oldOnMessage; - return postMessageIsAsynchronous; - } - } + if (!changing) { + this._previousAttributes = _.clone(this.attributes); + this.changed = {}; + } - function installPostMessageImplementation() { - // Installs an event handler on `global` for the `message` event: see - // * https://developer.mozilla.org/en/DOM/window.postMessage - // * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages + var current = this.attributes; + var changed = this.changed; + var prev = this._previousAttributes; - var messagePrefix = "setImmediate$" + Math.random() + "$"; - var onGlobalMessage = function(event) { - if (event.source === global && - typeof event.data === "string" && - event.data.indexOf(messagePrefix) === 0) { - runIfPresent(+event.data.slice(messagePrefix.length)); - } - }; + // Check for changes of `id`. + if (this.idAttribute in attrs) this.id = attrs[this.idAttribute]; - if (global.addEventListener) { - global.addEventListener("message", onGlobalMessage, false); + // 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 { - global.attachEvent("onmessage", onGlobalMessage); + delete changed[attr]; } + unset ? delete current[attr] : current[attr] = val; + } - registerImmediate = function(handle) { - global.postMessage(messagePrefix + handle, "*"); - }; - } + // 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); + } + } - function installMessageChannelImplementation() { - var channel = new MessageChannel(); - channel.port1.onmessage = function(event) { - var handle = event.data; - runIfPresent(handle); - }; + // 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; + }, - registerImmediate = function(handle) { - channel.port2.postMessage(handle); - }; - } + // 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})); + }, - function installReadyStateChangeImplementation() { - var html = doc.documentElement; - registerImmediate = function(handle) { - // Create a