'use strict'; /** * Licensed Materials - Property of IBM * IBM Cognos Products: BI Cloud (C) Copyright IBM Corp. 2014, 2020 * US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp. */ define(['../../lib/@waca/dashboard-common/dist/core/Model', './content/ContentModel', './ModelUtils', 'underscore', 'jquery'], function (Model, ContentModel, ModelUtils, _, $) { /** * * Public model operations: * * Function name: add * Description: Adds a model as a child to the layout model * Triggered event name: 'add:item' * Event listeners: Layout view object - Needed to created the proper html for the new view. * Called by: * - Board model: when a new widget is added. * - Layout model - updateModel operation * * * Function name: remove * Description: Removes a model from the layout model * Triggered event name: 'remove:item' * * Event listeners: Layout view object - Needed to the remove the html node associated with the deleted * Called by: * - Board model: when a new widget is deleted. * - Layout model - updateModel operation * * * Function name: updateStyle * Description: Updates the style property in the model. This operation will do a mixin with current value. * Triggered event name: 'change:style' * Event listeners: Layout view object - Needed to update the css style of the model node * Called by: * - Layout model - updateModel operation * * Function name: updateData * Description: Updates the data property in the model. * Triggered event name: 'change:data' * Event listeners: Layout view object - Needed to update the impress positioning of the view * Called by: * - Layout model - updateModel operation * * Function name: updateParent * Description: Updates the parent of the model. * Triggered event name: 'change:parent' * Event listeners: Layout view object - Needed to update the view node parent to match the new parent model * Called by: * - Layout model - updateModel operation * * * Function name: updateModel * Description: An operation that updates a model. This operation can add,update and remove models in one operation * Triggered event name: 'op:updateModel' * Event listeners: Board model - Needed to propagate the event to the auto save and undo/redo controller. * Called by: * - Layout interaction controller - when doing a move operation * * */ var LayoutModel = Model.extend({ localizedProps: ['title'], /** * Initialize this model from a layout spec, using the json under 'layout' from a board specification. * @param {object} layout spec * @param {object} The board models that owns this layout */ init: function init(spec, boardModel, logger) { LayoutModel.inherited('init', this, arguments); this.boardModel = boardModel; this.whitelistAttrs = ['id', 'from', 'css', 'items', 'style', 'type', 'title', 'templateName', 'relatedLayouts', 'clones', 'fillColor', 'disableScrollDrop', 'showGrid', 'snapGrid', 'snapObjects', 'tabTextColor', 'tabSelectedLineColor', 'tabBackgroundColor', 'pageSize', 'hideTab', 'tabPosition', 'tabIconPosition', 'tabIcon', 'tabIconColor', 'layoutPositioning', 'fitPage', 'content']; this.colorProperties = ['fillColor', 'tabTextColor', 'tabSelectedLineColor', 'tabBackgroundColor', 'tabIconColor']; // eslint-disable-next-line no-undef this.selected = new Set(); if (this.boardModel.layoutExtensions) { var modelExtensions = this.boardModel.layoutExtensions; Object.keys(modelExtensions || {}).forEach(function (property) { this.whitelistAttrs.push(property); if (modelExtensions[property] && typeof modelExtensions[property].init === 'function') { modelExtensions[property].init(this, spec, boardModel, logger); } }, this); } // Notify the board model when there is a layout change to the items so that the event is propagated to the auto save and the undo/redo controller this.on('op', this.boardModel.onLayoutChange, this.boardModel); this.on('change:title', this.boardModel.onLayoutChange, this.boardModel); // TODO: for change:css, we should move away from monitoring/setting the css property in the model and set specify properties this.on('change:css', this.boardModel.onLayoutChange, this.boardModel); this.on('change:fillColor', this.boardModel.onLayoutChange, this.boardModel); this.on('change:type', this.boardModel.onLayoutChange, this.boardModel); this.on('change:showGrid', this.boardModel.onLayoutChange, this.boardModel); this.on('change:snapGrid', this.boardModel.onLayoutChange, this.boardModel); this.on('change:snapObjects', this.boardModel.onLayoutChange, this.boardModel); this.on('change:tabTextColor', this.boardModel.onLayoutChange, this.boardModel); this.on('change:tabSelectedLineColor', this.boardModel.onLayoutChange, this.boardModel); this.on('change:tabBackgroundColor', this.boardModel.onLayoutChange, this.boardModel); this.on('change:pageSize', this.boardModel.onLayoutChange, this.boardModel); this.on('change:hideTab', this.boardModel.onLayoutChange, this.boardModel); this.on('change:tabPosition', this.boardModel.onLayoutChange, this.boardModel); this.on('change:tabIconPosition', this.boardModel.onLayoutChange, this.boardModel); this.on('change:tabIcon', this.boardModel.onLayoutChange, this.boardModel); this.on('change:tabIconColor', this.boardModel.onLayoutChange, this.boardModel); this.on('change:layoutPositioning', this.boardModel.onLayoutChange, this.boardModel); this.on('change:fitPage', this.boardModel.onLayoutChange, this.boardModel); this._initializeContentModel(); this.logger = logger; var idMap = {}; if (spec.items) { this.items = []; for (var i = 0, iLen = spec.items.length; i < iLen; i++) { var item = new LayoutModel(spec.items[i], this.boardModel, logger); if (!idMap[item.id]) { this.items.push(item); idMap[item.id] = true; } else { this.logger.error('Found duplicate layout id "' + item.id + '" on initialization of layout "' + this.id + '".'); } } } return this; }, getValueFromSelfOrParent: function getValueFromSelfOrParent(prop) { var value = this.get(prop); if (value === undefined) { var parent = this.getParent(); if (parent) { value = parent.getValueFromSelfOrParent(prop); } } return value; }, cloneLayout: function cloneLayout(idMap) { var clone = new LayoutModel(this.toJSON(), this.boardModel); if (!this.clones) { this.clones = 0; } this.clones++; clone.clones = 0; clone.replaceIds(idMap); clone.replaceRelatedLayouts(idMap); clone.incrementTitleCount(this.clones); return clone; }, /** * Find a model based on its id recursively. * @param {String} sId */ findModel: function findModel(sId) { var m = null; if (this.id === sId) { m = this; } if (!m && this.items) { for (var i = 0; !m && i < this.items.length; i++) { m = this.items[i].findModel(sId); } } return m; }, /** * Return an array of the widget IDs contained in the layouts with the specified IDs. * * @param aIDs Layout id array */ listWidgets: function listWidgets(aIDs) { var widgetIdList = []; var sId; for (var i = 0; i < aIDs.length; i++) { sId = aIDs[i]; var layout = this.findModel(sId); if (!layout) { continue; } if (layout.type === 'widget') { widgetIdList.push(layout.id); } else if (layout.items) { for (var j = 0; j < layout.items.length; j++) { widgetIdList.push.apply(widgetIdList, layout.items[j].listWidgets([layout.items[j].id])); } } } return widgetIdList; }, /** * Add a layout model as a child. * @param {object} add options * options.model - model json * options.insertBefore - insert location * @param sender - scope or identifier for the object doing the update * @param payloadData - Additional data that will be included in the event payload. * * @returns - Triggered event payload if available */ add: function add(options, sender, payloadData) { payloadData = this.checkPayloadData(payloadData); var parentId = options.parentId ? options.parentId : this.id; var parent = this.findModel(parentId); //TODO: This needs to be more generic and not specific to widget var isSubContent = parent && parent.type === 'widget'; var modelJSON = options.model; if (!modelJSON) { return null; } var payload = this._insertItem({ model: modelJSON, insertBeforeId: options.insertBefore }, sender, payloadData); var addedModel = payload.value.parameter.model; if (isSubContent) { return this._createPayload('add:item', { op: 'add', parameter: { model: addedModel, insertBefore: options.insertBefore } }, { op: 'remove', parameter: addedModel.id }, sender, payloadData); } return this._triggerEvent('add:item', { op: 'add', parameter: { model: addedModel, insertBefore: options.insertBefore } }, { op: 'remove', parameter: addedModel.id }, sender, payloadData); }, /** * Add multiple layout models * @param {object} modelArray An array of add options * options.parentId - parent id. If not available, the model will be added to the current model. * options.model - model json * options.insertBefore - insert location * @param sender - scope or identifier for the object doing the update * @param payloadData - Additional data that will be included in the event payload. * * @returns - Triggered event payload if available */ addArray: function addArray(modelArray, sender, payloadData) { payloadData = this.checkPayloadData(payloadData); var modelIdArray = []; var addedModels = []; var addPayload, options, parent, parentId; for (var i = 0; i < modelArray.length; i++) { options = modelArray[i]; parentId = options.parentId ? options.parentId : this.id; parent = this.findModel(parentId); addPayload = parent.add(modelArray[i], sender, payloadData); if (addPayload && addPayload.value && addPayload.prevValue) { addedModels.push(_.extend({ parentId: parentId }, addPayload.value.parameter)); modelIdArray.unshift(addPayload.prevValue.parameter); } } var payload = null; if (modelIdArray.length > 0) { payload = this._triggerEvent('add:items', { op: 'addArray', parameter: addedModels }, { op: 'removeArray', parameter: modelIdArray }, sender, payloadData); } return payload; }, /** * Remove a child from this Model. * @param {string} model id to remove. * @param sender - scope or identifier for the object doing the update * @param payloadData - Additional data that will be included in the event payload. * * @returns - Triggered event payload if available */ remove: function remove(id, sender, payloadData) { payloadData = this.checkPayloadData(payloadData); this._triggerEvent('pre:remove:item', { parameter: id }, null, sender, payloadData); //remove from current parent var payload = null; var oldSiblingId = this.findModel(id).getNextSiblingId(); var model = this._removeItem(id); if (model) { payload = this._triggerEvent('remove:item', { op: 'remove', parameter: id }, { op: 'add', parameter: { model: model.toJSON(), insertBefore: oldSiblingId } }, sender, payloadData); model.off(); } return payload; }, /** * Remove multiple children from the model. * @param {string} Array of model ids to remove. * @param sender - scope or identifier for the object doing the update * @param payloadData - Additional data that will be included in the event payload. * * @returns - Triggered event payload if available */ removeArray: function removeArray(idArray, sender, payloadData) { payloadData = this.checkPayloadData(payloadData); var models = []; var removePayload; var id, parent; for (var i = 0; i < idArray.length; i++) { id = idArray[i]; parent = this.findParentModel(id); if (parent) { removePayload = parent.remove(idArray[i], sender, payloadData); if (removePayload) { models.unshift(_.extend({ parentId: parent.id }, removePayload.prevValue.parameter)); } } } var payload = null; if (models.length > 0) { payload = this._triggerEvent('remove:items', { op: 'removeArray', parameter: idArray }, { op: 'addArray', parameter: models }, sender, payloadData); } return payload; }, /** * Update the style property of a model. This function will merge the provided styles with the existing ones * @param style - object containing the styles that we would like to update * @param sender - scope or identifier for the object doing the update * @param payloadData - Additional data that will be included in the event payload. * * @returns - Triggered event payload if available */ updateStyle: function updateStyle(style, sender, payloadData) { payloadData = this.checkPayloadData(payloadData); var payload = null; if (style) { if (!this.style) { this.style = {}; } var prev = this._getStyles(style); payload = this._triggerEvent('prechange:style', { style: style }, null, sender, payloadData); _.extend(this.style, style); payload = this._triggerEvent(LayoutModel.CHANGE_STYLE_EVENT_NAME, { op: 'updateStyle', parameter: style }, { op: 'updateStyle', parameter: prev }, sender, payloadData); } return payload; }, /** * Update the filters of a model given id * @param id * @param filters * @param sender - scope or identifier for the object doing the update * @param payloadData - Additional data that will be included in the event payload. * * @returns - Triggered event payload if available */ updateFilters: function updateFilters(id, filters) { var changes = { prevValue: {}, value: {} }; var widgetModel = this.boardModel.getWidgetModel(id); if (widgetModel && widgetModel.filters) { var modelFilters = widgetModel.filters; widgetModel.filters = filters; changes.prevValue.filters = modelFilters; changes.value.filters = filters; } return changes; }, /** * Update the parent of the model * * @param options * options.parentId - new parent id * options.insertBefore - Id of the next sibling. If not provided, the model will be appended at the end. * @param sender - scope or identifier for the object doing the update * @param payloadData - Additional data that will be included in the event payload. * * @returns - Triggered event payload if available */ updateParent: function updateParent(options, sender, payloadData) { payloadData = this.checkPayloadData(payloadData); var payload = null; var newParent = this.boardModel.layout.findModel(options.parentId); if (newParent) { //remove from current parent var oldParent = this.getParent(); var oldSiblingId = null; if (oldParent) { oldSiblingId = this.getNextSiblingId(); oldParent._removeItem(this.id); } newParent._insertItem({ model: this, insertBeforeId: options.insertBefore }, sender, payloadData); payload = this._triggerEvent('change:parent', { op: 'updateParent', parameter: options }, { op: 'updateParent', parameter: { parentId: oldParent ? oldParent.id : null, insertBefore: oldSiblingId } }, sender, payloadData); } return payload; }, /** * Apply changes to the model using the update spec. This method can do add, remove and update in one operation. * * The order of the execution is the following: * * - Add new models * - Update models * - Remove models * * * * @param {object} options that describe the operation * options.addArray - Array of options needed to add the model. * { * model: {}, // model to add * parentId: 'parentId' // If not available, the model will be added to the current model. * } * * options.removeArray - Array of model IDs to remove * * * options.updateArray - Options used by the move operation. * { * id: 'model id', * parentId:'parent id' // If not available, then the model will be moved to the first model that is being added in this operation * insertBefore: 'someId', // Id of the model where we need to insert * style :{ * top:'10px', * left:'10px' * } * } * @param sender - scope or identifier for the object doing the update * @param payloadData - Additional data that will be included in the event payload. * * @returns - Triggered event payload if available */ updateModel: function updateModel(options, sender, payloadData) { payloadData = this.checkPayloadData(payloadData); var payload; var addPayload = null; var payloadValue = {}; var payloadPreValue = {}; if (options.addArray) { addPayload = this.addArray(options.addArray, sender, payloadData); if (addPayload) { payloadValue.addArray = addPayload.value.parameter; payloadPreValue.removeArray = addPayload.prevValue.parameter; } } if (options.updateArray) { var addedModels = addPayload ? addPayload.value.parameter : null; var updatePayload = this._updateModelsProperties(options.updateArray, sender, addedModels, payloadData); if (updatePayload) { if (JSON.stringify(updatePayload.value) !== JSON.stringify(updatePayload.prevValue)) { payloadValue.updateArray = updatePayload.value; payloadPreValue.updateArray = updatePayload.prevValue; } } } if (options.removeArray) { var removePayload = this.removeArray(options.removeArray, sender, payloadData); if (removePayload) { payloadValue.removeArray = removePayload.value.parameter; payloadPreValue.addArray = removePayload.prevValue.parameter; } } // Maintain any payload data that the caller included in the options. if (options.payloadData) { payloadValue.info = options.payloadData; payloadPreValue.info = options.payloadData; } if (!_.isEmpty(payloadValue)) { payload = this._triggerEvent('op:updateModel', { op: 'updateModel', parameter: payloadValue }, { op: 'updateModel', parameter: payloadPreValue }, sender, payloadData); } return payload; }, /** * @deprecate should use CanvasAPI.moveContent() instead. */ moveModel: function moveModel(options, sender, payloadData) { payloadData = this.checkPayloadData(payloadData); var payload = null; var payloadValue = {}; var payloadPreValue = {}; if (options.removeArray) { var removePayload = this.removeArray(options.removeArray, sender, payloadData); if (removePayload) { payloadValue.removeArray = removePayload.value.parameter; payloadPreValue.addArray = removePayload.prevValue.parameter; } } if (options.addArray) { var addPayload = this.addArray(options.addArray, sender, payloadData); if (addPayload) { payloadValue.addArray = addPayload.value.parameter; payloadPreValue.removeArray = addPayload.prevValue.parameter; } } if (options.updateArray) { var updatePayload = this._updateModelsProperties(options.updateArray, sender, payloadData); if (updatePayload) { payloadValue.updateArray = updatePayload.value; payloadPreValue.updateArray = updatePayload.prevValue; } } // Maintain any payload data that the caller included in the options. if (options.payloadData) { payloadValue.info = options.payloadData; payloadPreValue.info = options.payloadData; } payload = this._triggerEvent('op:moveModel', { op: 'moveModel', parameter: payloadValue }, { op: 'moveModel', parameter: payloadPreValue }, sender, payloadData); return payload; }, checkPayloadData: function checkPayloadData(payloadData) { var data = payloadData; if (!data) { var undoRedoTransactionId = _.uniqueId('layoutModelTransaction'); data = { undoRedoTransactionId: undoRedoTransactionId }; } return data; }, /** * Helper function that updated the parent and the style of a model. Returns an object with value before and after the change. * @param model * @param options * @param sender * @param addedModels - a list of models that were added in the same operation * @param payloadData - Additional data that will be included in the event payload. */ _updateModelProperties: function _updateModelProperties(model, options, sender, addedModels, payloadData) { var changes = { prevValue: { id: model.id }, value: { id: model.id } }; if (options.parentId) { var parentId = options.parentId; // For now, only support adding to the first added model if (parentId === '$addArray[0]' && addedModels && addedModels.length > 0) { parentId = addedModels[0].model.id; } // Update the parent var updateParent = model.updateParent({ parentId: parentId, insertBefore: options.insertBefore }, sender, payloadData); if (updateParent !== null) { changes.prevValue = _.extend(changes.prevValue, updateParent.prevValue.parameter); changes.value = _.extend(changes.value, updateParent.value.parameter); } } // Update the style submodel var updateStyle = model.updateStyle(options.style, sender, payloadData); if (updateStyle) { changes.prevValue.style = updateStyle.prevValue.parameter; changes.value.style = updateStyle.value.parameter; } // Update the filters submodel if (options.filters) { var updateFilters = model.updateFilters(options.id, options.filters); if (updateFilters) { changes.prevValue.filters = updateFilters.prevValue.filters; changes.value.filters = updateFilters.value.filters; } } if (this.boardModel.layoutExtensions) { var modelExtensions = this.boardModel.layoutExtensions; Object.keys(modelExtensions || {}).forEach(function (property) { var update = model._callExtensionMethod({ property: property, value: options[property] }, sender, payloadData); if (update) { changes.prevValue[property] = update.prevValue.parameter.value; changes.value[property] = update.value.parameter.value; } }, this); } return changes; }, /** * Helper to call extension update. Handles triggering an event and undo redo automatically * @param options {object} : * { * property: name of the property * value: value of the property * } * @param sender sender of the call * @param payloadData - Additional data that will be included in the event payload. */ _callExtensionMethod: function _callExtensionMethod(options, sender, payloadData) { var modelExtension = this.boardModel.layoutExtensions[options.property]; if (modelExtension && typeof modelExtension.update === 'function') { var payload = modelExtension.update(this, options.value); if (payload) { return this._triggerEvent(payload.event, { op: '_callExtensionMethod', parameter: { property: options.property, value: payload.value } }, { op: '_callExtensionMethod', parameter: { property: options.property, value: payload.previousValue } }, sender, payloadData); } } return null; }, /** * Helper function that updates an list of models. */ _updateModelsProperties: function _updateModelsProperties(updateArray, sender, addedModels, payloadData) { var changes = { value: [], prevValue: [] }; var info; for (var i = 0; i < updateArray.length; i++) { info = updateArray[i]; var child = this.findModel(info.id); if (child) { var change = this._updateModelProperties(child, info, sender, addedModels, payloadData); changes.value.push(change.value); changes.prevValue.unshift(change.prevValue); } } return changes; }, isSelected: function isSelected(id) { return this.selected.has(id); }, select: function select(id) { var model = this.findModel(id); if (model) { this.selected.add(id); } }, deselect: function deselect(id) { this.selected.delete(id); // Recursively deselect all the way up to the root. var parent = this.getParent(); parent && parent.deselect(id); }, getSelectedChildLayouts: function getSelectedChildLayouts() { var _this = this; var items = []; var addModel = function addModel(id) { var model = _this.findModel(id); if (model) { items.push(model); } return model; }; // Find the selected layouts at this level. this.selected.forEach(addModel); if (this.type === 'group') { var parent = this.getParent(); // If this layout is selected and a 'group', then add the subitems as they are implicitly selected. if (parent && parent.isSelected(this.id)) { var addNestedItems = function addNestedItems(item) { addModel(item.id); item.item && item.items.forEach(function (item) { return addNestedItems(item); }); }; this.items.forEach(function (item) { return addNestedItems(item); }); return items; } } // Recursively iterate through children. if (this.items) { this.items.forEach(function (item) { var selected = item.getSelectedChildLayouts(); if (selected) { items = items.concat(selected); } }); } return items; }, getSelectedWidgets: function getSelectedWidgets() { return this.getSelectedChildLayouts().filter(function (item) { return item.type === 'widget'; }); }, getWidgetByIndex: function getWidgetByIndex(index) { if (index < 0) { return; } function _getWidgetByIndex(item, index, cursor) { if (item.type === 'widget' && index === cursor.index++) { return item; } var items = item.items; if (items) { var length = items.length; // Cannot use _.find here. Noticed some weird behaviour using it in a recursive // setting. It would return the parent of the matched item (sharing env or something?). for (var i = 0; i < length; i++) { var subItem = items[i]; var widget = _getWidgetByIndex(subItem, index, cursor); if (widget) { return widget; } } } } return _getWidgetByIndex(this, index, { index: 0 }); }, /** * Get the next sibling id * @returns */ getNextSiblingId: function getNextSiblingId() { return this._getSiblingId(1); }, /** * Get the previous sibling id * @returns */ getPreviousSiblingId: function getPreviousSiblingId() { return this._getSiblingId(-1); }, _getSiblingId: function _getSiblingId(step) { var parent = this.getParent(); var next = null; if (parent) { var idx = parent.items.indexOf(this) + step; if (idx >= 0 && idx < parent.items.length) { next = parent.items[idx].id; } } return next; }, getParent: function getParent() { return this.boardModel.layout.findParentModel(this.id); }, getTopLayoutModel: function getTopLayoutModel() { return this.boardModel.layout; }, /** * Get the style map using the names in the given map * * @param names - map with names * @returns {___anonymous8145_8146} */ _getStyles: function _getStyles(names) { var styles = {}; for (var name in names) { if (names.hasOwnProperty(name)) { styles[name] = this.style && this.style[name] ? this.style[name] : ''; } } return styles; }, /** * Util for incrementing a style value ( % or px ) by 5% or 25px * Moved from BoardModel to become common * * @param value - value to be incremented * @returns the incremented value */ incrementStyleValue: function incrementStyleValue(value) { if (value) { if (value[value.length - 1] === '%') { return parseFloat(value) + 5 + '%'; } else if (value[value.length - 1] === 'x') { return parseFloat(value) + 25 + 'px'; } else { return value; } } return value; }, /** * Util for decrementing a style value ( % or px ) by 5% or 25px * Moved from BoardModel to become common * * @param value - value to be incremented * @returns the incremented value */ decrementStyleValue: function decrementStyleValue(value) { if (value) { if (value[value.length - 1] === '%') { return parseFloat(value) - 5 + '%'; } else if (value[value.length - 1] === 'x') { return parseFloat(value) - 25 + 'px'; } else { return value; } } return value; }, /** * Find a parent model based on the child id recursively. * @param {String} sId */ findParentModel: function findParentModel(id) { var index = this._getItemIndex(id); if (index !== -1) { return this; } var parent = null; if (this.items) { for (var i = 0; !parent && i < this.items.length; i++) { parent = this.items[i].findParentModel(id); } } return parent; }, /** * A private method to check if the layout type is a container layout * * @returns {boolean} true if type is container; false otherwise */ _isContainerType: function _isContainerType() { if (_.contains(['container'], this.type)) { return true; } return false; }, /** * This method will return an object containing a list of drop zones found from the layout it is called from. * This can be every drop zone in a dashboard or story (all tabs or all scenes) or it can be a single tab/scene's * drop zones depending on how high up the model the search is done from. * * @returns undefined|{Object} Return early if not template layout. Otherwise return an object with an array of IDs * and the parent ID of the drop zones */ findDropZones: function findDropZones() { if (!this._isContainerType()) { return; } var dropZones = this.findDescendantsWithType(['templateDropZone', 'templateIndicator']); var parentId = this.findParentModel(dropZones[0].id).id; var dropZoneIds = []; for (var i = 0; i < dropZones.length; i++) { dropZoneIds.push(dropZones[i].id); } return { ids: dropZoneIds, parentId: parentId }; }, /** * Return the list of all the descendant layouts with the given type * Stops descending on found model type (does not search its children) * * @param type - type(s) of layout to search for (single value or array of values) */ findDescendantsWithType: function findDescendantsWithType(types) { var findTypes = Array.isArray(types) ? types : [types]; var descendants = []; if (this.items) { for (var _iterator = this.items, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { var _ref; if (_isArray) { if (_i >= _iterator.length) break; _ref = _iterator[_i++]; } else { _i = _iterator.next(); if (_i.done) break; _ref = _i.value; } var item = _ref; if (findTypes.indexOf(item.type) !== -1) { descendants.push(item); } else { descendants.push.apply(descendants, item.findDescendantsWithType(types)); } } } return descendants; }, /** * Return the parent layouts that are groups * the returned object are the actual layouts and not the IDs * * @param layout1 the first layout. * @param layout2 the second layout. * @return [ * [widget1, widget2], * [parent1, parent2], * [grandParent1, grandParent2], * ... and so on ... * ] */ getLinkedLayoutTree: function getLinkedLayoutTree(layout1, layout2) { var result = []; return this._getLinkedLayoutTreeWorker(layout1, layout2, result); }, /* recurse up the family tree until we find a parent that is not a "linkable" container type */ _getLinkedLayoutTreeWorker: function _getLinkedLayoutTreeWorker(layout1, layout2, result) { result.push([layout1, layout2]); var oflinkableType = function oflinkableType(layout) { return layout.type === 'group'; }; var parent1 = layout1.getParent(); var parent2 = layout2.getParent(); if (!oflinkableType(parent1) && !oflinkableType(parent2)) { // both parents are not groups so the family tree could be the same. // and if we made it this far then they are the same. return result; } if (!oflinkableType(parent1) || !oflinkableType(parent2)) { // only 1 parent is not a group so definitely different family trees return null; } return this._getLinkedLayoutTreeWorker(parent1, parent2, result); }, /** * Given any layout item, find its top level parent item (the item in the layout's root level item list that contains it). * @param id - the id of the model for a widget, templateDropZone etc. * @returns the parent object (ie tab) for this model id */ findTopLevelParentItem: function findTopLevelParentItem(id) { var itemFound = null; _.each(this.items, function (item) { if (item.id === id) { itemFound = this; } else if (this.findChildItem(item.items, id) !== null) { itemFound = item; } }.bind(this)); return itemFound; }, /** * Recursively search all layout items and their child items lists for an id which matches * the specified id * @param items - the items list whose subtree of items lists are to be searched * @param id - the id to search for. * @returns the item if found or null if this id does not exist in this items list or any child lists. */ findChildItem: function findChildItem(items, id) { if (items) { for (var i = 0; i < items.length; ++i) { var item = items[i]; if (item.id === id) { // found it! return item; } else if (item.items) { item = this.findChildItem(item.items, id); if (item) { // found it! return item; } // otherwise continue with the remaining siblings } } } return null; }, /** * Insert an item in the item array. If insertBeforeId is not provided, the item will be inserted at the end * @param options * options.model * options.insertBeforeId * * @param sender * @param payloadData */ _insertItem: function _insertItem(options, sender, payloadData) { var item = options.model; var insertBeforeId = options.insertBeforeId; if (!(item instanceof LayoutModel)) { // Clone the model so that the internal model values are not affected by the value in the options parameters item = new LayoutModel($.extend(true, {}, item), this.boardModel); } if (!this.items) { this.items = []; } var duplicateIndex = this._getItemIndex(item.id); if (duplicateIndex !== -1) { // this should never occur since it would cause a layout with a duplicate ID to be added. // this works around the issue in the hope that we can find the broken code eventually. this.logger.error('Found duplicate layout id "' + item.id + '" at index "' + duplicateIndex + '" in layout "' + this.id + '".'); // this is not added to the undo/redo stack since undo of an insert should be a delete. // we are just working around the error condition of inserting a duplicate layout. this.items.splice(duplicateIndex, 1); } // Find insert position var idx = this._getItemIndex(insertBeforeId); // Add to the items array if (idx !== -1) { this.items.splice(idx, 0, item); } else { this.items.push(item); } return this._triggerEvent('insert:item', { op: '_insertItem', parameter: { model: item.toJSON(), insertBeforeId: insertBeforeId } }, { op: '_removeItem', parameter: item.id }, sender, payloadData); }, /** * Find the index of the child in the item array * @param {Object} item with an id attribute */ _getItemIndex: function _getItemIndex(id) { var idx = -1; if (this.items) { var model = null; for (var i = 0; i < this.items.length; i++) { model = this.items[i]; if (model.id === id) { idx = i; break; } } } return idx; }, /** * Remove the child model with the given id * @param id * @returns */ _removeItem: function _removeItem(id) { var model = null; var idx = this._getItemIndex(id); if (idx >= 0) { model = this.items[idx]; this.items.splice(idx, 1); } return model; }, /* * Used while cloning a 'LayoutModel'; Replaces any 'related layout' ids with those found in map. */ replaceRelatedLayouts: function replaceRelatedLayouts(map) { if (this.relatedLayouts && this.relatedLayouts.length > 0) { var updated = ''; if (this.relatedLayouts[0] === '|') { var related = this.relatedLayouts.split('|'); updated += '|'; _.each(related, function (rel) { if (rel.length > 0) { updated += (map[rel] ? map[rel] : rel) + '|'; } }); } else { updated = map[this.relatedLayouts] ? map[this.relatedLayouts] : this.relatedLayouts; } this.relatedLayouts = updated; } _.each(this.items, function (item) { item.replaceRelatedLayouts(map); }); }, incrementTitleCount: function incrementTitleCount(count) { if (this.title && this.title.length > 0) { this.title = this.title + ' (' + count + ')'; } if (this.title && this.title.translationTable) { this.title.translationTable = _.extend({}, this.title.translationTable); Object.keys(this.title.translationTable).forEach(function (key) { this.title.translationTable[key] = this.title.translationTable[key] + '-' + count; }.bind(this)); } }, _createPayload: function _createPayload(eventName, value, prevValue, sender, payloadData) { var payload = { modelId: this.id, value: value, sender: sender ? sender : this }; if (payloadData) { payload.data = payloadData; } // the event supports undo/redo if (prevValue) { payload.prevValue = prevValue; // Use the applyFn of the top level when we the operation is not a change operation on the current model. // if we delete the model and then undo, we don't want to use the applyFn of a deleted model. var layout = eventName.indexOf('change:') === 0 ? this : this.boardModel.layout; var applyFn = layout.applyFn.bind(layout); payload.senderContext = { applyFn: function (undoRedoParam, undoRedoSender) { applyFn(undoRedoParam, undoRedoSender, payloadData); }.bind(this) }; } return payload; }, /** * Helper function that will trigger an event * @param eventName * @param value * @param prevValue * @param sender * @param payloadData - Additional data that will be included in the event payload. */ _triggerEvent: function _triggerEvent(eventName, value, prevValue, sender, payloadData) { var payload = this._createPayload(eventName, value, prevValue, sender, payloadData); this.trigger(eventName, payload); return payload; }, /** * function used for undo/redo. * @param value * @param sender * @param payloadData - Additional data that will be included in the event payload. */ applyFn: function applyFn(value, sender, payloadData) { var _this2 = this; if (value && value.op && typeof this[value.op] === 'function') { var args = [value.parameter]; args.push(sender); args.push(payloadData); this[value.op].apply(this, args); } else { var layoutContexts = this.boardModel && this.boardModel.layout && this.boardModel.layout.items || []; var matchingContext = layoutContexts.find(function (item) { return item.id === _this2.id; }); LayoutModel.inherited('applyFn', matchingContext || this, arguments); } }, /** * Determine the layout positioning for the given model. * Walk up the parent tree until found. * @param {boolean} includeParents - Search parents if not defined on this model * @return {string} Either 'absolute' or 'relative' */ getLayoutPositioning: function getLayoutPositioning(includeParents) { if (this.type === 'genericPage') { return this.layoutPositioning || 'relative'; } else if (includeParents) { var parent = this.getParent(); if (parent) { return parent.getLayoutPositioning(); } return undefined; } else { return undefined; } }, /** * Creates a ContentModel by using properties and features specs. * * If the features spec contains a "Models_internal" use that * If the features spec contains a "Models.internal" use that * If using one of them than instantiate a new widget based on that spec * * TODO: this functon is referenced in Explore, need to clean that up */ _initializeContentModel: function _initializeContentModel() { if (this.features) { var featureName = void 0; if (this.features['Models.internal']) { featureName = 'Models.internal'; } else if (this.features['Models_internal']) { featureName = 'Models_internal'; } if (featureName) { this.boardModel.createLegacyWidgetModel(this.features[featureName]); } } this.content = ModelUtils.initializeContentModel(this); }, /** * @return {ContentModel} @see ContentModel.js */ getContentModel: function getContentModel() { return this.content; }, getUsedCustomColors: function getUsedCustomColors(customColors) { var usedColors = LayoutModel.inherited('getUsedCustomColors', this, arguments); if (this.items && this.items.length) { this.items.forEach(function (item) { usedColors = usedColors.concat(item.getUsedCustomColors(customColors)); }); } return _.uniq(usedColors, false); } }); LayoutModel.CHANGE_STYLE_EVENT_NAME = 'change:style'; return LayoutModel; }); //# sourceMappingURL=LayoutModel.js.map