How to use row method in pom

Best Python code snippet using pom_python

rowComp.js

Source:rowComp.js Github

copy

Full Screen

1/**2 * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components3 * @version v18.0.14 * @link http://www.ag-grid.com/5 * @license MIT6 */7"use strict";8var __extends = (this && this.__extends) || (function () {9 var extendStatics = Object.setPrototypeOf ||10 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||11 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };12 return function (d, b) {13 extendStatics(d, b);14 function __() { this.constructor = d; }15 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());16 };17})();18var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {19 var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;20 if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);21 else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;22 return c > 3 && r && Object.defineProperty(target, key, r), r;23};24var __metadata = (this && this.__metadata) || function (k, v) {25 if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);26};27Object.defineProperty(exports, "__esModule", { value: true });28var utils_1 = require("../utils");29var cellComp_1 = require("./cellComp");30var rowNode_1 = require("../entities/rowNode");31var gridOptionsWrapper_1 = require("../gridOptionsWrapper");32var column_1 = require("../entities/column");33var events_1 = require("../events");34var context_1 = require("../context/context");35var component_1 = require("../widgets/component");36var componentAnnotations_1 = require("../widgets/componentAnnotations");37var LoadingCellRenderer = (function (_super) {38 __extends(LoadingCellRenderer, _super);39 function LoadingCellRenderer() {40 return _super.call(this, LoadingCellRenderer.TEMPLATE) || this;41 }42 LoadingCellRenderer.prototype.init = function (params) {43 var eLoadingIcon = utils_1._.createIconNoSpan('groupLoading', this.gridOptionsWrapper, null);44 this.eLoadingIcon.appendChild(eLoadingIcon);45 var localeTextFunc = this.gridOptionsWrapper.getLocaleTextFunc();46 this.eLoadingText.innerText = localeTextFunc('loadingOoo', 'Loading');47 };48 LoadingCellRenderer.prototype.refresh = function (params) {49 return false;50 };51 LoadingCellRenderer.TEMPLATE = "<div class=\"ag-stub-cell\">\n <span class=\"ag-loading-icon\" ref=\"eLoadingIcon\"></span>\n <span class=\"ag-loading-text\" ref=\"eLoadingText\"></span>\n </div>";52 __decorate([53 context_1.Autowired('gridOptionsWrapper'),54 __metadata("design:type", gridOptionsWrapper_1.GridOptionsWrapper)55 ], LoadingCellRenderer.prototype, "gridOptionsWrapper", void 0);56 __decorate([57 componentAnnotations_1.RefSelector('eLoadingIcon'),58 __metadata("design:type", HTMLElement)59 ], LoadingCellRenderer.prototype, "eLoadingIcon", void 0);60 __decorate([61 componentAnnotations_1.RefSelector('eLoadingText'),62 __metadata("design:type", HTMLElement)63 ], LoadingCellRenderer.prototype, "eLoadingText", void 0);64 return LoadingCellRenderer;65}(component_1.Component));66exports.LoadingCellRenderer = LoadingCellRenderer;67var RowComp = (function (_super) {68 __extends(RowComp, _super);69 function RowComp(parentScope, bodyContainerComp, pinnedLeftContainerComp, pinnedRightContainerComp, fullWidthContainerComp, rowNode, beans, animateIn, useAnimationFrameForCreate) {70 var _this = _super.call(this) || this;71 _this.eAllRowContainers = [];72 _this.active = true;73 _this.columnRefreshPending = false;74 _this.cellComps = {};75 // for animations, there are bits we want done in the next VM turn, to all DOM to update first.76 // instead of each row doing a setTimeout(func,0), we put the functions here and the rowRenderer77 // executes them all in one timeout78 _this.createSecondPassFuncs = [];79 // these get called before the row is destroyed - they set up the DOM for the remove animation (ie they80 // set the DOM up for the animation), then the delayedDestroyFunctions get called when the animation is81 // complete (ie removes from the dom).82 _this.removeFirstPassFuncs = [];83 // for animations, these functions get called 400ms after the row is cleared, called by the rowRenderer84 // so each row isn't setting up it's own timeout85 _this.removeSecondPassFuncs = [];86 _this.initialised = false;87 _this.parentScope = parentScope;88 _this.beans = beans;89 _this.bodyContainerComp = bodyContainerComp;90 _this.pinnedLeftContainerComp = pinnedLeftContainerComp;91 _this.pinnedRightContainerComp = pinnedRightContainerComp;92 _this.fullWidthContainerComp = fullWidthContainerComp;93 _this.rowNode = rowNode;94 _this.rowIsEven = _this.rowNode.rowIndex % 2 === 0;95 _this.paginationPage = _this.beans.paginationProxy.getCurrentPage();96 _this.useAnimationFrameForCreate = useAnimationFrameForCreate;97 _this.setAnimateFlags(animateIn);98 return _this;99 }100 RowComp.prototype.init = function () {101 var _this = this;102 this.rowFocused = this.beans.focusedCellController.isRowFocused(this.rowNode.rowIndex, this.rowNode.rowPinned);103 this.scope = this.createChildScopeOrNull(this.rowNode.data);104 this.setupRowContainers();105 this.addListeners();106 if (this.slideRowIn) {107 this.createSecondPassFuncs.push(function () {108 _this.onTopChanged();109 });110 }111 if (this.fadeRowIn) {112 this.createSecondPassFuncs.push(function () {113 _this.eAllRowContainers.forEach(function (eRow) { return utils_1._.removeCssClass(eRow, 'ag-opacity-zero'); });114 });115 }116 };117 RowComp.prototype.createTemplate = function (contents, extraCssClass) {118 if (extraCssClass === void 0) { extraCssClass = null; }119 var templateParts = [];120 var rowHeight = this.rowNode.rowHeight;121 var rowClasses = this.getInitialRowClasses(extraCssClass).join(' ');122 var rowIdSanitised = utils_1._.escape(this.rowNode.id);123 var userRowStyles = this.preProcessStylesFromGridOptions();124 var businessKey = this.getRowBusinessKey();125 var businessKeySanitised = utils_1._.escape(businessKey);126 var rowTopStyle = this.getInitialRowTopStyle();127 templateParts.push("<div");128 templateParts.push(" role=\"row\"");129 templateParts.push(" row-index=\"" + this.rowNode.getRowIndexString() + "\"");130 templateParts.push(rowIdSanitised ? " row-id=\"" + rowIdSanitised + "\"" : "");131 templateParts.push(businessKey ? " row-business-key=\"" + businessKeySanitised + "\"" : "");132 templateParts.push(" comp-id=\"" + this.getCompId() + "\"");133 templateParts.push(" class=\"" + rowClasses + "\"");134 templateParts.push(" style=\"height: " + rowHeight + "px; " + rowTopStyle + " " + userRowStyles + "\">");135 // add in the template for the cells136 templateParts.push(contents);137 templateParts.push("</div>");138 return templateParts.join('');139 };140 RowComp.prototype.getCellForCol = function (column) {141 var cellComp = this.cellComps[column.getColId()];142 if (cellComp) {143 return cellComp.getGui();144 }145 else {146 return null;147 }148 };149 RowComp.prototype.afterFlush = function () {150 if (!this.initialised) {151 this.initialised = true;152 this.executeProcessRowPostCreateFunc();153 }154 };155 RowComp.prototype.executeProcessRowPostCreateFunc = function () {156 var func = this.beans.gridOptionsWrapper.getProcessRowPostCreateFunc();157 if (func) {158 var params = {159 eRow: this.eBodyRow,160 ePinnedLeftRow: this.ePinnedLeftRow,161 ePinnedRightRow: this.ePinnedRightRow,162 node: this.rowNode,163 api: this.beans.gridOptionsWrapper.getApi(),164 rowIndex: this.rowNode.rowIndex,165 addRenderedRowListener: this.addEventListener.bind(this),166 columnApi: this.beans.gridOptionsWrapper.getColumnApi(),167 context: this.beans.gridOptionsWrapper.getContext()168 };169 func(params);170 }171 };172 RowComp.prototype.getInitialRowTopStyle = function () {173 // if sliding in, we take the old row top. otherwise we just set the current row top.174 var pixels = this.slideRowIn ? this.roundRowTopToBounds(this.rowNode.oldRowTop) : this.rowNode.rowTop;175 var afterPaginationPixels = this.applyPaginationOffset(pixels);176 var afterScalingPixels = this.beans.heightScaler.getRealPixelPosition(afterPaginationPixels);177 if (this.beans.gridOptionsWrapper.isSuppressRowTransform()) {178 return "top: " + afterScalingPixels + "px; ";179 }180 else {181 return "transform: translateY(" + afterScalingPixels + "px); ";182 }183 };184 RowComp.prototype.getRowBusinessKey = function () {185 if (typeof this.beans.gridOptionsWrapper.getBusinessKeyForNodeFunc() === 'function') {186 var businessKey = this.beans.gridOptionsWrapper.getBusinessKeyForNodeFunc()(this.rowNode);187 return businessKey;188 }189 };190 RowComp.prototype.lazyCreateCells = function (cols, eRow) {191 if (this.active) {192 var cellTemplatesAndComps = this.createCells(cols);193 eRow.innerHTML = cellTemplatesAndComps.template;194 this.callAfterRowAttachedOnCells(cellTemplatesAndComps.cellComps, eRow);195 }196 };197 RowComp.prototype.createRowContainer = function (rowContainerComp, cols, callback) {198 var _this = this;199 var cellTemplatesAndComps;200 if (this.useAnimationFrameForCreate) {201 cellTemplatesAndComps = { cellComps: [], template: '' };202 }203 else {204 cellTemplatesAndComps = this.createCells(cols);205 }206 var rowTemplate = this.createTemplate(cellTemplatesAndComps.template);207 rowContainerComp.appendRowTemplate(rowTemplate, function () {208 var eRow = rowContainerComp.getRowElement(_this.getCompId());209 _this.afterRowAttached(rowContainerComp, eRow);210 callback(eRow);211 if (_this.useAnimationFrameForCreate) {212 _this.beans.taskQueue.addP1Task(_this.lazyCreateCells.bind(_this, cols, eRow));213 }214 else {215 _this.callAfterRowAttachedOnCells(cellTemplatesAndComps.cellComps, eRow);216 }217 });218 };219 RowComp.prototype.createChildScopeOrNull = function (data) {220 if (this.beans.gridOptionsWrapper.isAngularCompileRows()) {221 var newChildScope_1 = this.parentScope.$new();222 newChildScope_1.data = data;223 newChildScope_1.rowNode = this.rowNode;224 newChildScope_1.context = this.beans.gridOptionsWrapper.getContext();225 this.addDestroyFunc(function () {226 newChildScope_1.$destroy();227 newChildScope_1.data = null;228 newChildScope_1.rowNode = null;229 newChildScope_1.context = null;230 });231 return newChildScope_1;232 }233 else {234 return null;235 }236 };237 RowComp.prototype.setupRowContainers = function () {238 var isFullWidthCellFunc = this.beans.gridOptionsWrapper.getIsFullWidthCellFunc();239 var isFullWidthCell = isFullWidthCellFunc ? isFullWidthCellFunc(this.rowNode) : false;240 var isDetailCell = this.beans.doingMasterDetail && this.rowNode.detail;241 var isGroupSpanningRow = this.rowNode.group && this.beans.gridOptionsWrapper.isGroupUseEntireRow();242 if (this.rowNode.stub) {243 this.createFullWidthRows(RowComp.LOADING_CELL_RENDERER, RowComp.LOADING_CELL_RENDERER_COMP_NAME);244 }245 else if (isDetailCell) {246 this.createFullWidthRows(RowComp.DETAIL_CELL_RENDERER, RowComp.DETAIL_CELL_RENDERER_COMP_NAME);247 }248 else if (isFullWidthCell) {249 this.createFullWidthRows(RowComp.FULL_WIDTH_CELL_RENDERER, null);250 }251 else if (isGroupSpanningRow) {252 this.createFullWidthRows(RowComp.GROUP_ROW_RENDERER, RowComp.GROUP_ROW_RENDERER_COMP_NAME);253 }254 else {255 this.setupNormalRowContainers();256 }257 };258 RowComp.prototype.setupNormalRowContainers = function () {259 var _this = this;260 var centerCols = this.beans.columnController.getAllDisplayedCenterVirtualColumnsForRow(this.rowNode);261 this.createRowContainer(this.bodyContainerComp, centerCols, function (eRow) { return _this.eBodyRow = eRow; });262 var leftCols = this.beans.columnController.getDisplayedLeftColumnsForRow(this.rowNode);263 var rightCols = this.beans.columnController.getDisplayedRightColumnsForRow(this.rowNode);264 this.createRowContainer(this.pinnedRightContainerComp, rightCols, function (eRow) { return _this.ePinnedRightRow = eRow; });265 this.createRowContainer(this.pinnedLeftContainerComp, leftCols, function (eRow) { return _this.ePinnedLeftRow = eRow; });266 };267 RowComp.prototype.createFullWidthRows = function (type, name) {268 var _this = this;269 this.fullWidthRow = true;270 this.fullWidthRowEmbedded = this.beans.gridOptionsWrapper.isEmbedFullWidthRows();271 if (this.fullWidthRowEmbedded) {272 this.createFullWidthRowContainer(this.bodyContainerComp, null, null, type, name, function (eRow) {273 _this.eFullWidthRowBody = eRow;274 }, function (cellRenderer) {275 _this.fullWidthRowComponentBody = cellRenderer;276 });277 this.createFullWidthRowContainer(this.pinnedLeftContainerComp, column_1.Column.PINNED_LEFT, 'ag-cell-last-left-pinned', type, name, function (eRow) {278 _this.eFullWidthRowLeft = eRow;279 }, function (cellRenderer) {280 _this.fullWidthRowComponentLeft = cellRenderer;281 });282 this.createFullWidthRowContainer(this.pinnedRightContainerComp, column_1.Column.PINNED_RIGHT, 'ag-cell-first-right-pinned', type, name, function (eRow) {283 _this.eFullWidthRowRight = eRow;284 }, function (cellRenderer) {285 _this.fullWidthRowComponentRight = cellRenderer;286 });287 }288 else {289 // otherwise we add to the fullWidth container as normal290 // let previousFullWidth = ensureDomOrder ? this.lastPlacedElements.eFullWidth : null;291 this.createFullWidthRowContainer(this.fullWidthContainerComp, null, null, type, name, function (eRow) {292 _this.eFullWidthRow = eRow;293 }, function (cellRenderer) {294 _this.fullWidthRowComponent = cellRenderer;295 });296 }297 };298 RowComp.prototype.setAnimateFlags = function (animateIn) {299 if (animateIn) {300 var oldRowTopExists = utils_1._.exists(this.rowNode.oldRowTop);301 // if the row had a previous position, we slide it in (animate row top)302 this.slideRowIn = oldRowTopExists;303 // if the row had no previous position, we fade it in (animate304 this.fadeRowIn = !oldRowTopExists;305 }306 else {307 this.slideRowIn = false;308 this.fadeRowIn = false;309 }310 };311 RowComp.prototype.isEditing = function () {312 return this.editingRow;313 };314 RowComp.prototype.stopRowEditing = function (cancel) {315 this.stopEditing(cancel);316 };317 RowComp.prototype.isFullWidth = function () {318 return this.fullWidthRow;319 };320 RowComp.prototype.addListeners = function () {321 this.addDestroyableEventListener(this.rowNode, rowNode_1.RowNode.EVENT_HEIGHT_CHANGED, this.onRowHeightChanged.bind(this));322 this.addDestroyableEventListener(this.rowNode, rowNode_1.RowNode.EVENT_ROW_SELECTED, this.onRowSelected.bind(this));323 this.addDestroyableEventListener(this.rowNode, rowNode_1.RowNode.EVENT_ROW_INDEX_CHANGED, this.onRowIndexChanged.bind(this));324 this.addDestroyableEventListener(this.rowNode, rowNode_1.RowNode.EVENT_TOP_CHANGED, this.onTopChanged.bind(this));325 this.addDestroyableEventListener(this.rowNode, rowNode_1.RowNode.EVENT_EXPANDED_CHANGED, this.onExpandedChanged.bind(this));326 this.addDestroyableEventListener(this.rowNode, rowNode_1.RowNode.EVENT_DATA_CHANGED, this.onRowNodeDataChanged.bind(this));327 this.addDestroyableEventListener(this.rowNode, rowNode_1.RowNode.EVENT_CELL_CHANGED, this.onRowNodeCellChanged.bind(this));328 this.addDestroyableEventListener(this.rowNode, rowNode_1.RowNode.EVENT_DRAGGING_CHANGED, this.onRowNodeDraggingChanged.bind(this));329 var eventService = this.beans.eventService;330 this.addDestroyableEventListener(eventService, events_1.Events.EVENT_HEIGHT_SCALE_CHANGED, this.onTopChanged.bind(this));331 this.addDestroyableEventListener(eventService, events_1.Events.EVENT_DISPLAYED_COLUMNS_CHANGED, this.onDisplayedColumnsChanged.bind(this));332 this.addDestroyableEventListener(eventService, events_1.Events.EVENT_VIRTUAL_COLUMNS_CHANGED, this.onVirtualColumnsChanged.bind(this));333 this.addDestroyableEventListener(eventService, events_1.Events.EVENT_COLUMN_RESIZED, this.onColumnResized.bind(this));334 this.addDestroyableEventListener(eventService, events_1.Events.EVENT_CELL_FOCUSED, this.onCellFocusChanged.bind(this));335 this.addDestroyableEventListener(eventService, events_1.Events.EVENT_PAGINATION_CHANGED, this.onPaginationChanged.bind(this));336 this.addDestroyableEventListener(eventService, events_1.Events.EVENT_GRID_COLUMNS_CHANGED, this.onGridColumnsChanged.bind(this));337 };338 // when grid columns change, then all cells should be cleaned out,339 // as the new columns could have same id as the previous columns and may conflict340 RowComp.prototype.onGridColumnsChanged = function () {341 var allRenderedCellIds = Object.keys(this.cellComps);342 this.removeRenderedCells(allRenderedCellIds);343 };344 RowComp.prototype.onRowNodeDataChanged = function (event) {345 // if this is an update, we want to refresh, as this will allow the user to put in a transition346 // into the cellRenderer refresh method. otherwise this might be completely new data, in which case347 // we will want to completely replace the cells348 this.forEachCellComp(function (cellComp) {349 return cellComp.refreshCell({350 suppressFlash: !event.update,351 newData: !event.update352 });353 });354 // check for selected also, as this could be after lazy loading of the row data, in which case355 // the id might of just gotten set inside the row and the row selected state may of changed356 // as a result. this is what happens when selected rows are loaded in virtual pagination.357 // - niall note - since moving to the stub component, this may no longer be true, as replacing358 // the stub component now replaces the entire row359 this.onRowSelected();360 // as data has changed, then the style and class needs to be recomputed361 this.postProcessCss();362 };363 RowComp.prototype.onRowNodeCellChanged = function (event) {364 // as data has changed, then the style and class needs to be recomputed365 this.postProcessCss();366 };367 RowComp.prototype.postProcessCss = function () {368 this.postProcessStylesFromGridOptions();369 this.postProcessClassesFromGridOptions();370 this.postProcessRowClassRules();371 this.postProcessRowDragging();372 };373 RowComp.prototype.onRowNodeDraggingChanged = function () {374 this.postProcessRowDragging();375 };376 RowComp.prototype.postProcessRowDragging = function () {377 var dragging = this.rowNode.dragging;378 this.eAllRowContainers.forEach(function (row) { return utils_1._.addOrRemoveCssClass(row, 'ag-row-dragging', dragging); });379 };380 RowComp.prototype.onExpandedChanged = function () {381 if (this.rowNode.group && !this.rowNode.footer) {382 var expanded_1 = this.rowNode.expanded;383 this.eAllRowContainers.forEach(function (row) { return utils_1._.addOrRemoveCssClass(row, 'ag-row-group-expanded', expanded_1); });384 this.eAllRowContainers.forEach(function (row) { return utils_1._.addOrRemoveCssClass(row, 'ag-row-group-contracted', !expanded_1); });385 }386 };387 RowComp.prototype.onDisplayedColumnsChanged = function () {388 if (!this.fullWidthRow) {389 this.refreshCells();390 }391 };392 RowComp.prototype.destroyFullWidthComponents = function () {393 if (this.fullWidthRowComponent) {394 if (this.fullWidthRowComponent.destroy) {395 this.fullWidthRowComponent.destroy();396 }397 this.fullWidthRowComponent = null;398 }399 if (this.fullWidthRowComponentBody) {400 if (this.fullWidthRowComponentBody.destroy) {401 this.fullWidthRowComponentBody.destroy();402 }403 this.fullWidthRowComponent = null;404 }405 if (this.fullWidthRowComponentLeft) {406 if (this.fullWidthRowComponentLeft.destroy) {407 this.fullWidthRowComponentLeft.destroy();408 }409 this.fullWidthRowComponentLeft = null;410 }411 if (this.fullWidthRowComponentRight) {412 if (this.fullWidthRowComponentRight.destroy) {413 this.fullWidthRowComponentRight.destroy();414 }415 this.fullWidthRowComponent = null;416 }417 };418 RowComp.prototype.getContainerForCell = function (pinnedType) {419 switch (pinnedType) {420 case column_1.Column.PINNED_LEFT: return this.ePinnedLeftRow;421 case column_1.Column.PINNED_RIGHT: return this.ePinnedRightRow;422 default: return this.eBodyRow;423 }424 };425 RowComp.prototype.onVirtualColumnsChanged = function () {426 if (!this.fullWidthRow) {427 this.refreshCells();428 }429 };430 RowComp.prototype.onColumnResized = function () {431 if (!this.fullWidthRow) {432 this.refreshCells();433 }434 };435 RowComp.prototype.refreshCells = function () {436 if (this.beans.gridOptionsWrapper.isSuppressAnimationFrame()) {437 this.refreshCellsInAnimationFrame();438 }439 else {440 if (this.columnRefreshPending) {441 return;442 }443 this.beans.taskQueue.addP1Task(this.refreshCellsInAnimationFrame.bind(this));444 }445 };446 RowComp.prototype.refreshCellsInAnimationFrame = function () {447 if (!this.active) {448 return;449 }450 this.columnRefreshPending = false;451 var centerCols = this.beans.columnController.getAllDisplayedCenterVirtualColumnsForRow(this.rowNode);452 var leftCols = this.beans.columnController.getDisplayedLeftColumnsForRow(this.rowNode);453 var rightCols = this.beans.columnController.getDisplayedRightColumnsForRow(this.rowNode);454 this.insertCellsIntoContainer(this.eBodyRow, centerCols);455 this.insertCellsIntoContainer(this.ePinnedLeftRow, leftCols);456 this.insertCellsIntoContainer(this.ePinnedRightRow, rightCols);457 var colIdsToRemove = Object.keys(this.cellComps);458 centerCols.forEach(function (col) { return utils_1._.removeFromArray(colIdsToRemove, col.getId()); });459 leftCols.forEach(function (col) { return utils_1._.removeFromArray(colIdsToRemove, col.getId()); });460 rightCols.forEach(function (col) { return utils_1._.removeFromArray(colIdsToRemove, col.getId()); });461 // we never remove editing cells, as this would cause the cells to loose their values while editing462 // as the grid is scrolling horizontally.463 colIdsToRemove = utils_1._.filter(colIdsToRemove, this.isCellEligibleToBeRemoved.bind(this));464 // remove old cells from gui, but we don't destroy them, we might use them again465 this.removeRenderedCells(colIdsToRemove);466 };467 RowComp.prototype.removeRenderedCells = function (colIds) {468 var _this = this;469 colIds.forEach(function (key) {470 var cellComp = _this.cellComps[key];471 // could be old reference, ie removed cell472 if (utils_1._.missing(cellComp)) {473 return;474 }475 cellComp.detach();476 cellComp.destroy();477 _this.cellComps[key] = null;478 });479 };480 RowComp.prototype.isCellEligibleToBeRemoved = function (indexStr) {481 var displayedColumns = this.beans.columnController.getAllDisplayedColumns();482 var REMOVE_CELL = true;483 var KEEP_CELL = false;484 var renderedCell = this.cellComps[indexStr];485 if (!renderedCell) {486 return REMOVE_CELL;487 }488 // always remove the cell if it's in the wrong pinned location489 if (this.isCellInWrongRow(renderedCell)) {490 return REMOVE_CELL;491 }492 // we want to try and keep editing and focused cells493 var editing = renderedCell.isEditing();494 var focused = this.beans.focusedCellController.isCellFocused(renderedCell.getGridCell());495 var mightWantToKeepCell = editing || focused;496 if (mightWantToKeepCell) {497 var column = renderedCell.getColumn();498 var cellStillDisplayed = displayedColumns.indexOf(column) >= 0;499 return cellStillDisplayed ? KEEP_CELL : REMOVE_CELL;500 }501 else {502 return REMOVE_CELL;503 }504 };505 RowComp.prototype.ensureCellInCorrectContainer = function (cellComp) {506 var element = cellComp.getGui();507 var column = cellComp.getColumn();508 var pinnedType = column.getPinned();509 var eContainer = this.getContainerForCell(pinnedType);510 // if in wrong container, remove it511 var eOldContainer = cellComp.getParentRow();512 var inWrongRow = eOldContainer !== eContainer;513 if (inWrongRow) {514 // take out from old row515 if (eOldContainer) {516 eOldContainer.removeChild(element);517 }518 eContainer.appendChild(element);519 cellComp.setParentRow(eContainer);520 }521 };522 RowComp.prototype.isCellInWrongRow = function (cellComp) {523 var column = cellComp.getColumn();524 var rowWeWant = this.getContainerForCell(column.getPinned());525 // if in wrong container, remove it526 var oldRow = cellComp.getParentRow();527 return oldRow !== rowWeWant;528 };529 RowComp.prototype.insertCellsIntoContainer = function (eRow, cols) {530 var _this = this;531 if (!eRow) {532 return;533 }534 var cellTemplates = [];535 var newCellComps = [];536 cols.forEach(function (col) {537 var colId = col.getId();538 var oldCell = _this.cellComps[colId];539 if (oldCell) {540 _this.ensureCellInCorrectContainer(oldCell);541 }542 else {543 _this.createNewCell(col, eRow, cellTemplates, newCellComps);544 }545 });546 if (cellTemplates.length > 0) {547 utils_1._.appendHtml(eRow, cellTemplates.join(''));548 this.callAfterRowAttachedOnCells(newCellComps, eRow);549 }550 };551 RowComp.prototype.addDomData = function (eRowContainer) {552 var gow = this.beans.gridOptionsWrapper;553 gow.setDomData(eRowContainer, RowComp.DOM_DATA_KEY_RENDERED_ROW, this);554 this.addDestroyFunc(function () {555 gow.setDomData(eRowContainer, RowComp.DOM_DATA_KEY_RENDERED_ROW, null);556 });557 };558 RowComp.prototype.createNewCell = function (col, eContainer, cellTemplates, newCellComps) {559 var newCellComp = new cellComp_1.CellComp(this.scope, this.beans, col, this.rowNode, this, false);560 var cellTemplate = newCellComp.getCreateTemplate();561 cellTemplates.push(cellTemplate);562 newCellComps.push(newCellComp);563 this.cellComps[col.getId()] = newCellComp;564 newCellComp.setParentRow(eContainer);565 };566 RowComp.prototype.onMouseEvent = function (eventName, mouseEvent) {567 switch (eventName) {568 case 'dblclick':569 this.onRowDblClick(mouseEvent);570 break;571 case 'click':572 this.onRowClick(mouseEvent);573 break;574 }575 };576 RowComp.prototype.createRowEvent = function (type, domEvent) {577 return {578 type: type,579 node: this.rowNode,580 data: this.rowNode.data,581 rowIndex: this.rowNode.rowIndex,582 rowPinned: this.rowNode.rowPinned,583 context: this.beans.gridOptionsWrapper.getContext(),584 api: this.beans.gridOptionsWrapper.getApi(),585 columnApi: this.beans.gridOptionsWrapper.getColumnApi(),586 event: domEvent587 };588 };589 RowComp.prototype.createRowEventWithSource = function (type, domEvent) {590 var event = this.createRowEvent(type, domEvent);591 // when first developing this, we included the rowComp in the event.592 // this seems very weird. so when introducing the event types, i left the 'source'593 // out of the type, and just include the source in the two places where this event594 // was fired (rowClicked and rowDoubleClicked). it doesn't make sense for any595 // users to be using this, as the rowComp isn't an object we expose, so would be596 // very surprising if a user was using it.597 event.source = this;598 return event;599 };600 RowComp.prototype.onRowDblClick = function (mouseEvent) {601 if (utils_1._.isStopPropagationForAgGrid(mouseEvent)) {602 return;603 }604 var agEvent = this.createRowEventWithSource(events_1.Events.EVENT_ROW_DOUBLE_CLICKED, mouseEvent);605 this.beans.eventService.dispatchEvent(agEvent);606 };607 RowComp.prototype.onRowClick = function (mouseEvent) {608 var stop = utils_1._.isStopPropagationForAgGrid(mouseEvent);609 if (stop) {610 return;611 }612 var agEvent = this.createRowEventWithSource(events_1.Events.EVENT_ROW_CLICKED, mouseEvent);613 this.beans.eventService.dispatchEvent(agEvent);614 // ctrlKey for windows, metaKey for Apple615 var multiSelectKeyPressed = mouseEvent.ctrlKey || mouseEvent.metaKey;616 var shiftKeyPressed = mouseEvent.shiftKey;617 // we do not allow selecting groups by clicking (as the click here expands the group)618 // so return if it's a group row619 if (this.rowNode.group) {620 return;621 }622 // we also don't allow selection of pinned rows623 if (this.rowNode.rowPinned) {624 return;625 }626 // if no selection method enabled, do nothing627 if (!this.beans.gridOptionsWrapper.isRowSelection()) {628 return;629 }630 // if click selection suppressed, do nothing631 if (this.beans.gridOptionsWrapper.isSuppressRowClickSelection()) {632 return;633 }634 var multiSelectOnClick = this.beans.gridOptionsWrapper.isRowMultiSelectWithClick();635 var rowDeselectionWithCtrl = this.beans.gridOptionsWrapper.isRowDeselection();636 if (this.rowNode.isSelected()) {637 if (multiSelectOnClick) {638 this.rowNode.setSelectedParams({ newValue: false });639 }640 else if (multiSelectKeyPressed) {641 if (rowDeselectionWithCtrl) {642 this.rowNode.setSelectedParams({ newValue: false });643 }644 }645 else {646 // selected with no multi key, must make sure anything else is unselected647 this.rowNode.setSelectedParams({ newValue: true, clearSelection: true });648 }649 }650 else {651 var clearSelection = multiSelectOnClick ? false : !multiSelectKeyPressed;652 this.rowNode.setSelectedParams({ newValue: true, clearSelection: clearSelection, rangeSelect: shiftKeyPressed });653 }654 };655 RowComp.prototype.createFullWidthRowContainer = function (rowContainerComp, pinned, extraCssClass, cellRendererType, cellRendererName, eRowCallback, cellRendererCallback) {656 var _this = this;657 var rowTemplate = this.createTemplate('', extraCssClass);658 rowContainerComp.appendRowTemplate(rowTemplate, function () {659 var eRow = rowContainerComp.getRowElement(_this.getCompId());660 var params = _this.createFullWidthParams(eRow, pinned);661 var callback = function (cellRenderer) {662 if (_this.isAlive()) {663 var gui = cellRenderer.getGui();664 eRow.appendChild(gui);665 cellRendererCallback(cellRenderer);666 }667 else {668 if (cellRenderer.destroy) {669 cellRenderer.destroy();670 }671 }672 };673 _this.beans.componentResolver.createAgGridComponent(null, params, cellRendererType, params, cellRendererName).then(callback);674 _this.afterRowAttached(rowContainerComp, eRow);675 eRowCallback(eRow);676 _this.angular1Compile(eRow);677 });678 };679 RowComp.prototype.angular1Compile = function (element) {680 if (this.scope) {681 this.beans.$compile(element)(this.scope);682 }683 };684 RowComp.prototype.createFullWidthParams = function (eRow, pinned) {685 var params = {686 fullWidth: true,687 data: this.rowNode.data,688 node: this.rowNode,689 value: this.rowNode.key,690 $scope: this.scope,691 rowIndex: this.rowNode.rowIndex,692 api: this.beans.gridOptionsWrapper.getApi(),693 columnApi: this.beans.gridOptionsWrapper.getColumnApi(),694 context: this.beans.gridOptionsWrapper.getContext(),695 // these need to be taken out, as part of 'afterAttached' now696 eGridCell: eRow,697 eParentOfValue: eRow,698 pinned: pinned,699 addRenderedRowListener: this.addEventListener.bind(this)700 };701 return params;702 };703 RowComp.prototype.getInitialRowClasses = function (extraCssClass) {704 var classes = [];705 if (utils_1._.exists(extraCssClass)) {706 classes.push(extraCssClass);707 }708 classes.push('ag-row');709 classes.push(this.rowFocused ? 'ag-row-focus' : 'ag-row-no-focus');710 if (this.fadeRowIn) {711 classes.push('ag-opacity-zero');712 }713 if (this.rowIsEven) {714 classes.push('ag-row-even');715 }716 else {717 classes.push('ag-row-odd');718 }719 if (this.rowNode.isSelected()) {720 classes.push('ag-row-selected');721 }722 if (this.rowNode.group) {723 classes.push('ag-row-group');724 // if a group, put the level of the group in725 classes.push('ag-row-level-' + this.rowNode.level);726 if (this.rowNode.footer) {727 classes.push('ag-row-footer');728 }729 }730 else {731 // if a leaf, and a parent exists, put a level of the parent, else put level of 0 for top level item732 if (this.rowNode.parent) {733 classes.push('ag-row-level-' + (this.rowNode.parent.level + 1));734 }735 else {736 classes.push('ag-row-level-0');737 }738 }739 if (this.rowNode.stub) {740 classes.push('ag-row-stub');741 }742 if (this.fullWidthRow) {743 classes.push('ag-full-width-row');744 }745 if (this.rowNode.group && !this.rowNode.footer) {746 classes.push(this.rowNode.expanded ? 'ag-row-group-expanded' : 'ag-row-group-contracted');747 }748 if (this.rowNode.dragging) {749 classes.push('ag-row-dragging');750 }751 utils_1._.pushAll(classes, this.processClassesFromGridOptions());752 utils_1._.pushAll(classes, this.preProcessRowClassRules());753 return classes;754 };755 RowComp.prototype.preProcessRowClassRules = function () {756 var res = [];757 this.processRowClassRules(function (className) {758 res.push(className);759 }, function (className) {760 // not catered for, if creating, no need761 // to remove class as it was never there762 });763 return res;764 };765 RowComp.prototype.processRowClassRules = function (onApplicableClass, onNotApplicableClass) {766 this.beans.stylingService.processClassRules(this.beans.gridOptionsWrapper.rowClassRules(), {767 value: undefined,768 colDef: undefined,769 data: this.rowNode.data,770 node: this.rowNode,771 rowIndex: this.rowNode.rowIndex,772 api: this.beans.gridOptionsWrapper.getApi(),773 $scope: this.scope,774 context: this.beans.gridOptionsWrapper.getContext()775 }, onApplicableClass, onNotApplicableClass);776 };777 RowComp.prototype.stopEditing = function (cancel) {778 if (cancel === void 0) { cancel = false; }779 this.forEachCellComp(function (renderedCell) {780 renderedCell.stopEditing(cancel);781 });782 if (this.editingRow) {783 if (!cancel) {784 var event_1 = this.createRowEvent(events_1.Events.EVENT_ROW_VALUE_CHANGED);785 this.beans.eventService.dispatchEvent(event_1);786 }787 this.setEditingRow(false);788 }789 };790 RowComp.prototype.setEditingRow = function (value) {791 this.editingRow = value;792 this.eAllRowContainers.forEach(function (row) { return utils_1._.addOrRemoveCssClass(row, 'ag-row-editing', value); });793 var event = value ?794 this.createRowEvent(events_1.Events.EVENT_ROW_EDITING_STARTED)795 : this.createRowEvent(events_1.Events.EVENT_ROW_EDITING_STOPPED);796 this.beans.eventService.dispatchEvent(event);797 };798 RowComp.prototype.startRowEditing = function (keyPress, charPress, sourceRenderedCell) {799 if (keyPress === void 0) { keyPress = null; }800 if (charPress === void 0) { charPress = null; }801 if (sourceRenderedCell === void 0) { sourceRenderedCell = null; }802 // don't do it if already editing803 if (this.editingRow) {804 return;805 }806 this.forEachCellComp(function (renderedCell) {807 var cellStartedEdit = renderedCell === sourceRenderedCell;808 if (cellStartedEdit) {809 renderedCell.startEditingIfEnabled(keyPress, charPress, cellStartedEdit);810 }811 else {812 renderedCell.startEditingIfEnabled(null, null, cellStartedEdit);813 }814 });815 this.setEditingRow(true);816 };817 RowComp.prototype.forEachCellComp = function (callback) {818 utils_1._.iterateObject(this.cellComps, function (key, cellComp) {819 if (cellComp) {820 callback(cellComp);821 }822 });823 };824 RowComp.prototype.postProcessClassesFromGridOptions = function () {825 var _this = this;826 var cssClasses = this.processClassesFromGridOptions();827 if (cssClasses) {828 cssClasses.forEach(function (classStr) {829 _this.eAllRowContainers.forEach(function (row) { return utils_1._.addCssClass(row, classStr); });830 });831 }832 };833 RowComp.prototype.postProcessRowClassRules = function () {834 var _this = this;835 this.processRowClassRules(function (className) {836 _this.eAllRowContainers.forEach(function (row) { return utils_1._.addCssClass(row, className); });837 }, function (className) {838 _this.eAllRowContainers.forEach(function (row) { return utils_1._.removeCssClass(row, className); });839 });840 };841 RowComp.prototype.processClassesFromGridOptions = function () {842 var res = [];843 var process = function (rowClass) {844 if (typeof rowClass === 'string') {845 res.push(rowClass);846 }847 else if (Array.isArray(rowClass)) {848 rowClass.forEach(function (e) { return res.push(e); });849 }850 };851 // part 1 - rowClass852 var rowClass = this.beans.gridOptionsWrapper.getRowClass();853 if (rowClass) {854 if (typeof rowClass === 'function') {855 console.warn('ag-Grid: rowClass should not be a function, please use getRowClass instead');856 return;857 }858 process(rowClass);859 }860 // part 2 - rowClassFunc861 var rowClassFunc = this.beans.gridOptionsWrapper.getRowClassFunc();862 if (rowClassFunc) {863 var params = {864 node: this.rowNode,865 data: this.rowNode.data,866 rowIndex: this.rowNode.rowIndex,867 context: this.beans.gridOptionsWrapper.getContext(),868 api: this.beans.gridOptionsWrapper.getApi()869 };870 var rowClassFuncResult = rowClassFunc(params);871 process(rowClassFuncResult);872 }873 return res;874 };875 RowComp.prototype.preProcessStylesFromGridOptions = function () {876 var rowStyles = this.processStylesFromGridOptions();877 return utils_1._.cssStyleObjectToMarkup(rowStyles);878 };879 RowComp.prototype.postProcessStylesFromGridOptions = function () {880 var rowStyles = this.processStylesFromGridOptions();881 this.eAllRowContainers.forEach(function (row) { return utils_1._.addStylesToElement(row, rowStyles); });882 };883 RowComp.prototype.processStylesFromGridOptions = function () {884 // part 1 - rowStyle885 var rowStyle = this.beans.gridOptionsWrapper.getRowStyle();886 if (rowStyle && typeof rowStyle === 'function') {887 console.log('ag-Grid: rowStyle should be an object of key/value styles, not be a function, use getRowStyle() instead');888 return;889 }890 // part 1 - rowStyleFunc891 var rowStyleFunc = this.beans.gridOptionsWrapper.getRowStyleFunc();892 var rowStyleFuncResult;893 if (rowStyleFunc) {894 var params = {895 data: this.rowNode.data,896 node: this.rowNode,897 api: this.beans.gridOptionsWrapper.getApi(),898 context: this.beans.gridOptionsWrapper.getContext(),899 $scope: this.scope900 };901 rowStyleFuncResult = rowStyleFunc(params);902 }903 return utils_1._.assign({}, rowStyle, rowStyleFuncResult);904 };905 RowComp.prototype.createCells = function (cols) {906 var _this = this;907 var templateParts = [];908 var newCellComps = [];909 cols.forEach(function (col) {910 var newCellComp = new cellComp_1.CellComp(_this.scope, _this.beans, col, _this.rowNode, _this, false);911 var cellTemplate = newCellComp.getCreateTemplate();912 templateParts.push(cellTemplate);913 newCellComps.push(newCellComp);914 _this.cellComps[col.getId()] = newCellComp;915 });916 var templateAndComps = {917 template: templateParts.join(''),918 cellComps: newCellComps919 };920 return templateAndComps;921 };922 RowComp.prototype.onRowSelected = function () {923 var selected = this.rowNode.isSelected();924 this.eAllRowContainers.forEach(function (row) { return utils_1._.addOrRemoveCssClass(row, 'ag-row-selected', selected); });925 };926 // called:927 // + after row created for first time928 // + after horizontal scroll, so new cells due to column virtualisation929 RowComp.prototype.callAfterRowAttachedOnCells = function (newCellComps, eRow) {930 var _this = this;931 newCellComps.forEach(function (cellComp) {932 cellComp.setParentRow(eRow);933 cellComp.afterAttached();934 // if we are editing the row, then the cell needs to turn935 // into edit mode936 if (_this.editingRow) {937 cellComp.startEditingIfEnabled();938 }939 });940 };941 RowComp.prototype.afterRowAttached = function (rowContainerComp, eRow) {942 var _this = this;943 this.addDomData(eRow);944 this.removeSecondPassFuncs.push(function () {945 // console.log(eRow);946 rowContainerComp.removeRowElement(eRow);947 });948 this.removeFirstPassFuncs.push(function () {949 if (utils_1._.exists(_this.rowNode.rowTop)) {950 // the row top is updated anyway, however we set it here again951 // to something more reasonable for the animation - ie if the952 // row top is 10000px away, the row will flash out, so this953 // gives it a rounded value, so row animates out more slowly954 var rowTop = _this.roundRowTopToBounds(_this.rowNode.rowTop);955 _this.setRowTop(rowTop);956 }957 else {958 utils_1._.addCssClass(eRow, 'ag-opacity-zero');959 }960 });961 this.eAllRowContainers.push(eRow);962 // adding hover functionality adds listener to this row, so we963 // do it lazily in an animation frame964 if (this.useAnimationFrameForCreate) {965 this.beans.taskQueue.addP1Task(this.addHoverFunctionality.bind(this, eRow));966 }967 else {968 this.addHoverFunctionality(eRow);969 }970 };971 RowComp.prototype.addHoverFunctionality = function (eRow) {972 var _this = this;973 // because we use animation frames to do this, it's possible the row no longer exists974 // by the time we get to add it975 if (!this.active) {976 return;977 }978 // because mouseenter and mouseleave do not propagate, we cannot listen on the gridPanel979 // like we do for all the other mouse events.980 // because of the pinning, we cannot simply add / remove the class based on the eRow. we981 // have to check all eRow's (body & pinned). so the trick is if any of the rows gets a982 // mouse hover, it sets such in the rowNode, and then all three reflect the change as983 // all are listening for event on the row node.984 // step 1 - add listener, to set flag on row node985 this.addDestroyableEventListener(eRow, 'mouseenter', function () { return _this.rowNode.onMouseEnter(); });986 this.addDestroyableEventListener(eRow, 'mouseleave', function () { return _this.rowNode.onMouseLeave(); });987 // step 2 - listen for changes on row node (which any eRow can trigger)988 this.addDestroyableEventListener(this.rowNode, rowNode_1.RowNode.EVENT_MOUSE_ENTER, function () {989 // if hover turned off, we don't add the class. we do this here so that if the application990 // toggles this property mid way, we remove the hover form the last row, but we stop991 // adding hovers from that point onwards.992 if (!_this.beans.gridOptionsWrapper.isSuppressRowHoverHighlight()) {993 utils_1._.addCssClass(eRow, 'ag-row-hover');994 }995 });996 this.addDestroyableEventListener(this.rowNode, rowNode_1.RowNode.EVENT_MOUSE_LEAVE, function () {997 utils_1._.removeCssClass(eRow, 'ag-row-hover');998 });999 };1000 // for animation, we don't want to animate entry or exit to a very far away pixel,1001 // otherwise the row would move so fast, it would appear to disappear. so this method1002 // moves the row closer to the viewport if it is far away, so the row slide in / out1003 // at a speed the user can see.1004 RowComp.prototype.roundRowTopToBounds = function (rowTop) {1005 var range = this.beans.gridPanel.getVScrollPosition();1006 var minPixel = this.applyPaginationOffset(range.top, true) - 100;1007 var maxPixel = this.applyPaginationOffset(range.bottom, true) + 100;1008 if (rowTop < minPixel) {1009 return minPixel;1010 }1011 else if (rowTop > maxPixel) {1012 return maxPixel;1013 }1014 else {1015 return rowTop;1016 }1017 };1018 RowComp.prototype.onRowHeightChanged = function () {1019 // check for exists first - if the user is resetting the row height, then1020 // it will be null (or undefined) momentarily until the next time the flatten1021 // stage is called where the row will then update again with a new height1022 if (utils_1._.exists(this.rowNode.rowHeight)) {1023 var heightPx_1 = this.rowNode.rowHeight + 'px';1024 this.eAllRowContainers.forEach(function (row) { return row.style.height = heightPx_1; });1025 }1026 };1027 RowComp.prototype.addEventListener = function (eventType, listener) {1028 if (eventType === 'renderedRowRemoved' || eventType === 'rowRemoved') {1029 eventType = events_1.Events.EVENT_VIRTUAL_ROW_REMOVED;1030 console.warn('ag-Grid: Since version 11, event renderedRowRemoved is now called ' + events_1.Events.EVENT_VIRTUAL_ROW_REMOVED);1031 }1032 _super.prototype.addEventListener.call(this, eventType, listener);1033 };1034 RowComp.prototype.removeEventListener = function (eventType, listener) {1035 if (eventType === 'renderedRowRemoved' || eventType === 'rowRemoved') {1036 eventType = events_1.Events.EVENT_VIRTUAL_ROW_REMOVED;1037 console.warn('ag-Grid: Since version 11, event renderedRowRemoved and rowRemoved is now called ' + events_1.Events.EVENT_VIRTUAL_ROW_REMOVED);1038 }1039 _super.prototype.removeEventListener.call(this, eventType, listener);1040 };1041 RowComp.prototype.destroy = function (animate) {1042 if (animate === void 0) { animate = false; }1043 _super.prototype.destroy.call(this);1044 this.active = false;1045 // why do we have this method? shouldn't everything below be added as a destroy func beside1046 // the corresponding create logic?1047 this.destroyFullWidthComponents();1048 if (animate) {1049 this.removeFirstPassFuncs.forEach(function (func) { return func(); });1050 this.removeSecondPassFuncs.push(this.destroyContainingCells.bind(this));1051 }1052 else {1053 this.destroyContainingCells();1054 // we are not animating, so execute the second stage of removal now.1055 // we call getAndClear, so that they are only called once1056 var delayedDestroyFunctions = this.getAndClearDelayedDestroyFunctions();1057 delayedDestroyFunctions.forEach(function (func) { return func(); });1058 }1059 var event = this.createRowEvent(events_1.Events.EVENT_VIRTUAL_ROW_REMOVED);1060 this.dispatchEvent(event);1061 this.beans.eventService.dispatchEvent(event);1062 };1063 RowComp.prototype.destroyContainingCells = function () {1064 this.forEachCellComp(function (renderedCell) { return renderedCell.destroy(); });1065 this.destroyFullWidthComponents();1066 };1067 // we clear so that the functions are never executed twice1068 RowComp.prototype.getAndClearDelayedDestroyFunctions = function () {1069 var result = this.removeSecondPassFuncs;1070 this.removeSecondPassFuncs = [];1071 return result;1072 };1073 RowComp.prototype.onCellFocusChanged = function () {1074 var rowFocused = this.beans.focusedCellController.isRowFocused(this.rowNode.rowIndex, this.rowNode.rowPinned);1075 if (rowFocused !== this.rowFocused) {1076 this.eAllRowContainers.forEach(function (row) { return utils_1._.addOrRemoveCssClass(row, 'ag-row-focus', rowFocused); });1077 this.eAllRowContainers.forEach(function (row) { return utils_1._.addOrRemoveCssClass(row, 'ag-row-no-focus', !rowFocused); });1078 this.rowFocused = rowFocused;1079 }1080 // if we are editing, then moving the focus out of a row will stop editing1081 if (!rowFocused && this.editingRow) {1082 this.stopEditing(false);1083 }1084 };1085 RowComp.prototype.onPaginationChanged = function () {1086 var currentPage = this.beans.paginationProxy.getCurrentPage();1087 // it is possible this row is in the new page, but the page number has changed, which means1088 // it needs to reposition itself relative to the new page1089 if (this.paginationPage !== currentPage) {1090 this.paginationPage = currentPage;1091 this.onTopChanged();1092 }1093 };1094 RowComp.prototype.onTopChanged = function () {1095 this.setRowTop(this.rowNode.rowTop);1096 };1097 // applies pagination offset, eg if on second page, and page height is 500px, then removes1098 // 500px from the top position, so a row with rowTop 600px is displayed at location 100px.1099 // reverse will take the offset away rather than add.1100 RowComp.prototype.applyPaginationOffset = function (topPx, reverse) {1101 if (reverse === void 0) { reverse = false; }1102 if (this.rowNode.isRowPinned()) {1103 return topPx;1104 }1105 else {1106 var pixelOffset = this.beans.paginationProxy.getPixelOffset();1107 if (reverse) {1108 return topPx + pixelOffset;1109 }1110 else {1111 return topPx - pixelOffset;1112 }1113 }1114 };1115 RowComp.prototype.setRowTop = function (pixels) {1116 // need to make sure rowTop is not null, as this can happen if the node was once1117 // visible (ie parent group was expanded) but is now not visible1118 if (utils_1._.exists(pixels)) {1119 var afterPaginationPixels = this.applyPaginationOffset(pixels);1120 var afterScalingPixels = this.beans.heightScaler.getRealPixelPosition(afterPaginationPixels);1121 var topPx_1 = afterScalingPixels + "px";1122 if (this.beans.gridOptionsWrapper.isSuppressRowTransform()) {1123 this.eAllRowContainers.forEach(function (row) { return row.style.top = "" + topPx_1; });1124 }1125 else {1126 this.eAllRowContainers.forEach(function (row) { return row.style.transform = "translateY(" + topPx_1 + ")"; });1127 }1128 }1129 };1130 // we clear so that the functions are never executed twice1131 RowComp.prototype.getAndClearNextVMTurnFunctions = function () {1132 var result = this.createSecondPassFuncs;1133 this.createSecondPassFuncs = [];1134 return result;1135 };1136 RowComp.prototype.getRowNode = function () {1137 return this.rowNode;1138 };1139 RowComp.prototype.getRenderedCellForColumn = function (column) {1140 return this.cellComps[column.getColId()];1141 };1142 RowComp.prototype.onRowIndexChanged = function () {1143 this.onCellFocusChanged();1144 this.updateRowIndexes();1145 };1146 RowComp.prototype.updateRowIndexes = function () {1147 var rowIndexStr = this.rowNode.getRowIndexString();1148 var rowIsEven = this.rowNode.rowIndex % 2 === 0;1149 var rowIsEvenChanged = this.rowIsEven !== rowIsEven;1150 if (rowIsEvenChanged) {1151 this.rowIsEven = rowIsEven;1152 }1153 this.eAllRowContainers.forEach(function (eRow) {1154 eRow.setAttribute('row-index', rowIndexStr);1155 if (rowIsEvenChanged) {1156 utils_1._.addOrRemoveCssClass(eRow, 'ag-row-even', rowIsEven);1157 utils_1._.addOrRemoveCssClass(eRow, 'ag-row-odd', !rowIsEven);1158 }1159 });1160 };1161 RowComp.prototype.ensureDomOrder = function () {1162 var body = this.getBodyRowElement();1163 if (body) {1164 this.bodyContainerComp.ensureDomOrder(body);1165 }1166 var left = this.getPinnedLeftRowElement();1167 if (left) {1168 this.pinnedLeftContainerComp.ensureDomOrder(left);1169 }1170 var right = this.getPinnedRightRowElement();1171 if (right) {1172 this.pinnedRightContainerComp.ensureDomOrder(right);1173 }1174 var fullWidth = this.getFullWidthRowElement();1175 if (fullWidth) {1176 this.fullWidthContainerComp.ensureDomOrder(fullWidth);1177 }1178 };1179 // returns the pinned left container, either the normal one, or the embedded full with one if exists1180 RowComp.prototype.getPinnedLeftRowElement = function () {1181 return this.ePinnedLeftRow ? this.ePinnedLeftRow : this.eFullWidthRowLeft;1182 };1183 // returns the pinned right container, either the normal one, or the embedded full with one if exists1184 RowComp.prototype.getPinnedRightRowElement = function () {1185 return this.ePinnedRightRow ? this.ePinnedRightRow : this.eFullWidthRowRight;1186 };1187 // returns the body container, either the normal one, or the embedded full with one if exists1188 RowComp.prototype.getBodyRowElement = function () {1189 return this.eBodyRow ? this.eBodyRow : this.eFullWidthRowBody;1190 };1191 // returns the full width container1192 RowComp.prototype.getFullWidthRowElement = function () {1193 return this.eFullWidthRow;1194 };1195 RowComp.DOM_DATA_KEY_RENDERED_ROW = 'renderedRow';1196 RowComp.FULL_WIDTH_CELL_RENDERER = 'fullWidthCellRenderer';1197 RowComp.GROUP_ROW_RENDERER = 'groupRowRenderer';1198 RowComp.GROUP_ROW_RENDERER_COMP_NAME = 'agGroupRowRenderer';1199 RowComp.LOADING_CELL_RENDERER = 'loadingCellRenderer';1200 RowComp.LOADING_CELL_RENDERER_COMP_NAME = 'agLoadingCellRenderer';1201 RowComp.DETAIL_CELL_RENDERER = 'detailCellRenderer';1202 RowComp.DETAIL_CELL_RENDERER_COMP_NAME = 'agDetailCellRenderer';1203 return RowComp;1204}(component_1.Component));...

Full Screen

Full Screen

clean_breseq.py

Source:clean_breseq.py Github

copy

Full Screen

1from __future__ import division2import os, re3import numpy as np4import pandas as pd5mydir = os.path.expanduser("~/GitHub/LTDE/")6merged_on = ['seq_id', 'position', 'gene_list', \7 'gene_name', 'gene_position', 'gene_product', \8 'locus_tag', 'gene_strand', 'transl_table', 'reference']9to_rename = ['mutation', 'codon_ref_seq', 'codon_new_seq', 'codon_number', \10 'codon_position', 'aa_position', 'aa_ref_seq', 'aa_new_seq', \11 'frequency', 'total_cov', 'number', 'file_number', \12 'prediction', 'consensus_score', 'polymorphism_score', \13 'fisher_strand_p_value', 'ks_quality_p_value', 'bias_e_value', \14 'bias_p_value', 'reject', 'snp_type', 'type', \15 'major_base', 'minor_base', 'sample']16class cleanBreseq_annotated:17 def __init__(self, path):18 self.path = path19 def clean_value(self, row, value_name):20 value_name = value_name + '='21 data_indices = [i for i, s in enumerate(row) if '=' in s]22 gene_name_index = [i for i, s in enumerate(row) if value_name in s]23 if len(gene_name_index) > 0:24 gene_name_index = gene_name_index[0]25 gene_name_index_end = data_indices.index(gene_name_index)26 if gene_name_index_end+1 >= len(data_indices):27 gene_name = row[gene_name_index:]28 gene_name = '_'.join(gene_name)29 gene_name = re.sub(r'[^\x00-\x7F]+','-', gene_name)30 return row[:gene_name_index] + [gene_name]31 else:32 gene_name = row[gene_name_index:data_indices[gene_name_index_end+1]]33 gene_name = '_'.join(gene_name)34 gene_name = re.sub(r'[^\x00-\x7F]+','-', gene_name)35 return row[:gene_name_index] + [gene_name] + row[data_indices[gene_name_index_end+1]:]36 else:37 return row38 def variant_line(self, row, columns):39 row = self.clean_value(row, 'gene_product')40 row = self.clean_value(row, 'gene_position')41 row = self.clean_value(row, 'gene_name')42 row = self.clean_value(row, 'locus_tag')43 row = self.clean_value(row, 'between')44 if row[0] == 'SNP':45 # 7 b/c added column for insertion length (which is nan for SNPs)46 columns_6_inf = columns[7:]47 row_0_6 = row[:6]48 row_6_inf = row[6:]49 row_list = []50 values_dict = dict(item.split("=") for item in row_6_inf if '=' in item)51 for column in columns_6_inf:52 if column in values_dict:53 row_list.append(values_dict[column])54 else:55 row_list.append(float('nan'))56 row_list = [str(x) for x in row_list]57 # add one for point mutations58 new_row = row_0_6 + ['nan'] + row_list59 return new_row60 elif row[0] == 'SUB':61 row[6], row[5] = row[5], row[6]62 columns_7_inf = columns[7:]63 row_0_7 = row[:7]64 row_7_inf = row[7:]65 row_list = []66 values_dict = dict(item.split("=") for item in row_7_inf)67 for column in columns_7_inf:68 if column in values_dict:69 row_list.append(values_dict[column])70 else:71 row_list.append(float('nan'))72 row_list = [str(x) for x in row_list]73 new_row = row_0_7 + row_list74 return new_row75 elif row[0] == 'INS':76 # 7 b/c added column for insertion length (which is nan for SNPs)77 columns_6_inf = columns[7:]78 row_0_6 = row[:6]79 row_6_inf = row[6:]80 row_list = []81 values_dict = dict(item.split("=") for item in row_6_inf)82 for column in columns_6_inf:83 if column in values_dict:84 row_list.append(values_dict[column])85 else:86 row_list.append(float('nan'))87 row_list = [str(x) for x in row_list]88 # add length of insertion89 new_row = row_0_6 + [str(len(row_0_6[-1]))] + row_list90 return new_row91 elif row[0] == 'DEL':92 # 7 b/c added column for insertion length (which is nan for SNPs)93 columns_6_inf = columns[7:]94 row_0_6 = row[:6]95 row_6_inf = row[6:]96 row_list = []97 values_dict = dict(item.split("=") for item in row_6_inf if '=' in item)98 for column in columns_6_inf:99 if column in values_dict:100 row_list.append(values_dict[column])101 else:102 row_list.append(float('nan'))103 row_list = [str(x) for x in row_list]104 # add length of insertion105 new_row = row_0_6 + ['nan'] + row_list106 return new_row107 def RA_line(self, row, columns):108 row = self.clean_value(row, 'gene_product')109 row = self.clean_value(row, 'gene_position')110 row = self.clean_value(row, 'gene_name')111 row = self.clean_value(row, 'locus_tag')112 row = self.clean_value(row, 'between')113 columns = columns[8:]114 row_0_8 = row[:8]115 row_8_inf = row[8:]116 row_list = []117 values_dict = dict(item.split("=") for item in row_8_inf if '=' in item)118 for column in columns:119 if column in values_dict:120 row_list.append(values_dict[column])121 else:122 row_list.append(float('nan'))123 row_list = [str(x) for x in row_list]124 new_row = row_0_8 + row_list125 return new_row126 def MC_line(self, row, columns):127 row = self.clean_value(row, 'gene_product')128 row = self.clean_value(row, 'gene_position')129 row = self.clean_value(row, 'locus_tag')130 row = self.clean_value(row, 'gene_name')131 row = self.clean_value(row, 'gene_list')132 row = self.clean_value(row, 'html_gene_name')133 columns = columns[8:]134 row_0_8 = row[:8]135 row_8_inf = row[8:]136 row_list = []137 values_dict = dict(item.split("=") for item in row_8_inf)138 for column in columns:139 if column in values_dict:140 row_list.append(values_dict[column])141 else:142 row_list.append(float('nan'))143 row_list = [str(x) for x in row_list]144 new_row = row_0_8 + row_list145 return new_row146 def JC_line(self, row, columns):147 columns = columns[10:]148 row_0_8 = row[:10]149 row_8_inf = row[10:]150 row_list = []151 values_dict = dict(item.split("=") for item in row_8_inf)152 for column in columns:153 if column in values_dict:154 row_list.append(values_dict[column])155 else:156 row_list.append(float('nan'))157 row_list = [str(x) for x in row_list]158 new_row = row_0_8 + row_list159 return new_row160 def split_annotated(self):161 path_split = self.path.split('/')162 path = '/'.join(path_split[:-3]) + '/breseq_essentials_split/' + path_split[8:9][0]163 if not os.path.exists(path):164 os.makedirs(path)165 OUT_RA = open(path + '/evidence_RA.txt', 'w')166 OUT_MC = open(path + '/evidence_MC.txt', 'w')167 OUT_JC = open(path + '/evidence_JC.txt', 'w')168 OUT_UN = open(path + '/evidence_UN.txt', 'w')169 OUT_variants = open(path + '/evidence_variants.txt', 'w')170 columns_variants = ['type','number', 'file_number', 'seq_id', 'position', \171 'mutation', 'size', 'frequency', 'gene_list', 'gene_name', 'gene_position', \172 'gene_product', 'locus_tag', 'snp_type', 'aa_new_seq', 'aa_position', \173 'aa_ref_seq', 'codon_new_seq', 'codon_number', 'codon_position', \174 'codon_ref_seq', 'gene_strand', 'transl_table', 'insert_position', 'between']175 columns_RA = ['type','number', 'misc', 'seq_id', 'position', 'change', \176 'reference', 'sample', 'total_cov', 'new_cov', 'ref_cov', 'major_cov', \177 'minor_cov', 'major_base', 'minor_base', 'prediction', 'frequency', \178 'polymorphism_frequency', 'major_frequency', 'consensus_score', \179 'polymorphism_score', 'fisher_strand_p_value', 'ks_quality_p_value', \180 'bias_e_value', 'reject', 'snp_type', 'locus_tag', 'gene_product', \181 'gene_position', 'gene_list', 'gene_name', 'bias_p_value']182 columns_MC = ['type', 'number', 'misc', 'seq_id', 'start', 'finish', \183 'zero1', 'zero2', 'left_inside_cov', 'left_outside_cov', \184 'right_inside_cov', 'right_outside_cov', 'gene_list', 'gene_name', \185 'gene_position', 'gene_product', 'locus_tag']186 columns_JC = ['type', 'number', 'misc', 'seq_id_start', 'start', 'strand'\187 'seq_id_finish', 'finish', 'unknown1', 'unknown2' 'side_1_read_count', \188 'max_right_plus', 'coverage_minus', 'prediction', 'frequency', \189 'polymorphism_frequency', 'max_min_left_plus', 'side_2_annotate_key', \190 'alignment_overlap', 'max_left_plus', 'max_min_left', 'flanking_left', \191 'max_left', 'max_min_right_plus', 'total_non_overlap_reads', \192 'coverage_plus', 'side_2_overlap', 'neg_log10_pos_hash_p_value', \193 'max_left_minus', 'side_2_redundant', 'side_1_possible_overlap_registers', \194 'side_2_coverage', 'side_1_continuation', 'max_right_minus', \195 'side_1_redundant', 'side_2_possible_overlap_registers', \196 'unique_read_sequence', 'max_min_left_minus', \197 'new_junction_read_count', 'max_pos_hash_score', 'key', \198 'side_2_continuation', 'pos_hash_score', \199 'junction_possible_overlap_registers', 'side_1_overlap', \200 'max_min_right', 'flanking_right', 'max_right', 'side_1_coverage', \201 'side_2_read_count', 'max_min_right_minus', 'new_junction_coverage', \202 'side_1_annotate_key']203 columns_UN = ['type', 'number', 'misc', 'seq_id', 'start', 'finish']204 print('\t'.join(columns_RA), file=OUT_RA)205 print('\t'.join(columns_MC), file=OUT_MC)206 print('\t'.join(columns_JC), file=OUT_JC)207 print('\t'.join(columns_UN), file=OUT_UN)208 print('\t'.join(columns_variants), file=OUT_variants)209 #print>> OUT_RA, '\t'.join(columns_RA)210 #print>> OUT_MC, '\t'.join(columns_MC)211 #print>> OUT_JC, '\t'.join(columns_JC)212 #print>> OUT_UN, '\t'.join(columns_UN)213 #print>> OUT_variants, '\t'.join(columns_variants)214 set_test = []215 with open(self.path) as f:216 for row in f:217 row = row.split()218 if len(row) < 3:219 continue220 if row[0] == 'DEL' or row[0] == 'SNP' or \221 row[0] == 'SUB' or row[0] == 'INS':222 row_clean = self.variant_line(row, columns_variants)223 #print>> OUT_variants, '\t'.join(row_clean)224 print('\t'.join(row_clean), file=OUT_variants)225 elif row[0] == 'RA':226 row_clean = self.RA_line(row, columns_RA)227 #print>> OUT_RA, '\t'.join(row_clean)228 print('\t'.join(row_clean), file=OUT_RA)229 elif row[0] == 'MC':230 row_clean = self.MC_line(row, columns_RA)231 elif row[0] == 'JC':232 row_clean = self.JC_line(row, columns_RA)233 elif row[0] == 'UN':234 #print>> OUT_UN, '\t'.join(row)235 print('\t'.join(row), file=OUT_UN)236 else:237 continue238 OUT_RA.close()239 OUT_MC.close()240 OUT_JC.close()241 OUT_UN.close()242 OUT_variants.close()243def get_variant_annotated(variant_type, strain):244 in_path = mydir + 'data/breseq/breseq_essentials_split/' + strain245 variants_path = in_path + '/evidence_variants.txt'246 RA_path = in_path + '/evidence_RA.txt'247 if os.path.exists(variants_path) == True:248 IN_variants = pd.read_csv(variants_path, sep = '\t', header = 'infer')249 IN_RA = pd.read_csv(RA_path, sep = '\t', header = 'infer')250 IN_variants_SNPs = IN_variants.loc[IN_variants['type'] == variant_type]251 IN_variants_SNPs = IN_variants_SNPs.drop(['size'], axis=1)252 drop_RA = ['gene_product', 'frequency', 'gene_list', 'gene_name', \253 'gene_position', 'locus_tag', 'snp_type', 'type', 'number']254 IN_RA = IN_RA.drop(drop_RA, axis=1)255 IN_variants_SNPs.position = IN_variants_SNPs.position.astype(str)256 IN_variants_SNPs.seq_id = IN_variants_SNPs.seq_id.astype(str)257 IN_RA.position = IN_RA.position.astype(str)258 IN_RA.seq_id = IN_RA.seq_id.astype(str)259 IN_merged = pd.merge(IN_variants_SNPs, IN_RA, how='inner',260 on=['seq_id', 'position'])261 out_path = mydir + 'data/breseq/breseq_essentials_split_clean/' + strain262 if variant_type == 'INS':263 drop_dups_on = ['type', 'seq_id', 'position']264 IN_merged = IN_merged.drop_duplicates(subset=drop_dups_on, keep="first")265 if not os.path.exists(out_path):266 os.makedirs(out_path)267 #print IN_variants_SNPs268 IN_merged.to_csv(out_path + '/' + variant_type +'.txt', sep = '\t', index = False)269def merge_variant_annotated(strain, variant_type):270 count = 0271 rootdir = mydir + 'data/breseq/breseq_essentials_split_clean/'272 for folder in os.listdir(rootdir):273 if strain not in folder:274 continue275 path = rootdir + folder + '/' + variant_type +'.txt'276 IN = pd.read_csv(path, sep = '\t', header = 'infer')277 renamed = []278 for x in to_rename:279 x_renamed = x + '_' + folder280 IN = IN.rename(columns = {x : x_renamed})281 renamed.append(x_renamed)282 if count == 0:283 merged = IN284 frequency = 'frequency_' + folder285 merged_freq = merged[frequency]286 merged.drop(labels=[frequency], axis=1,inplace = True)287 merged.insert(len(merged.columns)-1, frequency, merged_freq)288 else:289 merged_keep = renamed + merged_on290 merged = pd.merge(merged, IN[merged_keep], \291 how='outer', on = merged_on)292 count += 1293 test = merged.columns.tolist()294 for i, column in enumerate(merged_on):295 test.remove(column)296 test.insert(i, column)297 merged = merged.reindex_axis(test, axis=1)298 sample_freqs = [x for x in merged.columns if 'frequency_' in x]299 merged_freqs = merged[sample_freqs]300 samples = merged_freqs.shape[1]301 NoDups = merged_freqs[merged_freqs.apply(lambda x: x.isnull().sum() == samples - 1, 1)]302 NoDups_index = NoDups.index.values303 merged_unique = merged.ix[NoDups_index]304 if merged_unique.shape[0] == 0:305 return306 OUT_path = mydir + 'data/breseq/breseq_essentials_split_clean_split/' + strain307 if not os.path.exists(OUT_path):308 os.makedirs(OUT_path)309 reps = [x.split('_')[1] for x in merged_unique.columns if 'frequency_' in x]310 for rep in reps:311 to_rename_rep = [x + '_' + rep for x in to_rename]312 to_slice = merged_on + to_rename_rep313 merged_unique_rep = merged_unique[to_slice]314 set_p = list(set(merged_unique_rep['bias_p_value_' + rep].values))315 if (len(set_p)) == 1 and (np.isnan(set_p[0]) == True):316 continue317 merged_unique_rep = merged_unique_rep[np.isfinite(merged_unique_rep['bias_p_value_' + rep])]318 OUT_path_rep = OUT_path + '/' + rep + '_' + variant_type +'.txt'319 merged_unique_rep.to_csv(OUT_path_rep, sep = '\t', index = False)320 #OUT_name = OUT_path + '/' + variant_type + '.txt'321 #merged_unique.to_csv(OUT_name, sep = '\t', index = False)322def run_everything():323 strains = []324 variants = ['SNP','INS','DEL']325 rootdir = mydir + 'data/breseq/breseq_essentials'326 for filename in os.listdir(rootdir):327 if filename == '.DS_Store':328 continue329 #annotated_path = rootdir + '/' + filename + '/annotated.gd'330 #cleanBreseq_annotated(annotated_path).split_annotated()331 #for variant in variants:332 # get_variant_annotated(variant, strain = filename)333 strains.append(filename.split('-')[0])334 strains = list(set(strains))335 for strain in strains:336 print(strain)337 for variant in variants:338 merge_variant_annotated(strain, variant)339 # split the merged file into reps340 #if unique_mutations == True:341 # #print "unique_mutations"342 # get_unique_mutations(day, strain, variant_type)...

Full Screen

Full Screen

factory.py

Source:factory.py Github

copy

Full Screen

1#-*- coding: ISO-8859-1 -*-2# pysqlite2/test/factory.py: tests for the various factories in pysqlite3#4# Copyright (C) 2005-2007 Gerhard Häring <gh@ghaering.de>5#6# This file is part of pysqlite.7#8# This software is provided 'as-is', without any express or implied9# warranty. In no event will the authors be held liable for any damages10# arising from the use of this software.11#12# Permission is granted to anyone to use this software for any purpose,13# including commercial applications, and to alter it and redistribute it14# freely, subject to the following restrictions:15#16# 1. The origin of this software must not be misrepresented; you must not17# claim that you wrote the original software. If you use this software18# in a product, an acknowledgment in the product documentation would be19# appreciated but is not required.20# 2. Altered source versions must be plainly marked as such, and must not be21# misrepresented as being the original software.22# 3. This notice may not be removed or altered from any source distribution.23import unittest24import sqlite3 as sqlite25from collections import Sequence26class MyConnection(sqlite.Connection):27 def __init__(self, *args, **kwargs):28 sqlite.Connection.__init__(self, *args, **kwargs)29def dict_factory(cursor, row):30 d = {}31 for idx, col in enumerate(cursor.description):32 d[col[0]] = row[idx]33 return d34class MyCursor(sqlite.Cursor):35 def __init__(self, *args, **kwargs):36 sqlite.Cursor.__init__(self, *args, **kwargs)37 self.row_factory = dict_factory38class ConnectionFactoryTests(unittest.TestCase):39 def setUp(self):40 self.con = sqlite.connect(":memory:", factory=MyConnection)41 def tearDown(self):42 self.con.close()43 def CheckIsInstance(self):44 self.assertIsInstance(self.con, MyConnection)45class CursorFactoryTests(unittest.TestCase):46 def setUp(self):47 self.con = sqlite.connect(":memory:")48 def tearDown(self):49 self.con.close()50 def CheckIsInstance(self):51 cur = self.con.cursor(factory=MyCursor)52 self.assertIsInstance(cur, MyCursor)53class RowFactoryTestsBackwardsCompat(unittest.TestCase):54 def setUp(self):55 self.con = sqlite.connect(":memory:")56 def CheckIsProducedByFactory(self):57 cur = self.con.cursor(factory=MyCursor)58 cur.execute("select 4+5 as foo")59 row = cur.fetchone()60 self.assertIsInstance(row, dict)61 cur.close()62 def tearDown(self):63 self.con.close()64class RowFactoryTests(unittest.TestCase):65 def setUp(self):66 self.con = sqlite.connect(":memory:")67 def CheckCustomFactory(self):68 self.con.row_factory = lambda cur, row: list(row)69 row = self.con.execute("select 1, 2").fetchone()70 self.assertIsInstance(row, list)71 def CheckSqliteRowIndex(self):72 self.con.row_factory = sqlite.Row73 row = self.con.execute("select 1 as a, 2 as b").fetchone()74 self.assertIsInstance(row, sqlite.Row)75 col1, col2 = row["a"], row["b"]76 self.assertEqual(col1, 1, "by name: wrong result for column 'a'")77 self.assertEqual(col2, 2, "by name: wrong result for column 'a'")78 col1, col2 = row["A"], row["B"]79 self.assertEqual(col1, 1, "by name: wrong result for column 'A'")80 self.assertEqual(col2, 2, "by name: wrong result for column 'B'")81 self.assertEqual(row[0], 1, "by index: wrong result for column 0")82 self.assertEqual(row[0L], 1, "by index: wrong result for column 0")83 self.assertEqual(row[1], 2, "by index: wrong result for column 1")84 self.assertEqual(row[1L], 2, "by index: wrong result for column 1")85 self.assertEqual(row[-1], 2, "by index: wrong result for column -1")86 self.assertEqual(row[-1L], 2, "by index: wrong result for column -1")87 self.assertEqual(row[-2], 1, "by index: wrong result for column -2")88 self.assertEqual(row[-2L], 1, "by index: wrong result for column -2")89 with self.assertRaises(IndexError):90 row['c']91 with self.assertRaises(IndexError):92 row[2]93 with self.assertRaises(IndexError):94 row[2L]95 with self.assertRaises(IndexError):96 row[-3]97 with self.assertRaises(IndexError):98 row[-3L]99 with self.assertRaises(IndexError):100 row[2**1000]101 def CheckSqliteRowIter(self):102 """Checks if the row object is iterable"""103 self.con.row_factory = sqlite.Row104 row = self.con.execute("select 1 as a, 2 as b").fetchone()105 for col in row:106 pass107 def CheckSqliteRowAsTuple(self):108 """Checks if the row object can be converted to a tuple"""109 self.con.row_factory = sqlite.Row110 row = self.con.execute("select 1 as a, 2 as b").fetchone()111 t = tuple(row)112 self.assertEqual(t, (row['a'], row['b']))113 def CheckSqliteRowAsDict(self):114 """Checks if the row object can be correctly converted to a dictionary"""115 self.con.row_factory = sqlite.Row116 row = self.con.execute("select 1 as a, 2 as b").fetchone()117 d = dict(row)118 self.assertEqual(d["a"], row["a"])119 self.assertEqual(d["b"], row["b"])120 def CheckSqliteRowHashCmp(self):121 """Checks if the row object compares and hashes correctly"""122 self.con.row_factory = sqlite.Row123 row_1 = self.con.execute("select 1 as a, 2 as b").fetchone()124 row_2 = self.con.execute("select 1 as a, 2 as b").fetchone()125 row_3 = self.con.execute("select 1 as a, 3 as b").fetchone()126 self.assertEqual(row_1, row_1)127 self.assertEqual(row_1, row_2)128 self.assertTrue(row_2 != row_3)129 self.assertFalse(row_1 != row_1)130 self.assertFalse(row_1 != row_2)131 self.assertFalse(row_2 == row_3)132 self.assertEqual(row_1, row_2)133 self.assertEqual(hash(row_1), hash(row_2))134 self.assertNotEqual(row_1, row_3)135 self.assertNotEqual(hash(row_1), hash(row_3))136 def CheckSqliteRowAsSequence(self):137 """ Checks if the row object can act like a sequence """138 self.con.row_factory = sqlite.Row139 row = self.con.execute("select 1 as a, 2 as b").fetchone()140 as_tuple = tuple(row)141 self.assertEqual(list(reversed(row)), list(reversed(as_tuple)))142 self.assertIsInstance(row, Sequence)143 def tearDown(self):144 self.con.close()145class TextFactoryTests(unittest.TestCase):146 def setUp(self):147 self.con = sqlite.connect(":memory:")148 def CheckUnicode(self):149 austria = unicode("Österreich", "latin1")150 row = self.con.execute("select ?", (austria,)).fetchone()151 self.assertEqual(type(row[0]), unicode, "type of row[0] must be unicode")152 def CheckString(self):153 self.con.text_factory = str154 austria = unicode("Österreich", "latin1")155 row = self.con.execute("select ?", (austria,)).fetchone()156 self.assertEqual(type(row[0]), str, "type of row[0] must be str")157 self.assertEqual(row[0], austria.encode("utf-8"), "column must equal original data in UTF-8")158 def CheckCustom(self):159 self.con.text_factory = lambda x: unicode(x, "utf-8", "ignore")160 austria = unicode("Österreich", "latin1")161 row = self.con.execute("select ?", (austria.encode("latin1"),)).fetchone()162 self.assertEqual(type(row[0]), unicode, "type of row[0] must be unicode")163 self.assertTrue(row[0].endswith(u"reich"), "column must contain original data")164 def CheckOptimizedUnicode(self):165 self.con.text_factory = sqlite.OptimizedUnicode166 austria = unicode("Österreich", "latin1")167 germany = unicode("Deutchland")168 a_row = self.con.execute("select ?", (austria,)).fetchone()169 d_row = self.con.execute("select ?", (germany,)).fetchone()170 self.assertEqual(type(a_row[0]), unicode, "type of non-ASCII row must be unicode")171 self.assertEqual(type(d_row[0]), str, "type of ASCII-only row must be str")172 def tearDown(self):173 self.con.close()174class TextFactoryTestsWithEmbeddedZeroBytes(unittest.TestCase):175 def setUp(self):176 self.con = sqlite.connect(":memory:")177 self.con.execute("create table test (value text)")178 self.con.execute("insert into test (value) values (?)", ("a\x00b",))179 def CheckString(self):180 # text_factory defaults to unicode181 row = self.con.execute("select value from test").fetchone()182 self.assertIs(type(row[0]), unicode)183 self.assertEqual(row[0], "a\x00b")184 def CheckCustom(self):185 # A custom factory should receive an str argument186 self.con.text_factory = lambda x: x187 row = self.con.execute("select value from test").fetchone()188 self.assertIs(type(row[0]), str)189 self.assertEqual(row[0], "a\x00b")190 def CheckOptimizedUnicodeAsString(self):191 # ASCII -> str argument192 self.con.text_factory = sqlite.OptimizedUnicode193 row = self.con.execute("select value from test").fetchone()194 self.assertIs(type(row[0]), str)195 self.assertEqual(row[0], "a\x00b")196 def CheckOptimizedUnicodeAsUnicode(self):197 # Non-ASCII -> unicode argument198 self.con.text_factory = sqlite.OptimizedUnicode199 self.con.execute("delete from test")200 self.con.execute("insert into test (value) values (?)", (u'ä\0ö',))201 row = self.con.execute("select value from test").fetchone()202 self.assertIs(type(row[0]), unicode)203 self.assertEqual(row[0], u"ä\x00ö")204 def tearDown(self):205 self.con.close()206def suite():207 connection_suite = unittest.makeSuite(ConnectionFactoryTests, "Check")208 cursor_suite = unittest.makeSuite(CursorFactoryTests, "Check")209 row_suite_compat = unittest.makeSuite(RowFactoryTestsBackwardsCompat, "Check")210 row_suite = unittest.makeSuite(RowFactoryTests, "Check")211 text_suite = unittest.makeSuite(TextFactoryTests, "Check")212 text_zero_bytes_suite = unittest.makeSuite(TextFactoryTestsWithEmbeddedZeroBytes, "Check")213 return unittest.TestSuite((connection_suite, cursor_suite, row_suite_compat, row_suite, text_suite, text_zero_bytes_suite))214def test():215 runner = unittest.TextTestRunner()216 runner.run(suite())217if __name__ == "__main__":...

Full Screen

Full Screen

rowNodeBlock.js

Source:rowNodeBlock.js Github

copy

Full Screen

1/**2 * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components3 * @version v18.0.14 * @link http://www.ag-grid.com/5 * @license MIT6 */7"use strict";8var __extends = (this && this.__extends) || (function () {9 var extendStatics = Object.setPrototypeOf ||10 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||11 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };12 return function (d, b) {13 extendStatics(d, b);14 function __() { this.constructor = d; }15 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());16 };17})();18Object.defineProperty(exports, "__esModule", { value: true });19var utils_1 = require("../../utils");20var rowNode_1 = require("../../entities/rowNode");21var beanStub_1 = require("../../context/beanStub");22var RowNodeBlock = (function (_super) {23 __extends(RowNodeBlock, _super);24 function RowNodeBlock(blockNumber, rowNodeCacheParams) {25 var _this = _super.call(this) || this;26 _this.version = 0;27 _this.state = RowNodeBlock.STATE_DIRTY;28 _this.rowNodeCacheParams = rowNodeCacheParams;29 _this.blockNumber = blockNumber;30 // we don't need to calculate these now, as the inputs don't change,31 // however it makes the code easier to read if we work them out up front32 _this.startRow = blockNumber * rowNodeCacheParams.blockSize;33 _this.endRow = _this.startRow + rowNodeCacheParams.blockSize;34 return _this;35 }36 RowNodeBlock.prototype.isAnyNodeOpen = function (rowCount) {37 var result = false;38 this.forEachNodeCallback(function (rowNode) {39 if (rowNode.expanded) {40 result = true;41 }42 }, rowCount);43 return result;44 };45 RowNodeBlock.prototype.forEachNodeCallback = function (callback, rowCount) {46 for (var rowIndex = this.startRow; rowIndex < this.endRow; rowIndex++) {47 // we check against rowCount as this page may be the last one, and if it is, then48 // the last rows are not part of the set49 if (rowIndex < rowCount) {50 var rowNode = this.getRowUsingLocalIndex(rowIndex);51 callback(rowNode, rowIndex);52 }53 }54 };55 RowNodeBlock.prototype.forEachNode = function (callback, sequence, rowCount, deep) {56 this.forEachNodeCallback(function (rowNode) {57 callback(rowNode, sequence.next());58 // this will only every happen for server side row model, as infinite59 // row model doesn't have groups60 if (deep && rowNode.childrenCache) {61 rowNode.childrenCache.forEachNodeDeep(callback, sequence);62 }63 }, rowCount);64 };65 RowNodeBlock.prototype.forEachNodeDeep = function (callback, sequence, rowCount) {66 this.forEachNode(callback, sequence, rowCount, true);67 };68 RowNodeBlock.prototype.forEachNodeShallow = function (callback, sequence, rowCount) {69 this.forEachNode(callback, sequence, rowCount, false);70 };71 RowNodeBlock.prototype.getVersion = function () {72 return this.version;73 };74 RowNodeBlock.prototype.getLastAccessed = function () {75 return this.lastAccessed;76 };77 RowNodeBlock.prototype.getRowUsingLocalIndex = function (rowIndex, dontTouchLastAccessed) {78 if (dontTouchLastAccessed === void 0) { dontTouchLastAccessed = false; }79 if (!dontTouchLastAccessed) {80 this.lastAccessed = this.rowNodeCacheParams.lastAccessedSequence.next();81 }82 var localIndex = rowIndex - this.startRow;83 return this.rowNodes[localIndex];84 };85 RowNodeBlock.prototype.init = function (beans) {86 this.beans = beans;87 this.createRowNodes();88 };89 RowNodeBlock.prototype.getStartRow = function () {90 return this.startRow;91 };92 RowNodeBlock.prototype.getEndRow = function () {93 return this.endRow;94 };95 RowNodeBlock.prototype.getBlockNumber = function () {96 return this.blockNumber;97 };98 RowNodeBlock.prototype.setDirty = function () {99 // in case any current loads in progress, this will have their results ignored100 this.version++;101 this.state = RowNodeBlock.STATE_DIRTY;102 };103 RowNodeBlock.prototype.setDirtyAndPurge = function () {104 this.setDirty();105 this.rowNodes.forEach(function (rowNode) {106 rowNode.setData(null);107 });108 };109 RowNodeBlock.prototype.getState = function () {110 return this.state;111 };112 RowNodeBlock.prototype.setRowNode = function (rowIndex, rowNode) {113 var localIndex = rowIndex - this.startRow;114 this.rowNodes[localIndex] = rowNode;115 };116 RowNodeBlock.prototype.setBlankRowNode = function (rowIndex) {117 var localIndex = rowIndex - this.startRow;118 var newRowNode = this.createBlankRowNode(rowIndex);119 this.rowNodes[localIndex] = newRowNode;120 return newRowNode;121 };122 RowNodeBlock.prototype.setNewData = function (rowIndex, dataItem) {123 var newRowNode = this.setBlankRowNode(rowIndex);124 this.setDataAndId(newRowNode, dataItem, this.startRow + rowIndex);125 return newRowNode;126 };127 RowNodeBlock.prototype.createBlankRowNode = function (rowIndex) {128 var rowNode = new rowNode_1.RowNode();129 this.beans.context.wireBean(rowNode);130 rowNode.setRowHeight(this.rowNodeCacheParams.rowHeight);131 return rowNode;132 };133 // creates empty row nodes, data is missing as not loaded yet134 RowNodeBlock.prototype.createRowNodes = function () {135 this.rowNodes = [];136 for (var i = 0; i < this.rowNodeCacheParams.blockSize; i++) {137 var rowIndex = this.startRow + i;138 var rowNode = this.createBlankRowNode(rowIndex);139 this.rowNodes.push(rowNode);140 }141 };142 RowNodeBlock.prototype.load = function () {143 this.state = RowNodeBlock.STATE_LOADING;144 this.loadFromDatasource();145 };146 RowNodeBlock.prototype.pageLoadFailed = function () {147 this.state = RowNodeBlock.STATE_FAILED;148 var event = {149 type: RowNodeBlock.EVENT_LOAD_COMPLETE,150 success: false,151 page: this,152 lastRow: null153 };154 this.dispatchEvent(event);155 };156 RowNodeBlock.prototype.populateWithRowData = function (rows) {157 var _this = this;158 var rowNodesToRefresh = [];159 this.rowNodes.forEach(function (rowNode, index) {160 var data = rows[index];161 if (rowNode.stub) {162 rowNodesToRefresh.push(rowNode);163 }164 _this.setDataAndId(rowNode, data, _this.startRow + index);165 });166 if (rowNodesToRefresh.length > 0) {167 this.beans.rowRenderer.redrawRows(rowNodesToRefresh);168 }169 };170 RowNodeBlock.prototype.destroy = function () {171 _super.prototype.destroy.call(this);172 this.rowNodes.forEach(function (rowNode) {173 if (rowNode.childrenCache) {174 rowNode.childrenCache.destroy();175 rowNode.childrenCache = null;176 }177 // this is needed, so row render knows to fade out the row, otherwise it178 // see's row top is present, and thinks the row should be shown. maybe179 // rowNode should have a flag on whether it is visible???180 rowNode.clearRowTop();181 });182 };183 RowNodeBlock.prototype.pageLoaded = function (version, rows, lastRow) {184 // we need to check the version, in case there was an old request185 // from the server that was sent before we refreshed the cache,186 // if the load was done as a result of a cache refresh187 if (version === this.version) {188 this.state = RowNodeBlock.STATE_LOADED;189 this.populateWithRowData(rows);190 }191 lastRow = utils_1.Utils.cleanNumber(lastRow);192 // check here if lastrow should be set193 var event = {194 type: RowNodeBlock.EVENT_LOAD_COMPLETE,195 success: true,196 page: this,197 lastRow: lastRow198 };199 this.dispatchEvent(event);200 };201 RowNodeBlock.EVENT_LOAD_COMPLETE = 'loadComplete';202 RowNodeBlock.STATE_DIRTY = 'dirty';203 RowNodeBlock.STATE_LOADING = 'loading';204 RowNodeBlock.STATE_LOADED = 'loaded';205 RowNodeBlock.STATE_FAILED = 'failed';206 return RowNodeBlock;207}(beanStub_1.BeanStub));...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run pom automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful