123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290 |
- '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
|