Best JavaScript code snippet using puppeteer
VAutoLayoutFrame.js
Source:VAutoLayoutFrame.js
1'use strict';2function VAutoLayoutFrame()3{4 VBaseFrame.call(this);5 this.PublicForBusiness = new VAutoLayoutFrame_ForBusiness();6 this.UsedTemplatesIds = RequiredTemplates.AutoLayoutFrame;7 this.Layout = ko.observableArray();8 this.OpenMode = null;9 10 this.ChildFrames = { All: [], WoTabs: [], ByTabs: {}, ByIds: {} };11 var layoutCreated = false;12 this.IsNewEntity = false;13 this.Type = 'auto-layout';14 this.CreateLayout = function (layout)15 {16 if (!layoutCreated)17 {18 if (this.CurrentEntity())19 {20 FindChildFramesRecursive(layout, this.ChildFrames);21 this.Layout.push(layout);22 }23 if (this.OpenMode == NxOpenMode.New || this.OpenMode == NxOpenMode.ChildNew)24 this.IsNewEntity = true;25 this.InitDateControls();26 if (this.ChildFrames.All.length > 0)27 {28 $('#' + this.TempId).find('[class="ChildFrameHolder"]').last().hide();29 }30 //var tabs = $('[c-type="tabsContent"]');31 //if (tabs.length == 1)32 //{33 // var root = $('#layout_root_' + this.TempId)[0];34 // var commandBars = $(root).find('[id^=commandsBar_]');35 // $(commandBars).removeClass('CommandsBar_Child');36 //}37 layoutCreated = true;38 } 39 40 41 Resizer.ResizeRequest(new Delegate(this.Resize, this));42 for (var i = 0; i < this.ChildFrames.WoTabs.length; i++)43 {44 if (this.ChildFrames.WoTabs[i].LayoutElement != this.Layout()[0])45 RunChildFrame.call(this, this.ChildFrames.WoTabs[i]);46 }47 for (var i = 0; i < this.ChildFrames.All.length; i++)48 {49 if (this.ChildFrames.All[i].IsOpened)50 {51 var f = this.ChildFrames.All[i];52 //if (!f.FrameHolder)53 //{54 // f = this.ChildFrames.ByIds[f.LayoutElement.Id];55 //}56 if (f != this.Layout()[0])57 RunChildFrame.call(this, f);58 59 }60 61 }62 };63 function RunChildFrame(frameElement)64 {65 if (!frameElement.BFrame)66 {67 var frameInstance = Metadata.CreateClassInstance(frameElement.LayoutElement.FrameClassId);68 if (!frameInstance)69 {70 var layout = Metadata.GetFrame(frameElement.LayoutElement.FrameClassId);71 var frameInstance = BAutoLayoutFrame.CreateInstance();72 if (!layout)73 frameInstance.Layout = Metadata.GetFrame("DefaultDetailsLayout".toUpperCase());74 else75 frameInstance.Layout = layout;76 }77 var childOpenMode;78 if (this.OpenMode == NxOpenMode.ChildEdit || this.OpenMode == NxOpenMode.Edit)79 childOpenMode = NxOpenMode.ChildEdit;80 if (this.OpenMode == NxOpenMode.ChildView || this.OpenMode == NxOpenMode.View)81 childOpenMode = NxOpenMode.ChildView;82 if (this.OpenMode == NxOpenMode.ChildNew || this.OpenMode == NxOpenMode.New)83 childOpenMode = NxOpenMode.ChildNew;84 var frameData = {85 CurrentEntityUsageId: frameElement.LayoutElement.EntityUsageId,86 ParentEntity: this.BusinessLayer.GetCurrentEntity(),87 ParentEntityUsageId: this.EntityUsage.Id,88 EntityUsageId: frameElement.LayoutElement.EntityUsageId,89 ParentPks: this.BusinessLayer.GetCurrentEntityPks(),90 OpenMode: childOpenMode,91 FrameHolderId: frameElement.FrameHolder.id92 };93 frameInstance.InitFrame(frameData)94 if (this.ChildFrames.All.length == 1)95 {96 $('#child_frame_holder_' + this.TempId + frameInstance.EntityMetadataId).first().show();97 if(this.Layout()[0] && this.Layout()[0].Children[0] && this.Layout()[0].Children[0].Type == "tab_control")98 $('#' + this.TempId).find('[class="ChildFrameHolder"]').last().hide();99 if (this.Layout()[0] && this.Layout()[0].Children.length > 2)100 $('#' + this.TempId).find('[class="ChildFrameHolder"]').last().hide();101 102 }103 104 frameElement.BFrame = frameInstance;105 }106 if (frameElement.BFrame)107 {108 if (!frameElement.BFrame.DataLoaded)109 frameElement.BFrame.Run();110 else111 frameElement.BFrame.Refresh();112 }113 };114 function FindChildFramesRecursive(layout, foundContainer)115 {116 if (layout.Type == 'frame' && (!App.Utils.IsStringNullOrWhitespace(layout.FrameClassId) || (!App.Utils.IsStringNullOrWhitespace(layout.SlAutoLayoutFrameId))))117 {118 var f = { LayoutElement: layout, BFrame: undefined };119 foundContainer.All.push(f);120 foundContainer.ByIds[layout.Id] = f;121 if (foundContainer.LastTab)122 {123 if (foundContainer.ByTabs[foundContainer.LastTab.Id])124 foundContainer.ByTabs[foundContainer.LastTab.Id].push(f);125 else126 {127 foundContainer.ByTabs[foundContainer.LastTab.Id] = [];128 foundContainer.ByTabs[foundContainer.LastTab.Id].push(f);129 }130 }131 else132 {133 foundContainer.WoTabs.push(f);134 }135 }136 if (layout.Type == 'tab')137 {138 foundContainer.LastTab = layout;139 }140 for (var i = 0; i < layout.Children.length; i++)141 {142 var child = layout.Children[i];143 FindChildFramesRecursive(child, foundContainer);144 }145 }146 this.base_FrameDataLoaded = this.FrameDataLoaded;147 this.FrameDataLoaded = function (entityUsageId, attrsInSet, attrsByIds, vRows, templates, openMode)148 {149 this.base_FrameDataLoaded(entityUsageId, attrsInSet, attrsByIds, vRows, templates, openMode);150 this.OpenMode = openMode;151 if (vRows.length > 0)152 {153 vRows[0].OnPropertyChangedDelegate = new Delegate(this.OnPropertyChanged, this);154 this.CurrentEntity(vRows[0]);155 156 }157 this.Caption(this.GetFrameCaption());158 for (var i = 0; i < this.ChildFrames.WoTabs.length; i++)159 {160 RunChildFrame.call(this, this.ChildFrames.WoTabs[i]);161 }162 for (var i = 0; i < this.ChildFrames.All.length; i++)163 {164 if( this.ChildFrames.All[i].IsOpened)165 RunChildFrame.call(this, this.ChildFrames.All[i]);166 }167 var thumbs = $('[class="Thumb"]').children('img');168 for (var i = 0; i < thumbs.length; i++)169 {170 var href = $(thumbs[i]).attr('src');171 href = App.Utils.UpdateURLParameter(href, 'g', App.Utils.ShortGuid());172 $(thumbs[i]).attr('src', href);173 }174 175 };176 this.OnPropertyChanged = function (attr, value)177 {178 this.BusinessLayer.OnPropertyChanged(attr, value);179 }180 this.ExpressionValuesChanged = function (data)181 {182 if (this.CurrentEntity)183 {184 for (var i = 0; i < data.ExprResult.Attributes.length; i++)185 {186 var attr = data.ExprResult.Attributes[i];187 this.CurrentEntity()[attr.Id].Readonly(attr.ReadOnly);188 this.CurrentEntity()[attr.Id].Visible(attr.Visible);189 if (data.ExprResult.Values[attr.Id] && this.CurrentEntity()[attr.Id])190 {191 this.CurrentEntity()[attr.Id](data.ExprResult.Values[attr.Id]);192 }193 194 }195 for (var i = 0; i < data.ExprResult.FilteredRowSources.length; i++)196 {197 var rs = data.ExprResult.FilteredRowSources[i];198 var prop = this.CurrentEntity()[rs.OwnerAttributeId];199 prop.RsItems.removeAll()200 prop.RsItems.pushAll(rs.RowSourceData);201 var found = false;202 for (var k = 0; k < rs.RowSourceData.length; k++)203 {204 if (prop() == rs.RowSourceData[k].Value)205 {206 prop.SelectedRsItem(rs.RowSourceData[k]);207 prop(rs.RowSourceData[k].Value);208 found = true;209 }210 }211 if (found == false)212 {213 prop.SelectedRsItem({ Text: '', Value: null, ImageId: null });214 prop(null);215 }216 217 }218 219 }220 };221 this.GetLayoutTableRows = function (lElement, parent)222 {223 var rows = [];224 for (var i = 0; i < lElement.RowsCount; i++)225 {226 var rowObj = {227 LayoutElement: lElement,228 Height: ConvertToHtmlSize(lElement.RowsHeight, i),229 Columns: [],230 Index: i,231 }232 for (var k = 0; k < lElement.ColumnsCount; k++)233 {234 var colObj = {235 CssWidth: ConvertToHtmlSize(lElement.ColumnsHeight, k),236 ColumnWidth: ConvertColumnWidth(lElement.ColumnsHeight, i),237 Index: k,238 LayoutElement: lElement,239 RowObj: rowObj,240 }241 rowObj.Columns.push(colObj);242 }243 rows.push(rowObj);244 }245 return rows;246 };247 this.GetPanelTableRows = function (lElement, parent, openMode)248 {249 var rows = [];250 var rowsCount = lElement.RowsCount;251 if (!rowsCount || rowsCount == 0)252 rowsCount = 1;253 if (lElement.Children.length == 0)//panel with controls254 {255 var colsCount = lElement.ColumnsCount * 2;256 if (!colsCount || colsCount == 0)257 colsCount = 2;258 for (var i = 0; i < rowsCount; i++)//create rows and columns259 {260 var row = { Columns: [] };261 rows.push(row);262 for (var k = 0; k < colsCount; k++)263 {264 row.Columns.push({ ColumnType: 'empty' });265 }266 }267 var pnlAttrs = GetAttributesForPanel(this.EntityUsage, lElement.Id);268 var usedRows = 0;269 var usedCols = 0270 for (var i = 0; i < pnlAttrs.length; i++)271 {272 var attr = pnlAttrs[i];273 if (CheckIsNeedNewRow(usedCols, colsCount, attr))274 {275 usedRows++;276 usedCols = 0;277 AddRow(rows, colsCount);278 rowsCount++;279 }280 var labelCol = { ColumnType: 'label', Text: attr.Caption, IsRequired: IsLabelRequired(attr, openMode) };281 rows[usedRows].Columns[usedCols] = labelCol;282 usedCols++;283 var freeColsInRow = colsCount - usedCols;284 if (attr.ControlWidth && attr.ControlWidth > 0)//control with defined Control Width in attribute metadata285 {286 if (attr.ControlWidth > freeColsInRow)// 'ControlWidth' wider than we have in layput, just trim control to fit in layout287 {288 var controlCol = { ColumnType: 'control', Attr: attr, ColSpan: rows[usedRows].Columns.length - usedCols, ControlHeight: ConverToControlHeight(attr.ControlHeight) };289 rows[usedRows].Columns[usedCols] = controlCol;290 usedCols = colsCount;291 continue;292 }293 else// 'ControlWidth' fits in current row294 {295 var controlCol = { ColumnType: 'control', Attr: attr, ColSpan: attr.ControlWidth, ControlHeight: ConverToControlHeight(attr.ControlHeight) };296 rows[usedRows].Columns[usedCols] = controlCol;297 usedCols = usedCols + attr.ControlWidth;298 continue;299 }300 }301 else302 {303 var controlCol = { ColumnType: 'control', Attr: attr, ColSpan: 0, ControlHeight: ConverToControlHeight(attr.ControlHeight) };304 rows[usedRows].Columns[usedCols] = controlCol;305 usedCols++;306 continue;307 }308 }309 SetColumnsWidth(rows);310 //return rows;311 }312 else// panel with child layout : tabs, frames, etc.313 {314 var colsCount = lElement.ColumnsCount;315 if (!colsCount || colsCount == 0)316 colsCount = 2;317 for (var i = 0; i < rowsCount; i++)//create rows and columns318 {319 var row = { Columns: [] };320 rows.push(row);321 for (var k = 0; k < colsCount; k++)322 {323 row.Columns.push({ ColumnType: 'empty' });324 }325 }326 rows[0].Columns.push({ ColumnType: 'child_layout', Children: lElement.Children });327 }328 return rows;329 };330 function CheckIsNeedNewRow(usedCols, colsCount, attr)331 {332 if (!attr.ControlWidth && attr.ControlWidth == 0)333 {334 return colsCount - usedCols < 2;335 }336 else337 {338 return (colsCount - usedCols - 1) < attr.ControlWidth;339 }340 };341 function AddRow(rows, colsCount)342 {343 var row = { Columns: [] };344 rows.push(row);345 for (var k = 0; k < colsCount; k++)346 {347 row.Columns.push({ ColumnType: 'empty' });348 }349 };350 this.GetChildrenForColumn = function (lElement, rowIndex, colIndex)351 {352 var children = [];353 for (var i = 0; i < lElement.Children.length; i++)354 {355 var child = lElement.Children[i];356 if (child.Row == rowIndex && child.Column == colIndex)357 children.push(child);358 }359 return children;360 };361 362 var createdTabChilds = {};363 var tabsLevel = {};364 var tabsFlow = [];365 this.GetChildrenForTabControl = function (parent, forWhat)366 {367 if (parent.Type == "tab_control")368 {369 if (!tabsLevel[parent.Id])370 tabsLevel[parent.Id] = tabsFlow.push(parent);371 }372 var parentEl;373 if (parent.LayoutElement)374 parentEl = parent.LayoutElement;375 else376 parentEl = parent;377 if (createdTabChilds[parentEl.Id])378 return createdTabChilds[parentEl.Id];379 var tabs = [];380 parent.TabViews = [];381 for (var i = 0; i < parentEl.Children.length; i++)382 {383 var tab = parentEl.Children[i];384 var tabViewObj = {385 LayoutElement: tab,386 Selected: ko.observable(false),387 Type: tab.Type,388 RowsHeight: App.Utils.IsStringNullOrWhitespace(tab.RowsHeight) ? 'auto' : tab.RowsHeight + 'px',389 Parent: parent,390 TabLevel: tabsLevel[parent.Id]391 };392 tabs.push(tabViewObj);393 parent.TabViews.push(tabViewObj);394 }395 //TODO: get Selected Tab from settings396 var selectedFromSettings;// = Settings.GetSettings('al_frame_' + this.EntityUsage.Id, 'sel_tab');397 //if (!App.Utils.IsStringNullOrWhitespace(selectedFromSettings))398 //{399 // selectedFromSettings = JSON.parse(selectedFromSettings);400 //}401 if (tabs.length > 0 && App.Utils.IsStringNullOrWhitespace(selectedFromSettings))402 {403 tabs[0].Selected(true);404 var byTab = this.ChildFrames.ByTabs[tabs[0].LayoutElement.Id]405 if (byTab)406 {407 for (var i = 0; i < byTab.length; i++)408 {409 byTab[i].IsOpened = true;410 }411 }412 413 }414 if (tabs.length > 0 && !App.Utils.IsStringNullOrWhitespace(selectedFromSettings))415 {416 for (var i = 0; i < tabs.length; i++)417 {418 if (tabs[i].LayoutElement && tabs[i].LayoutElement.Id == selectedFromSettings)419 {420 tabs[i].Selected(true);421 var byTab = this.ChildFrames.ByTabs[tabs[i].LayoutElement.Id]422 if (byTab)423 {424 for (var k = 0; k < byTab.length; k++)425 {426 byTab[k].IsOpened = true;427 }428 }429 }430 }431 }432 createdTabChilds[parentEl.Id] = tabs;433 434 return tabs;435 }436 function ConvertToHtmlSize(layoutSize, index)437 {438 if (!App.Utils.IsStringNullOrWhitespace(layoutSize))439 {440 var lowerVal = layoutSize.replace(' ', '');441 var splitted = lowerVal.split(',');442 var result = index ? splitted[index] : splitted[0];443 if (result == 'auto')444 return 'auto';445 if (result == '*')446 return '100%';447 return result + 'px';448 }449 return "auto";450 }451 function ConvertColumnWidth(layoutSize, index)452 {453 if (!App.Utils.IsStringNullOrWhitespace(layoutSize))454 {455 var lowerVal = layoutSize.replace(' ', '');456 var splitted = lowerVal.split(',');457 var result = index ? splitted[index] : splitted[0];458 if (result == 'auto')459 return '';460 if (result == '*')461 return '100%';462 return result;463 }464 return '';465 }466 function ConverToControlHeight(layoutSize)467 {468 if (layoutSize)469 {470 if (layoutSize == 0)471 return 'auto';472 return layoutSize + 'px';473 }474 return 'auto';475 }476 this.TabClick = function (item, context)477 {478 if (item.Selected())479 return;480 for (var i = 0; i < item.Parent.TabViews.length; i++)481 {482 item.Parent.TabViews[i].Selected(false);483 }484 item.Selected(true);485 //Settings.AddChangedSettings('al_frame_' + this.EntityUsage.Id, 'sel_tab', item.LayoutElement.Id);486 for (var i = 0; i < context.ChildFrames.All.length; i++)487 {488 context.ChildFrames.All[i].IsOpened = false;489 }490 var childFrames = context.ChildFrames.ByTabs[item.LayoutElement.Id];491 if (childFrames && childFrames.length > 0)492 {493 494 for (var i = 0; i < childFrames.length; i++)495 {496 childFrames[i].IsOpened = true;497 var f = childFrames[i];498 if (!f.FrameHolder)499 {500 f = this.ChildFrames.ByIds[f.LayoutElement.Id];501 }502 RunChildFrame.call(this, f);503 }504 }505 };506 function GetAttributesForPanel(entityUsage, panelId)507 {508 var attributes = [];509 if (panelId.toUpperCase() == "PNDEFAULT")510 {511 for (var i = 0; i < entityUsage.EditableAttributes.length; i++)512 {513 var attr = entityUsage.Attributes[entityUsage.EditableAttributes[i]];514 if (App.Utils.IsStringNullOrWhitespace(attr.ControlPlacement) &&515 entityUsage.EditableAttributesById[attr.Id])516 {517 attributes.push(attr);518 }519 }520 }521 else522 {523 for (var i = 0; i < entityUsage.EditableAttributes.length; i++)524 {525 var attr = entityUsage.Attributes[entityUsage.EditableAttributes[i]];526 if (attr.ControlPlacement.toUpperCase() == panelId.toUpperCase() &&527 entityUsage.EditableAttributesById[attr.Id])528 {529 attributes.push(attr);530 }531 }532 }533 return attributes;534 };535 function IsLabelRequired(attributeMetadata, openMode)536 {537 if (!attributeMetadata.Nullable &&538 (openMode == NxOpenMode.Edit ||539 openMode == NxOpenMode.New ||540 openMode == NxOpenMode.ChildEdit ||541 openMode == NxOpenMode.ChildView))542 {543 return true;544 }545 return false;546 };547 function SetColumnsWidth(rows)548 {549 var maxControlsInRow = 1;550 for (var i = 0; i < rows.length; i++)551 {552 var row = rows[i];553 var controlsCount = 0;554 for (var k = 0; k < row.Columns.length; k++)555 {556 if (row.Columns[k].ColumnType == 'control')557 controlsCount++;558 }559 if (maxControlsInRow < controlsCount)560 maxControlsInRow = controlsCount;561 }562 var widthPercent = (100 / maxControlsInRow) + '%';563 for (var i = 0; i < rows.length; i++)564 {565 var row = rows[i];566 for (var k = 0; k < row.Columns.length; k++)567 {568 if (row.Columns[k].ColumnType == 'control')569 row.Columns[k].Width = widthPercent;570 }571 }572 };573 this.Resize = function ()574 {575 576 577 //var x = $('.FieldSet');578 //for (var i = 0; i < x.length; i++)579 //{580 // $(x[i]).width();581 // var maxContentHeight = 0;582 // var tabContent = $(x[i]).find('.TabContent');583 // for (var k = 0; k < tabContent.length; k++)584 // {585 // var he = $(tabContent[k]).height();586 // if (maxContentHeight < he)587 // maxContentHeight = he;588 // }589 // if (maxContentHeight > 0)590 // {591 // var oldH = $(x[i]).height();592 // if (oldH < maxContentHeight)593 // {594 // // $(x[i]).height(oldH + maxContentHeight);595 // }596 // }597 //}598 if (navigator.userAgent.toLowerCase().indexOf('firefox') > -1)599 {600 $('[id^=rs_arrow_]').css("margin-top", -12);601 602 }603 604 };605 this.GetControlTemplateName = function (attr, openMode, val)606 {607 var mode = 'edit_';608 if (openMode == NxOpenMode.ChildView || openMode == NxOpenMode.View ||609 ((openMode == NxOpenMode.Edit || openMode == NxOpenMode.ChildEdit) && attr.ReadOnlyForUpdate))610 var mode = 'view_';611 if (!App.Utils.IsStringNullOrWhitespace(attr.RowSourceId))612 {613 return 'form_' + mode + ControlsTemplatesIds.RowSourceComboBox;614 }615 else616 {617 var type = attr.Type;618 if (!App.Utils.IsStringNullOrWhitespace(attr.SlControl))619 type = attr.SlControl;620 var template = ControlsTemplatesIds[type];621 if (!template)622 template = ControlsTemplatesIds.string;623 return 'form_' + mode + template;624 }625 };626 this.SaveAndClose = function ()627 {628 // if (this.HasChanges())629 // {630 var errors = this.CurrentEntity().ValidateEntity();631 if (errors.length > 0)632 {633 ShowMessage(errors, 'Validation', [DialogButtons.OK, DialogButtons.Cancel], NxMessageBoxIcon.Warning);634 }635 else636 {637 this.BusinessLayer.SaveCurentEntity(this.CurrentEntity());638 }639 //}640 };641 this.HasChanges = function ()642 {643 if (this.OpenMode == NxOpenMode.New || this.OpenMode == NxOpenMode.ChildNew)644 return true;645 if (this.CurrentEntity && this.CurrentEntity() && this.CurrentEntity().HasChanges)646 {647 return true;648 }649 return false;650 };651 this.RevertChanges = function ()652 {653 if (this.CurrentEntity && this.CurrentEntity() && this.CurrentEntity().HasChanges)654 {655 this.CurrentEntity().RevertChanges();656 }657 };658 this.SaveChanges = function (doneDelegate)659 {660 661 662 if (this.CurrentEntity && this.CurrentEntity() /*&& this.CurrentEntity().HasChanges*/)663 {664 var errors = this.CurrentEntity().ValidateEntity();665 if (errors.length > 0)666 {667 ShowMessage(errors, 'Validation', [DialogButtons.OK, DialogButtons.Cancel], NxMessageBoxIcon.Warning);668 return;669 }670 this.BusinessLayer.SaveCurentEntity(this.CurrentEntity(), doneDelegate);671 }672 else673 {674 doneDelegate.Invoke();675 }676 };677 this.AllChangesSaved = function ()678 {679 this.CurrentEntity().HasChanges = false;680 this.IsNewEntity = false;681 if (this.OpenMode == NxOpenMode.New)682 this.OpenMode = NxOpenMode.Edit;683 if (this.OpenMode == NxOpenMode.ChildNew)684 this.OpenMode = NxOpenMode.ChildEdit;685 };686 this.AddChildFrame = function (frameLayoutElement, context)687 {688 context.ChildFrames.ByIds[frameLayoutElement.Id].FrameHolder = document.getElementById('child_frame_holder_' + context.TempId + frameLayoutElement.EntityUsageId);689 return App.Utils.ShortGuid();690 };691 this.GetDownloadlinkUrl = function (attrId, context)692 {693 return downloadUrl + '?entityUsageId=' +694 this.EntityUsage.Id + '&attributeId=' +695 attrId + '&pkVals=' + JSON.stringify(context.BusinessLayer.GetCurrentEntityPks()) + '&g=' + App.Utils.ShortGuid();696 }697 this.GetPhotoUrl = function (attrId, context, thumb)698 {699 return downloadPhotoUrl + '?entityUsageId=' +700 this.EntityUsage.Id + '&attributeId=' +701 attrId + '&pkVals=' + JSON.stringify(context.BusinessLayer.GetCurrentEntityPks() ) + '&thumb=' + thumb + '&g=' + App.Utils.ShortGuid();702 }703 this.OnThumbClick = function (attrId, context)704 {705 window.open(showImageUrl + "?imageUrl=" + encodeURIComponent( context.GetPhotoUrl(attrId, context, false)) , "_blank");706 }707 this.Base_Dispose = this.Dispose;708 this.Dispose = function ()709 {710 this.Base_Dispose();711 for (var i = 0; i < this.ChildFrames.All.length; i++)712 {713 var child = this.ChildFrames.All[i];714 if (child.FrameHolder)715 ko.cleanNode(child.FrameHolder);716 if (child.BFrame && child.BFrame.ViewLayer && child.BFrame.ViewLayer.Dispose)717 child.BFrame.ViewLayer.Dispose();718 719 }720 };721 this.Refresh = function ()722 {723 this.BusinessLayer.Refresh();724 };725 this.GetSelectedTabClassName = function(frame)726 {727 if (frame.OpenMode.indexOf('Child') == -1)728 return 'TabGripSelected';729 else730 return 'TabGripSelected_Child';731 }732 this.GetChildFrame = function (entityUsageId)733 {734 for (var i = 0; i < this.ChildFrames.All.length; i++)735 {736 if (this.ChildFrames.All[i].BFrame && this.ChildFrames.All[i].BFrame.EntityMetadataId == entityUsageId)737 return this.ChildFrames.All[i].BFrame;738 }739 740 };741 this.DymmicCommandClick = function (item, attr)742 {743 this.BusinessLayer.DymmicCommandClick(item, attr);744 }745};746extend(VAutoLayoutFrame, VBaseFrame);747function VAutoLayoutFrame_ForBusiness()748{749 VBaseFrame_ForBusiness.call(this);750 this.CreateLayout = function (layout) { };751 this.AllChangesSaved = function (layout) { };752 this.GetChildFrame = function (entityUsageId) { };...
interframe.js
Source:interframe.js
1/* ==============================================================================2 * Interframe v1.0.03 * Copyright (c) 2011-Present Vagaro, Inc4 * ============================================================================== */56+function (w, d) {7 'use strict';89 if (typeof (w.$Interframe) !== 'undefined') {10 return;11 }1213 var err = new Error('Interframe requires jQuery version 1.9.1 or higher, but lower than version 3.'),14 $ = typeof jQuery === 'undefined' ? undefined : jQuery;15 if (typeof $ === 'undefined') {16 throw err;17 }18 var ver = $.fn.jquery.split(' ')[0].split('.');19 if ((ver[0] < 2 && ver[1] < 9) || (ver[0] == 1 && ver[1] == 9 && ver[2] < 1) || (ver[0] > 2)) {20 throw err;21 }2223 var pollingInterval = 500,24 FBPollingInterval = 250, isFBParent = undefined,25 isChrome = /Chrome/.test(navigator.userAgent), isSafari = isChrome === false && /Safari/.test(navigator.userAgent), isFirefox = /firefox/i.test(navigator.userAgent),26 debug = 0, isIniting = false, isRegistered = false,27 getOrigin = function (src) {28 var match = /^(https?:\/\/[^\/]*).*$/i.exec(src);29 return match ? match[1] : '*';30 },31 myParent = (w.parent != w && d.referrer != null) ? w.parent : null, parentOrigin = '*',32 childFrames = [],33 addChild = function (window, origin) {34 var children = $('iframe');35 for (var i = children.length - 1; i >= 0; --i) {36 if (children[i].contentWindow === window) {37 for (var j = childFrames.length - 1; j >= 0; --j) {38 if (childFrames[j].window === window) {39 childFrames.splice(j, 1);40 }41 }42 childFrames.push({ window: window, origin: origin, frame: children[i] });43 return childFrames[childFrames.length - 1];44 }45 }46 return null;47 },48 findChild = function (window, origin) {49 for (var i = childFrames.length - 1; i >= 0; --i) {50 if (childFrames[i].window === window && childFrames[i].origin === origin) {51 return childFrames[i];52 }53 }54 return null;55 },56 autoSize = true, sizeRequestThreshold = 5, sizeUpdateRequestQ = [], sizeUpdatingQ = [], curHeight = 0, curMinHeight = Number.MIN_VALUE, curMaxHeight = Number.MAX_VALUE,57 viewport2Window = 0, viewportHeight = $(w).height(), viewportWidth = $(w).width(),58 element2String = function (element) {59 return '<' + element.localName + ' id="' + element.id + '" class="' + element.className + '">';60 },61 log = (typeof console !== 'object' || typeof console.log !== 'function') ? function() {} : function (level, data) {62 typeof level === 'number' && debug >= level && console.log('[' + w.location.href.replace(/#.*$/, '') + ']\n' + data);63 },64 postMsg = function (target, origin, msg) {65 if (typeof target === 'object' && target !== null) {66 var msgJSON = JSON.stringify(typeof msg === 'object' ? msg : {});67 log(3, 'Send ' + msgJSON + ' to ' + origin);68 target.postMessage(msgJSON, origin);69 }70 },71 returnMsg = function (evt, msg) {72 postMsg(evt.originalEvent.source, evt.originalEvent.origin, msg);73 },74 getDocHeight = function () {75 return isChrome ? $('html')[0].scrollHeight : isFirefox ? $('body')[0].scrollHeight : isSafari ? $('html')[0].scrollHeight : $('body')[0].scrollHeight;76 },77 getFBInfo = function () {78 if (typeof w.FB === 'object') {79 if (typeof isFBParent === 'undefined') {80 isFBParent = null;81 setTimeout(function () {82 if (isFBParent === null) {83 isFBParent = false;84 }85 }, 5000);86 }87 if (isFBParent === null || isFBParent) {88 FB.Canvas.getPageInfo(function (page) {89 if (isFBParent === null) {90 isFBParent = true;91 isRegistered = true;92 myParent = null;93 $('html,body').css('height', 'auto');94 log(0, 'Facebook canvas detected');95 setInterval(getFBInfo, FBPollingInterval);96 }97 postMsg(w, w.location.origin, { object: 'updateViewport2Window', top: page.scrollTop - page.offsetTop, height: page.clientHeight, width: page.clientWidth });98 });99 }100 }101 },102 requestSizeUpdate = function (height, callback) {103 isRegistered === false && getFBInfo();104105 var orgH = getDocHeight();106 if (typeof height === 'undefined') {107 height = orgH;108 if (Math.abs(curHeight - height) < sizeRequestThreshold || (Math.abs(curHeight - curMinHeight) < sizeRequestThreshold && height + sizeRequestThreshold < curMinHeight) || (Math.abs(curHeight - curMaxHeight) < sizeRequestThreshold && height - sizeRequestThreshold > curMaxHeight)) {109 typeof callback === 'function' && callback(height, orgH);110 return;111 }112 }113114 if (isRegistered === false) {115 typeof callback === 'function' && callback(height, orgH);116 return;117 }118119 var evt = $.Event('changing.interframe', { height: height });120 $(w).trigger(evt);121 if (evt.isDefaultPrevented()) {122 typeof callback === 'function' && callback(height, orgH);123 return;124 }125126 if (isFBParent) {127 FB.Canvas.setSize({ height: height });128 log(1, 'FB.Canvas.setSize({ height: ' + height + ' })');129 typeof callback === 'function' && callback(height, orgH);130 setTimeout(function () {131 postMsg(w, w.location.origin, { object: 'updateSize', reqHeight: height, actHeight: height, orgHeight: orgH });132 }, 100);133 } else {134 sizeUpdateRequestQ.push({ height: height, callback: callback });135 if (sizeUpdatingQ.length === 0 && sizeUpdateRequestQ.length > 0) {136 var req = sizeUpdateRequestQ.shift();137 sizeUpdatingQ.push(req.callback);138 while (sizeUpdateRequestQ.length > 0) {139 if (sizeUpdateRequestQ[0].height === req.height) {140 sizeUpdatingQ.push(sizeUpdateRequestQ.shift().callback);141 } else {142 break;143 }144 }145 postMsg(myParent, parentOrigin, { object: 'requestSize', height: req.height });146 }147 }148 };149150 w.$Interframe = {151 inspect: function () {152 return {153 mutationObserver: (w.MutationObserver || w.WebKitMutationObserver || undefined) ? true : false,154 pollingInterval: pollingInterval,155 userAgent: navigator.userAgent,156 isChrome: isChrome,157 isSafari: isSafari,158 isFirefox: isFirefox,159 debug: debug,160 isIniting: isIniting,161 isRegistered: isRegistered,162 isFBParent: isFBParent,163 FBPollingInterval: FBPollingInterval,164 myParent: myParent,165 parentOrigin: parentOrigin,166 childFrames: childFrames,167 autoSize: autoSize,168 sizeRequestThreshold: sizeRequestThreshold,169 sizeUpdateRequestQ: sizeUpdateRequestQ,170 sizeUpdatingQ: sizeUpdatingQ,171 curHeight: curHeight,172 curMinHeight: curMinHeight,173 curMaxHeight: curMaxHeight,174 viewport2Window: viewport2Window,175 viewportTop: viewport2Window + $(w).scrollTop(),176 viewportHeight: viewportHeight,177 viewportWidth: viewportWidth,178 setPollingInterval: function (interval) {179 if (typeof interval === 'number' && interval > 100) {180 pollingInterval = interval;181 }182 return pollingInterval;183 },184 setFBPollingInterval: function (interval) {185 if (typeof interval === 'number' && interval > 100) {186 FBPollingInterval = interval;187 }188 return FBPollingInterval;189 },190 setDebug: function (level) {191 if (typeof level === 'number') {192 debug = Math.min(Math.max(level, 0), 3);193 }194 return debug;195 }196 };197 },198199 getJQuery: function () {200 return $;201 },202203 init: function (enableAutoSize, debugLevel) {204 if (isIniting) {205 log(2, '$Interframe.init() skipped.');206 return;207 }208 log(2, '$Interframe.init() started.');209 isIniting = true;210 if (typeof enableAutoSize === 'boolean') {211 autoSize = enableAutoSize;212 }213 if (typeof debugLevel === 'number') {214 debug = debugLevel;215 }216217 var msgHandlers = {218 // Receives registration invitation from my parent.219 // Sends registration request.220 'register?': function (evt, msg) {221 if (parentOrigin !== '*') {222 log(0, 'Received "register?".');223 } else {224 log(0, 'Received "register?". Send "register".')225 returnMsg(evt, { object: 'register' });226 }227 },228229 // Receives registration request from a child.230 // Acknowledges the child OK to register.231 'register': function (evt, msg) {232 log(0, 'Received "register". Send "registerACK".')233 returnMsg(evt, { object: 'registerACK' });234 },235236 // Receives registration acknowledgement from my parent.237 // Records the parent information.238 'registerACK': function (evt, msg) {239 if (parentOrigin !== '*') {240 log(0, 'Received "registerACK".');241 } else {242 log(0, 'Received "registerACK". Send "registerDone".')243 parentOrigin = evt.originalEvent.origin;244 returnMsg(evt, { object: 'registerDone' });245 }246 },247248 // Receives registration done from a child.249 // Records the child information.250 // It is now OK to send messages to the child.251 'registerDone': function (evt, msg) {252 log(0, 'Received "registerDone". Send "registerDoneACK".')253 var child = addChild(evt.originalEvent.source, evt.originalEvent.origin);254 returnMsg(evt, { object: 'registerDoneACK' });255 var viewport = w.$Interframe.getViewport2Doc();256 (myParent === null || isRegistered) && postMsg(child.window, child.origin, { object: 'updateViewport2Window', top: viewport.top - $(child.frame).offset().top, height: viewport.height, width: viewport.width });257 },258259 // Receives registration done from my parent.260 // It is now OK to send messages to my parent.261 'registerDoneACK': function (evt, msg) {262 log(0, 'Received "registerDoneACK".')263 isRegistered = true;264 $('html,body').css('height', 'auto');265 $(w).trigger($.Event('registered.interframe'));266 },267268 // Receives resize request from a child.269 // 1. Changes the iframe size; and270 // 2a. Notifies my parent to change my size; or271 // 2b. Notifies my children viewport change.272 'requestSize': function (evt, msg) {273 var child = findChild(evt.originalEvent.source, evt.originalEvent.origin);274 if (child !== null) {275 var orgH = $(child.frame).height(),276 reqH = isNaN(msg.height) ? orgH : msg.height,277 maxH = parseFloat($(child.frame).css('max-height')),278 minH = parseFloat($(child.frame).css('min-height')),279 actH = Math.max(Math.min(isNaN(maxH) ? reqH : maxH, reqH), isNaN(minH) ? reqH : minH);280 log(1, 'Received "requestSize". orgH=' + orgH + ' reqH=' + reqH + ' actH=' + actH + ' minH=' + minH + ' maxH=' + maxH);281 $(child.frame).attr('height', actH).attr('scrolling', (actH >= reqH) ? 'no' : 'auto').css('overflow', (actH >= reqH)? 'none' : 'auto');282 postMsg(child.window, child.origin, { object: 'updateSize', reqHeight: reqH, actHeight: actH, orgHeight: orgH, minHeight: minH, maxHeight: maxH });283 if (myParent || isFBParent) {284 requestSizeUpdate($(w).height() + actH - orgH);285 } else {286 var viewport = w.$Interframe.getViewport2Doc();287 $.each(childFrames, function () {288 postMsg(this.window, this.origin, { object: 'updateViewport2Window', top: viewport.top - $(this.frame).offset().top, height: viewport.height, width: viewport.width });289 });290 }291 }292 },293294 // Receives resize response from my parent.295 // Executes callbacks.296 'updateSize': function (evt, msg) {297 curHeight = msg.actHeight;298 typeof msg.minHeight !== 'undefined' && (curMinHeight = msg.minHeight);299 typeof msg.maxHeight !== 'undefined' && (curMaxHeight = msg.maxHeight);300 log(1, 'Received "updateSize". curHeight=' + curHeight + ' curMinHeight=' + curMinHeight + ' curMaxHeight=' + curMaxHeight);301 $.each(sizeUpdatingQ, function () {302 typeof this === 'function' && this(msg.reqHeight, msg.actHeight, msg.minHeight, msg.maxHeight);303 });304 sizeUpdatingQ = [];305 $(w).trigger($.Event('changed.interframe', { reqHeight: msg.reqHeight, actHeight: msg.actHeight, minHeight: msg.minHeight, maxHeight: msg.maxHeight }));306 setTimeout(requestSizeUpdate, pollingInterval);307 },308309 // Receives size check from my parent.310 // Sends request size.311 'checkSize': function (evt, msg) {312 log(1, 'Received "checkSize".');313 curHeight = 0;314 requestSizeUpdate();315 },316317 // Receives viewport change from my parent.318 // Notifies my children viewport change.319 'updateViewport2Window': function (evt, msg) {320 viewport2Window = msg.top;321 viewportHeight = msg.height;322 viewportWidth = msg.width;323 log(1, 'Received "updateViewport2Window". viewport2Window=' + viewport2Window + ' viewportHeight=' + viewportHeight + ' viewportWidth=' + viewportWidth);324 var viewport = w.$Interframe.getViewport2Doc();325 $(w).trigger($.Event('viewport.interframe', { top: viewport.top, height: viewport.height }))326 $.each(childFrames, function () {327 postMsg(this.window, this.origin, { object: 'updateViewport2Window', top: viewport.top - $(this.frame).offset().top, height: viewport.height, width: viewport.width });328 });329 },330 };331332 $(w).on('message', function (evt) {333 try {334 log(3, 'Received: "' + evt.originalEvent.data + '"');335 var msg = JSON.parse(evt.originalEvent.data);336 if (msg.hasOwnProperty('object')) {337 if (msg.object.indexOf('register') >= 0 || (evt.originalEvent.origin === parentOrigin && isRegistered) || evt.originalEvent.source === w ) {338 msgHandlers[msg.object](evt, msg);339 return;340 } else {341 if (findChild(evt.originalEvent.source, evt.originalEvent.origin) !== null) {342 msgHandlers[msg.object](evt, msg);343 return;344 }345 }346 }347 log(1, 'Ignored: "' + evt.originalEvent.data + '" from ' + evt.originalEvent.origin);348 } catch (err) {349 log(0, 'Error processing "' + evt.originalEvent.data, '": ' + err.message);350 return;351 }352 });353354 // Register with my parent.355 if (w.parent != w && typeof d.referrer === 'string' && d.referrer.length > 0) {356 postMsg(w.parent, parentOrigin, { object: 'register' });357 }358359 // Invites child frames to register.360 $('iframe').each(function () {361 postMsg(this.contentWindow, '*', { object: 'register?' });362 });363364 // Monitors change in body size and scroll events.365 $(w).on('resize', function () {366 if (myParent === null && isFBParent !== true) {367 viewportHeight = $(w).height();368 viewportWidth = $(w).width();369 }370 var viewport = w.$Interframe.getViewport2Doc();371 $.each(childFrames, function () {372 postMsg(this.window, this.origin, { object: 'updateViewport2Window', top: viewport.top - $(this.frame).offset().top, height: viewport.height, width: viewport.width });373 });374 }).on('scroll', function () {375 var viewport = w.$Interframe.getViewport2Doc();376 $.each(childFrames, function () {377 postMsg(this.window, this.origin, { object: 'updateViewport2Window', top: viewport.top - $(this.frame).offset().top, height: viewport.height, width: viewport.width });378 });379 });380381 var MutationObserver = w.MutationObserver || w.WebKitMutationObserver;382 if (typeof MutationObserver === 'undefined') {383 setInterval(function () {384 autoSize && requestSizeUpdate();385 }, pollingInterval);386 } else {387 new MutationObserver(function (mutations) {388 autoSize && requestSizeUpdate();389 }).observe(d.body, {390 attributes: true,391 childList: true,392 characterData: true,393 subtree: true394 });395 }396397 log(2, '$Interframe.init() done.');398 $(w).trigger($.Event('init.interframe'));399 },400 401 // Gets the browser window position w.r.t the frame's window coordinates.402 getViewport2Window: function () {403 var visibleTop = Math.max(viewport2Window, 0),404 visibleBottom = Math.min(viewport2Window + viewportHeight, $(w).height()),405 ret = {406 top: viewport2Window,407 height: viewportHeight,408 width: viewportWidth,409 visibleTop: visibleTop,410 visibleHeight: Math.max(visibleBottom - visibleTop, 0)411 };412 log(2, '$Interframe.getViewport2Window() = ' + JSON.stringify(ret));413 return ret;414 },415416 // Gets the browser window position w.r.t the frame's document coordinates.417 getViewport2Doc: function () {418 var V2W = w.$Interframe.getViewport2Window(),419 ret = {420 top: V2W.top + $(w).scrollTop(),421 height: V2W.height,422 width: V2W.width,423 visibleTop: V2W.visibleTop + $(w).scrollTop(),424 visibleHeight: V2W.visibleHeight425 };426 log(2, '$Interframe.getViewport2Doc() = ' + JSON.stringify(ret));427 return ret;428 },429430 // Gets the browser window position w.r.t. the element's coordinates.431 getViewport2Element: function (element) {432 element = $(element);433 var ret;434 if (element.length > 0) {435 var ret = {};436 if (element[0] === $(d)[0] || element[0] === $('html')[0]) {437 ret = w.$Interframe.getViewport2Doc();438 } else if (element[0] === $(w)[0]) {439 ret = w.$Interframe.getViewport2Window();440 } else {441 var oldDisplay = element.css('display'), oldVisibility = element.css('visibility');442 oldDisplay === 'none' && element.css('visibility', 'hidden').css('display', 'block');443 var V2D = w.$Interframe.getViewport2Doc(),444 visibleTop = Math.max(V2D.top - element.offset().top, 0) + element.scrollTop(),445 visibleBottom = Math.min(V2D.top - element.offset().top + V2D.height, element.height()) + element.scrollTop(),446 ret = {447 top: V2D.top - element.offset().top + element.scrollTop(),448 height: V2D.height,449 width: V2D.width,450 visibleTop: visibleTop,451 visibleHeight: Math.max(visibleBottom - visibleTop, 0)452 };453 element.css('display', oldDisplay).css('visibility', (oldVisibility === 'visible') ? '' : oldVisibility);454 }455 } else {456 ret = w.$Interframe.getViewport2Doc();457 }458 log(2, '$Interframe.getViewport2Element(' + element2String(element[0]) + ') = ' + JSON.stringify(ret));459 return ret;460 },461462 centerPopup: function (popup, height) {463 popup = $(popup);464 if (popup.length > 0) {465 var oldDisplay = popup.css('display'), oldVisibility = popup.css('visibility');466 oldDisplay === 'none' && popup.css('visibility', 'hidden').css('display', 'block');467 height = typeof height === 'number' ? height : popup.outerHeight();468 switch (popup.css('position')) {469 case 'fixed':470 var V2W = w.$Interframe.getViewport2Window(),471 top = V2W.visibleTop + Math.max((V2W.visibleHeight - height) / 2, 0);472 V2W.visibleHeight > 0 && popup.css('top', top + 'px').css('bottom', $(w).height() - top - height + 'px').css('margin-top', '0px').css('margin-bottom', '0px');473 break;474 case 'absolute':475 var parent = popup.parent();476 while (true) {477 if (parent.css('position') !== 'static') {478 break;479 } else if (parent[0] === $('html')[0]) {480 break;481 } else {482 parent = parent.parent();483 }484 }485 var V2P = w.$Interframe.getViewport2Element(parent[0]),486 top = V2P.visibleTop + Math.max((V2P.visibleHeight - height) / 2, 0);487 V2P.visibleHeight > 0 && popup.css('top', top + 'px').css('bottom', parent.scrollHeight - top - height + 'px').css('margin-top', '0px').css('margin-bottom', '0px');488 break;489 case 'relative':490 var parent = popup.parent(),491 V2P = w.$Interframe.getViewport2Element(parent[0]),492 top = V2P.visibleTop + Math.max((V2P.visibleHeight - height) / 2, 0);493 V2P.visibleHeight > 0 && popup.css('margin-top', top + 'px').css('margin-bottom', parent.scrollHeight - top - height + 'px').css('top', '0px').css('bottom', '0px');494 break;495 case 'static':496 var parent = popup.parent(),497 V2P = w.$Interframe.getViewport2Element(parent[0]),498 top = V2P.visibleTop + Math.max((V2P.visibleHeight - height) / 2, 0);499 V2P.visibleHeight > 0 && popup.css('margin-top', top + 'px').css('margin-bottom', parent.scrollHeight - top - height + 'px');500 break;501 default:502 break;503 }504 popup.css('display', oldDisplay).css('visibility', (oldVisibility === 'visible') ? '' : oldVisibility);505 log(2, '$Interframe.centerPopup(' + element2String(popup[0]) + ', ' + height + ')');506 }507 },508509 autoSize: function (enable) {510 autoSize = (enable) ? true : false;511 if (autoSize === false) {512 sizeUpdateRequestQ = [];513 }514 log(2, '$Interframe.autoSize(' + enable + ')');515 },516517 setSize: function (height) {518 requestSizeUpdate(height);519 log(2, '$Interframe.setSize(' + height + ')');520 },521522 checkSize: function () {523 $.each(childFrames, function () {524 postMsg(this.window, this.origin, { object: 'checkSize' });525 });526 log(2, '$Interframe.checkSize()');527 }528 };529530 $(w).on('load', function (evt) {531 w.$Interframe.init();532 });533}(window, document);
...
flamegraph.js
Source:flamegraph.js
1/* This Source Code Form is subject to the terms of the Mozilla Public2 * License, v. 2.0. If a copy of the MPL was not distributed with this3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */4function addFramesToFrame(currentFrame, frameNames, samples) {5 currentFrame.samples += samples;6 if (frameNames.length > 0) {7 const frameName = frameNames[0];8 if (!currentFrame.childFrames.has(frameName)) {9 currentFrame.childFrames.set(frameName, {10 name : frameName,11 samples : 0,12 childFrames: new Map(),13 depth : currentFrame.depth + 114 });15 }16 frameNames.shift();17 addFramesToFrame(currentFrame.childFrames.get(frameName), frameNames, samples);18 }19}20function parseFrames(log) {21 const lines = log.split('\n');22 23 const rootFrame = {24 name : 'all',25 samples : 0,26 childFrames: new Map(),27 depth : 028 };29 for (let i = 0; i < lines.length; i++) {30 const line = lines[i].trim();31 if (line) {32 const frames = lines[i].split(';');33 const spaceIndex = frames[frames.length - 1].lastIndexOf(' ');34 if (spaceIndex > 0) {35 const endFrame = frames[frames.length - 1];36 const samples = parseInt(endFrame.substring(spaceIndex + 1));37 frames[frames.length - 1] = endFrame.substring(0, spaceIndex);38 39 addFramesToFrame(rootFrame, frames, samples);40 }41 }42 }43 44 return rootFrame;45}46function createIdGenerator() {47 return {48 id: -1,49 generate() {50 this.id += 1;51 return this.id;52 }53 }54}55function enrichFrame(currentFrame, idGenerator, parentId) {56 if (!idGenerator) {57 idGenerator = createIdGenerator();58 }59 currentFrame.id = idGenerator.generate();60 currentFrame.selfSamples = currentFrame.samples;61 if (parentId || parentId === 0) {62 currentFrame.parentId = parentId;63 }64 if (!currentFrame.childFrames) {65 return;66 }67 let maxDepth = currentFrame.depth;68 currentFrame.childFrames.forEach(childFrame => {69 currentFrame.selfSamples -= childFrame.samples;70 const maxDepthInChild = enrichFrame(childFrame, idGenerator, currentFrame.id);71 if (maxDepth < maxDepthInChild) {72 maxDepth = maxDepthInChild;73 }74 });75 76 currentFrame.maxDepth = maxDepth;77 return maxDepth;78}79function visitFrames(currentFrame, callback, parentFrame) {80 callback(currentFrame, parentFrame);81 if (!currentFrame.childFrames) {82 return;83 }84 currentFrame.childFrames.forEach(childFrame => {85 visitFrames(childFrame, callback, currentFrame);86 });87}88function sortFrames(currentFrame) {89 if (!currentFrame || !currentFrame.childFrames) {90 return;91 }92 currentFrame.childFrames = new Map([...currentFrame.childFrames.entries()].sort());93 currentFrame.childFrames.forEach(childFrame => sortFrames(childFrame));94}95export function parseProfilingLog(log) {96 const rootFrame = parseFrames(log);97 sortFrames(rootFrame);98 enrichFrame(rootFrame);99 return rootFrame;100}101function copyChildFrames(srcFrame, dstFrame) {102 srcFrame.childFrames.forEach((childFrame, childFrameName) => {103 const dstChild = {104 name : childFrame.name,105 childFrames: new Map(),106 samples : childFrame.samples,107 selfSamples: childFrame.selfSamples,108 depth : childFrame.depth109 };110 dstFrame.childFrames.set(childFrameName, dstChild);111 copyChildFrames(childFrame, dstChild);112 });113}114class FrameData {115 constructor(rootFrame, rects, framesMap) {116 this.rootFrame = rootFrame;117 this.rects = rects;118 this.framesMap = framesMap;119 }120 toJSONObject() {121 const _traverse = (frame) => {122 const jsonFrame = {123 childFrames: {},124 samples: frame.samples,125 selfSamples: frame.selfSamples,126 };127 if (frame.mark) {128 jsonFrame.mark = frame.mark;129 }130 frame.childFrames.forEach((childFrame, childFrameName) => {131 jsonFrame.childFrames[childFrameName] = _traverse(childFrame);132 });133 return jsonFrame;134 };135 return {136 frame: _traverse(this.rootFrame)137 };138 }139 clone() {140 const newRoot = {141 name : this.rootFrame.name,142 childFrames: new Map(),143 samples : this.rootFrame.samples,144 selfSamples: this.rootFrame.selfSamples,145 depth : this.rootFrame.depth146 };147 copyChildFrames(this.rootFrame, newRoot);148 enrichFrame(newRoot);149 return generateFrameData(newRoot);150 }151 collectStackTrace(stackId) {152 if (!stackId) {153 return '';154 }155 const frame = this.framesMap[stackId];156 if (frame) {157 return frame.name +'\n' + this.collectStackTrace(frame.parentId);158 }159 return '';160 }161 findFrameById(id) {162 return this.framesMap[id];163 }164 findRectByIndex(idx) {165 if (0 <= idx && idx < this.rects.length) {166 return this.rects[idx];167 }168 return null;169 }170 findRectForFrame(frame) {171 if (!frame) {172 return null;173 }174 return this.findRectByIndex(frame.rectIndex);175 }176 traverseRectAncestors(rect, callback) {177 const parentFrame = this.findFrameById(rect.parentId);178 if (!parentFrame) {179 return;180 }181 const parentRect = this.findRectByIndex(parentFrame.rectIndex);182 if (!parentRect) {183 return;184 }185 callback(parentRect);186 this.traverseRectAncestors(parentRect, callback);187 }188 189 /**190 * Traverses tree of frames starting at the root191 * @param {Function} callback 192 */193 traverseFrames(callback) {194 this._traverseFrames(this.rootFrame, null, callback);195 }196 _traverseFrames(frame, parentFrame, callback) {197 callback(frame, parentFrame);198 frame.childFrames.forEach(childFrame => {199 this._traverseFrames(childFrame, frame, callback);200 });201 }202 traverseFramesStartingFrom(frame, callback) {203 this._traverseFrames(frame, null, callback);204 }205 /**206 * Tries to find all frames of the same length with the largest depth.207 * It assumes that during collection of stack-traces their depth was limited,208 * so in the resulting report they would all end up with the same max depth.209 * Once it finds those frames it will trie to repair frame by frame210 */211 repairBrokenFrames() {212 const brokenFrameNames = [];213 let maxBrokenDepth = 0;214 this.rootFrame.childFrames.forEach((frame, frameName) => {215 if (maxBrokenDepth < frame.maxDepth) {216 maxBrokenDepth = frame.maxDepth;217 brokenFrameNames.length = 0;218 brokenFrameNames.push(frameName);219 } else if (maxBrokenDepth === frame.maxDepth) {220 brokenFrameNames.push(frameName);221 }222 });223 for(let i = 0; i < brokenFrameNames.length; i++) {224 const frame = this.rootFrame.childFrames.get(brokenFrameNames[i]);225 this.repairFrame(frame);226 }227 }228 /**229 * Tries to find the frame with the same name that is further away and merge the specified frame at that point230 * @param {*} frameForRepair231 */232 repairFrame(frameForRepair) {233 // doing bredth search first, since we are trying to find a frame that is a bit further away.234 const queue = [this.rootFrame];235 let frameForMerge = null;236 while(queue.length > 0 && !frameForMerge) {237 const frame = queue.shift();238 frame.childFrames.forEach(childFrame => {239 if (childFrame.id !== frameForRepair.id) {240 queue.push(childFrame);241 }242 });243 if (frame.name === frameForRepair.name && frame.id !== frameForRepair.id && frame.depth > frameForRepair.depth) {244 frameForMerge = frame;245 }246 }247 if (!frameForMerge) {248 return;249 }250 if (frameForMerge.id !== frameForRepair.id) {251 const parentFrame = this.findParentFrameForFrame(frameForRepair);252 parentFrame.childFrames.delete(frameForRepair.name);253 this.mergeFrames(frameForMerge, frameForRepair);254 // walking up the frames in order to update all ancestor samples255 this.traverseAncestorFramesUntil(frameForMerge, 256 frame => {frame.samples += frameForRepair.samples},257 frame => frame.id !== parentFrame.id258 );259 }260 enrichFrame(this.rootFrame);261 const newFrameData = generateFrameData(this.rootFrame);262 this.rootFrame = newFrameData.rootFrame;263 this.rects = newFrameData.rects;264 this.framesMap = newFrameData.framesMap;265 }266 traverseAncestorFramesUntil(frame, callback, conditionCallback) {267 const parentFrame = this.findParentFrameForFrame(frame);268 if (!parentFrame) {269 return;270 }271 if (conditionCallback(parentFrame)) {272 callback(parentFrame);273 this.traverseAncestorFramesUntil(parentFrame, callback, conditionCallback);274 }275 }276 findParentFrameForFrame(frame) {277 return this.findFrameById(frame.parentId);278 }279 /**280 * Merges srcFrame into dstFrame281 * @param {*} dstFrame 282 * @param {*} srcFrame 283 */284 mergeFrames(dstFrame, srcFrame) {285 dstFrame.samples += srcFrame.samples;286 srcFrame.childFrames.forEach(childSrcFrame => {287 if (dstFrame.childFrames.has(childSrcFrame.name)) {288 this.mergeFrames(dstFrame.childFrames.get(childSrcFrame.name), childSrcFrame);289 } else {290 this.appendNewChildFrame(dstFrame, childSrcFrame);291 }292 });293 }294 appendNewChildFrame(frame, childFrame) {295 const newChildFrame = {296 name: childFrame.name,297 samples: childFrame.samples,298 childFrames: new Map(),299 depth : frame.depth + 1300 };301 frame.childFrames.set(childFrame.name, newChildFrame);302 childFrame.childFrames.forEach(childChildFrame => {303 this.appendNewChildFrame(newChildFrame, childChildFrame);304 });305 }306 compareWith(otherRootFrame) {307 this._compareWith(this.rootFrame, otherRootFrame, this.rootFrame.samples, otherRootFrame.samples);308 }309 _compareWith(frame, otherFrame, totalSamples, otherTotalSamples) {310 if (otherFrame) {311 const ratio = frame.samples / totalSamples;312 frame.otherRatio = otherFrame.samples / otherTotalSamples;313 frame.diffRatio = (frame.otherRatio - ratio) / ratio;314 frame.otherSamples = otherFrame.samples;315 frame.otherSelfSamples = otherFrame.selfSamples;316 } else {317 frame.diffRatio = -1.0;318 frame.otherRatio = 0.0;319 frame.otherSamples = 0;320 frame.otherSelfSamples = 0;321 }322 frame.childFrames.forEach((childFrame, childFrameName) => {323 const otherChild = otherFrame ? otherFrame.childFrames.get(childFrameName) : null;324 this._compareWith(childFrame, otherChild, totalSamples, otherTotalSamples);325 });326 }327}328export function generateFrameData(currentFrame) {329 const rects = [];330 const framesMap = {};331 const maxSamples = currentFrame.samples;332 visitFrames(currentFrame, (frame, parentFrame) => {333 framesMap[frame.id] = frame;334 frame.childOffset = frame.selfSamples/maxSamples;335 let offset = 0;336 if (parentFrame) {337 offset = parentFrame.childOffset + parentFrame.x;338 parentFrame.childOffset += frame.samples/maxSamples;339 }340 const rect = {341 name : frame.name,342 samples : frame.samples,343 id : frame.id,344 parentId: parentFrame ? parentFrame.id: null,345 w : frame.samples/maxSamples,346 x : offset,347 d : frame.depth,348 };349 frame.x = offset;350 frame.rectIndex = rects.length;351 rects.push(rect);352 });353 return new FrameData(currentFrame, rects, framesMap);354}355export function loadFlameGraphFormat(json) {356 const convertFrame = (jsonFrame, jsonFrameName, parentFrame) => {357 const frame = {358 name: jsonFrameName,359 samples: jsonFrame.samples,360 selfSamples: jsonFrame.selfSamples,361 childFrames: new Map(),362 depth: parentFrame ? parentFrame.depth + 1 : 0363 };364 if (jsonFrame.mark) {365 frame.mark = jsonFrame.mark;366 }367 if (jsonFrame.childFrames) {368 for (let childName in jsonFrame.childFrames) {369 if (jsonFrame.childFrames.hasOwnProperty(childName)) {370 frame.childFrames.set(childName, convertFrame(jsonFrame.childFrames[childName], childName, frame));371 }372 }373 }374 return frame;375 };376 const rootFrame = convertFrame(json.frameData.frame, 'all');377 enrichFrame(rootFrame);378 return generateFrameData(rootFrame);379}380export function loadJfrJson(events) {381 if (!Array.isArray(events)) {382 throw new Error('Expecting array');383 }384 const rootFrame = {385 name : 'all',386 samples : 0,387 childFrames: new Map(),388 depth : 0389 };390 for (let i = 0; i < events.length; i += 1) {391 const event = events[i];392 if (event.eventType === 'jdk.NativeMethodSample' && event.stackTrace && event.stackTrace.frames) {393 const frames = [];394 for (let j = event.stackTrace.frames.length - 1; j >=0; j -= 1) {395 frames.push(event.stackTrace.frames[j].method.class +'.'+ event.stackTrace.frames[j].method.method);396 }397 addFramesToFrame(rootFrame, frames, 1);398 }399 }400 sortFrames(rootFrame);401 enrichFrame(rootFrame);402 return generateFrameData(rootFrame);403}404export function parseNodeProfPreprocessedReport(json) {405 const rootFrame = {406 name : 'all',407 samples : 0,408 childFrames: new Map(),409 depth : 0410 };411 const codeToFrameName = (codeIdx) => {412 const code = json.code[codeIdx];413 if (!code) {414 return 'unknown';415 }416 // ignoring CODE types as we are mostly interested in JS part and it makes it difficult to read flame graphs with it417 if (code.type === 'CODE') {418 return null;419 }420 if (code.type === 'SHARED_LIB') {421 return '(lib) ' + code.name;422 }423 if (code.type === 'JS') {424 return code.name;425 }426 return code.type + ' ' + code.name;427 };428 for (let i = 0; i < json.ticks.length; i += 1) {429 const tick = json.ticks[i];430 const frames = [];431 for (let j = tick.s.length - 1; j >=0; j -= 1) {432 const name = codeToFrameName(tick.s[j]);433 if (name) {434 frames.push(name);435 }436 }437 addFramesToFrame(rootFrame, frames, 1);438 }439 sortFrames(rootFrame);440 enrichFrame(rootFrame);441 return generateFrameData(rootFrame);...
browser_getFrameTree.js
Source:browser_getFrameTree.js
1/* Any copyright is dedicated to the Public Domain.2 * http://creativecommons.org/publicdomain/zero/1.0/ */3"use strict";4const DOC = toDataURL("<div>foo</div>");5const DOC_IFRAME_MULTI = toDataURL(`6 <iframe src='data:text/html,foo'></iframe>7 <iframe src='data:text/html,bar'></iframe>8`);9const DOC_IFRAME_NESTED = toDataURL(`10 <iframe src="${DOC_IFRAME_MULTI}"></iframe>11`);12add_task(async function pageWithoutFrames({ client }) {13 const { Page } = client;14 info("Navigate to a page without a frame");15 await loadURL(DOC);16 const { frameTree } = await Page.getFrameTree();17 ok(!!frameTree.frame, "Expected frame details found");18 const expectedFrames = await getFlattenedFrameList();19 // Check top-level frame20 const expectedFrame = expectedFrames.get(frameTree.frame.id);21 is(frameTree.frame.id, expectedFrame.id, "Expected frame id found");22 is(frameTree.frame.parentId, undefined, "Parent frame doesn't exist");23 is(frameTree.name, undefined, "Top frame doens't contain name property");24 is(frameTree.frame.url, expectedFrame.url, "Expected url found");25 is(frameTree.childFrames, undefined, "No sub frames found");26});27add_task(async function PageWithFrames({ client }) {28 const { Page } = client;29 info("Navigate to a page with frames");30 await loadURL(DOC_IFRAME_MULTI);31 const { frameTree } = await Page.getFrameTree();32 ok(!!frameTree.frame, "Expected frame details found");33 const expectedFrames = await getFlattenedFrameList();34 let frame = frameTree.frame;35 let expectedFrame = expectedFrames.get(frame.id);36 info(`Check top frame with id: ${frame.id}`);37 is(frame.id, expectedFrame.id, "Expected frame id found");38 is(frame.parentId, undefined, "Parent frame doesn't exist");39 is(frame.name, undefined, "Top frame doesn't contain name property");40 is(frame.url, expectedFrame.url, "Expected URL found");41 is(frameTree.childFrames.length, 2, "Expected two sub frames");42 for (const childFrameTree of frameTree.childFrames) {43 let frame = childFrameTree.frame;44 let expectedFrame = expectedFrames.get(frame.id);45 info(`Check sub frame with id: ${frame.id}`);46 is(frame.id, expectedFrame.id, "Expected frame id found");47 is(frame.parentId, expectedFrame.parentId, "Expected parent id found");48 is(frame.name, expectedFrame.name, "Frame has expected name set");49 is(frame.url, expectedFrame.url, "Expected URL found");50 is(childFrameTree.childFrames, undefined, "No sub frames found");51 }52});53add_task(async function pageWithNestedFrames({ client }) {54 const { Page } = client;55 info("Navigate to a page with nested frames");56 await loadURL(DOC_IFRAME_NESTED);57 const { frameTree } = await Page.getFrameTree();58 ok(!!frameTree.frame, "Expected frame details found");59 const expectedFrames = await getFlattenedFrameList();60 let frame = frameTree.frame;61 let expectedFrame = expectedFrames.get(frame.id);62 info(`Check top frame with id: ${frame.id}`);63 is(frame.id, expectedFrame.id, "Expected frame id found");64 is(frame.parentId, undefined, "Parent frame doesn't exist");65 is(frame.name, undefined, "Top frame doesn't contain name property");66 is(frame.url, expectedFrame.url, "Expected URL found");67 is(frameTree.childFrames.length, 1, "Expected a single sub frame");68 const childFrameTree = frameTree.childFrames[0];69 frame = childFrameTree.frame;70 expectedFrame = expectedFrames.get(frame.id);71 info(`Check sub frame with id: ${frame.id}`);72 is(frame.id, expectedFrame.id, "Expected frame id found");73 is(frame.parentId, expectedFrame.parentId, "Expected parent id found");74 is(frame.name, expectedFrame.name, "Frame has expected name set");75 is(frame.url, expectedFrame.url, "Expected URL found");76 is(childFrameTree.childFrames.length, 2, "Expected two sub frames");77 let nestedChildFrameTree = childFrameTree.childFrames[0];78 frame = nestedChildFrameTree.frame;79 expectedFrame = expectedFrames.get(frame.id);80 info(`Check first nested frame with id: ${frame.id}`);81 is(frame.id, expectedFrame.id, "Expected frame id found");82 is(frame.parentId, expectedFrame.parentId, "Expected parent id found");83 is(frame.name, expectedFrame.name, "Frame has expected name set");84 is(frame.url, expectedFrame.url, "Expected URL found");85 is(nestedChildFrameTree.childFrames, undefined, "No sub frames found");86 nestedChildFrameTree = childFrameTree.childFrames[1];87 frame = nestedChildFrameTree.frame;88 expectedFrame = expectedFrames.get(frame.id);89 info(`Check second nested frame with id: ${frame.id}`);90 is(frame.id, expectedFrame.id, "Expected frame id found");91 is(frame.parentId, expectedFrame.parentId, "Expected parent id found");92 is(frame.name, expectedFrame.name, "Frame has expected name set");93 is(frame.url, expectedFrame.url, "Expected URL found");94 is(nestedChildFrameTree.childFrames, undefined, "No sub frames found");95});96/**97 * Retrieve all frames for the current tab as flattened list.98 */99function getFlattenedFrameList() {100 return SpecialPowers.spawn(gBrowser.selectedBrowser, [], () => {101 const frames = new Map();102 function getFrameDetails(context) {103 const frameElement = context.embedderElement;104 const frame = {105 id: context.id.toString(),106 parentId: context.parent ? context.parent.id.toString() : null,107 loaderId: null,108 name: frameElement?.id || frameElement?.name,109 url: context.docShell.domWindow.location.href,110 securityOrigin: null,111 mimeType: null,112 };113 if (context.parent) {114 frame.parentId = context.parent.id.toString();115 }116 frames.set(context.id.toString(), frame);117 for (const childContext of context.children) {118 getFrameDetails(childContext);119 }120 }121 getFrameDetails(content.docShell.browsingContext);122 return frames;123 });...
PageModel.js
Source:PageModel.js
1/*global define:false, window:false */2define( [ "./ChildFrameCollection", "../lint/LintCollection", "../coverage/CoverageDataModel", "../coverage/CoverageDataAggregator", "../deadcode/CodeListModel", "../deadcode/DeadCodeModel", "../notBackbone", "../notJQuery", "../notUnderscore", "../Config" ], function( ChildFrameCollection, LintCollection, CoverageDataModel, CoverageDataAggregator, CodeListModel, DeadCodeModel, Backbone, $, _, notKlujs ) {3 var log = function( msg ) {4 // console.log( msg );5 };6 var PageModel = Backbone.Model.extend( {7 defaults: {8 done : false9 // frameDiv, a div containing the iframes for suites.10 },11 initialize: function() {12 var self = this; 13 this.childFrames = new ChildFrameCollection.Model();14 this.childFrames.on( 'add', function( frameModel ) {15 self.get( "frameDiv" ).append( frameModel.frame );16 } );17 this.lintModel = new LintCollection();18 this.lintModel.on( 'add', function( modelAdded ) {19 modelAdded.check();20 } );21 this.lintModel.on( 'change', function() {22 log( "Unfinished: " + self.lintModel.unfinished() );23 if ( self.lintModel.unfinished() === 0 ) { 24 self.set( "lintDone", true );25 log( "lintDone" );26 }27 } );28 this.lintQueue = [];29 this.codeListModel = new CodeListModel( );30 this.codeListModel.fetch();31 this.coverageDataModel = new CoverageDataModel();32 this.deadCodeModel = new DeadCodeModel( {33 coverageDataModel : self.coverageDataModel,34 codeListModel: self.codeListModel,35 exceptions: notKlujs.deadCode()36 } );37 this.on( 'change:testDone', function( ) {38 if ( self.get( "testDone" ) === true ) {39 self.aggregateCoverage();40 self.doLint();41 }42 } );43 this.on( 'change:lintDone', function() {44 self.set("done", true );45 } );46 var built = false;47 var buildChildren = function() {48 if ( !built ) {49 built = true;50 $.each( self.get("config").suiteNames(), function( i, name ) {51 self.childFrames.add( {suite:name} );52 } );53 }54 };55 if ( self.get( "config" ) ) {56 buildChildren();57 }58 else {59 this.on( "change:config", buildChildren );60 }61 },62 check: function() {63 var self = this;64 var done = true;65 this.childFrames.forEach( function( x ) {66 x.check();67 done = done && (x.get("status") !== "running");68 } );69 if ( done ) {70 self.set( "testDone", true );71 }72 }, 73 lintFound : function( lf ) {74 this.lintQueue.push( lf );75 log( "q is " + this.lintQueue.length );76 },77 doLint : function() {78 var self = this;79 $.each( this.lintQueue, function( i, lf ) {80 self.lintModel.addFinderResult( lf );81 } );82 },83 coverageData: function() {84 var self = this; 85 var result = [];86 self.childFrames.forEach( function( cf ) {87 result.push( cf.plainFrame.contentWindow.$$_l );88 } );89 return result; 90 },91 aggregateCoverage: function() {92 var data = this.coverageData();93 var aggregate = CoverageDataAggregator( data );94 this.coverageDataModel.setData( aggregate );95 }96 } );97 return PageModel;...
stack-aggregator.js
Source:stack-aggregator.js
1module.exports =2class StackAggregator {3 constructor (sampleRate, functionNames) {4 this.sampleRate = sampleRate5 this.functionNames = functionNames6 if (typeof this.functionNames === 'string') {7 this.functionNames = [this.functionNames]8 }9 this.countedStacks = {}10 }11 getCountedStacks () {12 return Object.assign({}, this.countedStacks)13 }14 addStacks (stacks) {15 let index = 016 while (true) {17 const stackEndIndex = stacks.indexOf('\n\n', index, 'utf8')18 if (stackEndIndex === -1) break19 this.addStack(stacks.slice(index, stackEndIndex).toString('utf8'))20 index = stackEndIndex + 221 }22 return index23 }24 addStack (stack) {25 let truncatedStack26 if (this.functionNames && this.functionNames.length > 0) {27 let functionNameIndex = -128 for (const functionName of this.functionNames) {29 const index = stack.lastIndexOf(functionName)30 if (index > functionNameIndex) functionNameIndex = index31 }32 if (functionNameIndex !== -1) {33 const truncatedEndIndex = stack.indexOf('\n', functionNameIndex)34 truncatedStack = stack.slice(0, truncatedEndIndex) + stack.slice(stack.lastIndexOf('\n'))35 }36 } else {37 truncatedStack = stack38 }39 if (truncatedStack) {40 if (this.countedStacks[truncatedStack]) {41 this.countedStacks[truncatedStack]++42 } else {43 this.countedStacks[truncatedStack] = 144 }45 }46 }47 getCallTree () {48 const rootFrame = {childFrames: {}, sampleCount: 0}49 const stackStrings = Object.keys(this.countedStacks)50 for (let i = 0, n = stackStrings.length; i < n; i++) {51 const stackString = stackStrings[i]52 const sampleCount = this.countedStacks[stackString]53 const frameStrings = stackString.split('\n')54 rootFrame.sampleCount += sampleCount55 let frame = rootFrame56 for (let j = frameStrings.length - 2; j >= 0; j--) {57 const frameString = frameStrings[j].trim().split('+')[0]58 let childFrame = frame.childFrames[frameString]59 if (!childFrame) {60 childFrame = frame.childFrames[frameString] = {childFrames: {}, sampleCount: 0}61 }62 childFrame.sampleCount += sampleCount63 frame = childFrame64 }65 }66 return rootFrame67 }68 getBlocksToRender () {69 function addFrame (name, frame, depth, precedingSampleCount) {70 if (name) {71 blocks.push({72 name: name,73 depth: depth,74 left: precedingSampleCount / totalSampleCount * 100,75 width: frame.sampleCount / totalSampleCount * 100,76 duration: frame.sampleCount / sampleRate * 100077 })78 }79 depth++80 if (depth > 64) return81 const keys = Object.keys(frame.childFrames).sort();82 for (let childFrameName of keys.sort()) {83 const childFrame = frame.childFrames[childFrameName]84 addFrame(childFrameName, childFrame, depth, precedingSampleCount)85 precedingSampleCount += childFrame.sampleCount86 }87 }88 const blocks = []89 const rootFrame = this.getCallTree()90 const totalSampleCount = rootFrame.sampleCount91 const sampleRate = this.sampleRate92 addFrame(null, rootFrame, -1, 0)93 return blocks94 }...
stack-aggregator.test.js
Source:stack-aggregator.test.js
1const StackAggregator = require('../src/stack-aggregator')2const assert = require('assert')3describe('StackAggregator', () => {4 describe('.addStacks(buffer)', () => {5 it('adds each stack in the double-LF-separated output buffer', () => {6 const aggregator = new StackAggregator()7 aggregator.addStacks(Buffer.from([8 'aaa\n1',9 'bbb\naaa\n2',10 'bbb\naaa\n2',11 'ccc\nbbb\naaa\n3',12 'bbb\naaa\n2',13 'aaa\n1',14 ].join('\n\n') + '\n\n', 'utf8'))15 assert.deepEqual(aggregator.getCountedStacks(), {16 'aaa\n1': 2,17 'bbb\naaa\n2': 3,18 'ccc\nbbb\naaa\n3': 119 })20 })21 })22 describe('.getCallTree()', () => {23 it('returns a tree representing all the stacks', () => {24 const aggregator = new StackAggregator()25 aggregator.addStack('aaa\n1')26 aggregator.addStack('bbb\naaa\n2')27 aggregator.addStack('ccc\nbbb\naaa\n3')28 aggregator.addStack('ccc\nbbb\naaa\n3')29 aggregator.addStack('bbb\naaa\n2')30 aggregator.addStack('ddd\nbbb\naaa\n3')31 aggregator.addStack('eee\n1')32 aggregator.addStack('eee\n1')33 const rootFrame = aggregator.getCallTree()34 assert.equal(rootFrame.sampleCount, 8)35 assert.deepEqual(rootFrame, {36 sampleCount: 8,37 childFrames: {38 'aaa': {39 sampleCount: 6,40 childFrames: {41 'bbb': {42 sampleCount: 5,43 childFrames: {44 'ccc': {45 sampleCount: 2,46 childFrames: {}47 },48 'ddd': {49 sampleCount: 1,50 childFrames: {}51 }52 }53 }54 }55 },56 'eee': {57 sampleCount: 2,58 childFrames: {}59 }60 }61 })62 })63 })64 describe('.getBlocksToRender()', () => {65 it('returns a flat list of positioned rectanges representing stack frames to render', () => {66 const aggregator = new StackAggregator(500) // 500 samples / second67 aggregator.addStack('bbb\naaa\n2')68 aggregator.addStack('aaa\n1')69 aggregator.addStack('ccc\nbbb\naaa\n2')70 aggregator.addStack('eee\n1')71 const blocks = aggregator.getBlocksToRender()72 assert.deepEqual(blocks.slice(0, 3), [73 {74 name: 'aaa',75 depth: 0,76 left: 0,77 width: 75,78 duration: 679 },80 {81 name: 'bbb',82 depth: 1,83 left: 0,84 width: 50,85 duration: 486 },87 {88 name: 'ccc',89 depth: 2,90 left: 0,91 width: 25,92 duration: 293 }94 ])95 })96 })...
index.test.js
Source:index.test.js
1'use strict'2const chai = require('chai')3const app = require('../app')4describe('Testing', () => {5 it('Testing getFrameByName - Validation - with not frame', done => {6 try {7 app.getFrameByName(null, 'frameName')8 done('Should be throws validation error!')9 } catch (e) {10 done()11 }12 })13 it('Testing getFrameByName - Validation - with not mainFrame', done => {14 try {15 app.getFrameByName({}, 'frameName')16 done('Should be throws validation error!')17 } catch (e) {18 done()19 }20 })21 it('Testing getFrameByName - Validation - frame not found', done => {22 try {23 app.getFrameByName(24 {25 name: () => {26 return 'frameNotFound'27 },28 childFrames: () => {29 return []30 },31 },32 'frameName'33 )34 done('Should be throws validation error!')35 } catch (e) {36 done()37 }38 })39 it('Testing getFrameByName - OK', done => {40 try {41 const frame = app.getFrameByName(42 {43 name: () => {44 return 'frameName'45 },46 childFrames: () => {47 return []48 },49 },50 'frameName'51 )52 chai.assert.exists(frame.name, 'frame.name is not exists!')53 chai.assert.exists(frame.childFrames, 'frame.childFrames is not exists!')54 chai.assert.isFunction(frame.name, 'frame.name is not function!')55 chai.assert.isFunction(frame.childFrames, 'frame.childFrames is not function!')56 done()57 } catch (e) {58 done(e)59 }60 })...
Using AI Code Generation
1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch({4 });5 const page = await browser.newPage();6 const frame = await page.frames().find(f => f.name() === 'google_ads_iframe_/21772563934/Google_LB_1');7 await frame.click('a');8 await page.waitForNavigation();9 await page.screenshot({ path: 'google.png' });10 await browser.close();11})();
Using AI Code Generation
1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch({headless: false});4 const page = await browser.newPage();5 const frames = await page.frames();6 for (let frame of frames) {7 console.log(frame.url());8 }9 await browser.close();10})();
Using AI Code Generation
1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch({headless: false});4 const page = await browser.newPage();5 await page.waitForSelector('input[title="Search"]');6 await page.type('input[title="Search"]', 'puppeteer');7 await page.keyboard.press('Enter');8 await page.waitForSelector('h3.LC20lb');9 await page.click('h3.LC20lb');10 await page.waitForSelector('p');11 const childFrames = await page.frames();12 const frame = childFrames.find(f => f.name() === 'iframeResult');13 const p = await frame.$eval('p', el => el.textContent);14 console.log(p);15 await browser.close();16})();17Using childFrames() method18childFrames([selector])19const puppeteer = require('puppeteer');20(async () => {21 const browser = await puppeteer.launch({headless: false});22 const page = await browser.newPage();23 await page.waitForSelector('input[title="Search"]');24 await page.type('input[title="Search"]', 'puppeteer');25 await page.keyboard.press('Enter');26 await page.waitForSelector('h3.LC20lb');27 await page.click('h3.LC20lb');28 await page.waitForSelector('p');29 const childFrames = await page.frames();30 const frame = childFrames.find(f => f.name() === 'iframeResult');31 const p = await frame.$eval('p', el => el.textContent);32 console.log(p);33 await browser.close();34})();
Using AI Code Generation
1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch({headless: false});4 const page = await browser.newPage();5 const frames = await page.frames();6 for (let frame of frames) {7 if (frame.name() === 'childFrame') {8 await frame.evaluate(() => {9 console.log('Child frame name:', frame.name());10 });11 }12 }13 await browser.close();14})();15const puppeteer = require('puppeteer');16(async () => {17 const browser = await puppeteer.launch({headless: false});18 const page = await browser.newPage();19 const frames = await page.frames();20 for (let frame of frames) {21 if (frame.name() === 'childFrame') {22 await frame.evaluate(() => {23 console.log('Child frame name:', frame.name());24 });25 }26 }27 await browser.close();28})();29const puppeteer = require('puppeteer');30(async () => {31 const browser = await puppeteer.launch({headless: false});32 const page = await browser.newPage();33 const frames = await page.frames();34 for (let frame of frames) {35 if (frame.name() === 'childFrame') {36 await frame.evaluate(() => {37 console.log('Child frame name:', frame.name());38 });39 }40 }41 await browser.close();42})();43const puppeteer = require('puppeteer');44(async () => {45 const browser = await puppeteer.launch({headless: false});46 const page = await browser.newPage();47 const frames = await page.frames();48 for (let frame of frames) {49 if (frame.name() === 'childFrame') {50 await frame.evaluate(() => {51 console.log('Child frame name:', frame.name());52 });
Using AI Code Generation
1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch({headless: false});4 const page = await browser.newPage();5 const frames = await page.frames();6 const frame = frames.find(f => f.name() === 'iframe');7 await frame.click('#button');8 await browser.close();9})();10const frame = page.frames().find(f => f.name() === 'iframe');11const value = await frame.$eval('#field', el => el.value);12const frame = page.frames().find(f => f.name() === 'iframe');13const value = await frame.$eval('#field', el => el.value);14const frame = page.frames().find(f => f.name() === 'iframe');15const value = await frame.$eval('#field', el => el.value);16const frame = page.frames().find(f => f.name() === 'iframe');17const value = await frame.$eval('#field', el => el.value);
Using AI Code Generation
1const puppeteer = require('puppeteer');2const fs = require('fs');3const path = require('path');4(async () => {5 const browser = await puppeteer.launch({ headless: false });6 const page = await browser.newPage();7 await page.waitForNavigation();8 const frame = page.frames().find(f => f.name() === 'iframe-name');9 const frameElement = await frame.$('iframe-element');10 const frameContent = await frame.evaluate(e => e.contentWindow.document.body.innerHTML, frameElement);11 console.log(frameContent);12 await browser.close();13})();14const puppeteer = require('puppeteer');15const fs = require('fs');16const path = require('path');17(async () => {18 const browser = await puppeteer.launch({ headless: false });19 const page = await browser.newPage();20 await page.waitForNavigation();21 const frame = page.frames().find(f => f.name() === 'iframe-name');22 const frameElement = await frame.$('iframe-element');23 const frameContent = await frame.evaluate(e => e.contentWindow.document.body.innerHTML, frameElement);24 console.log(frameContent);25 await browser.close();26})();27const puppeteer = require('puppeteer');28const fs = require('fs');29const path = require('path');30(async () => {31 const browser = await puppeteer.launch({ headless: false });32 const page = await browser.newPage();33 await page.waitForNavigation();34 const frame = page.frames().find(f => f.name() === 'iframe-name');35 const frameElement = await frame.$('iframe-element');36 const frameContent = await frame.evaluate(e => e.contentWindow.document.body.innerHTML, frameElement);37 console.log(frameContent);38 await browser.close();39})();40const puppeteer = require('puppeteer');41const fs = require('fs');42const path = require('path');43(async () => {44 const browser = await puppeteer.launch({ headless: false });45 const page = await browser.newPage();
Using AI Code Generation
1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch();4 const page = await browser.newPage();5 await page.goto(url);6 const frames = await page.frames();7 const frame = frames.find(f => f.name() === 'myFrame');8 await frame.click('button');9 await browser.close();10})();11### Working with `page.frames()`12const puppeteer = require('puppeteer');13(async () => {14 const browser = await puppeteer.launch();15 const page = await browser.newPage();16 await page.goto(url);17 const frames = await page.frames();18 const frame = frames.find(f => f.name() === 'myFrame');19 await frame.click('button');20 await browser.close();21})();22const puppeteer = require('puppeteer');23(async () => {24 const browser = await puppeteer.launch();25 const page = await browser.newPage();26 await page.goto(url);27 const frames = await page.frames();28 await frame.click('button');29 await browser.close();30})();
Using AI Code Generation
1const puppeteer = require('puppeteer');2const fs = require('fs');3async function main() {4 const browser = await puppeteer.launch({5 });6 const page = await browser.newPage();7 await page.waitForSelector('input[name="q"]');8 await page.type('input[name="q"]', 'puppeteer');9 await page.keyboard.press('Enter');10 await page.waitForSelector('a[href="/web/tools/puppeteer/articles"]');11 await page.click('a[href="/web/tools/puppeteer/articles"]');12 await page.waitForSelector('a[href="/web/tools/puppeteer/articles/pdf"]');13 await page.click('a[href="/web/tools/puppeteer/articles/pdf"]');14 await page.waitForSelector('a[href="/web/tools/puppeteer/articles/pdf"]');15 await page.click('a[href="/web/tools/puppeteer/articles/pdf"]');16 await page.waitForSelector('a[href="/web/tools/puppeteer/articles/pdf"]');17 await page.click('a[href="/web/tools/puppeteer/articles/pdf"]');18 await page.waitForSelector('a[href="/web/tools/puppeteer/articles/pdf"]');19 await page.click('a[href="/web/tools/puppeteer/articles/pdf"]');20 await page.waitForSelector('a[href="/web/tools/puppeteer/articles/pdf"]');21 await page.click('a[href="/web/tools/puppeteer/articles/pdf"]');22 await page.waitForSelector('a[href="/web/tools/puppeteer/articles/pdf"]');23 await page.click('a[href="/web/tools/puppeteer/articles/pdf"]');24 await page.waitForSelector('a[href="/web/tools/puppeteer/articles/pdf"]');25 await page.click('a[href="/web/tools/puppeteer/articles/pdf"]');26 await page.waitForSelector('a[href="/web/tools/puppeteer/articles/pdf"]');27 await page.click('a[href="/web/tools/puppeteer/articles/pdf"]');28 await page.waitForSelector('a[href="/web/tools/puppeteer/articles/pdf"]');29 await page.click('a[href="/web/tools/puppeteer/articles/pdf"]');30 await page.waitForSelector('a[href="/web/tools/puppeteer/articles/pdf"]');31 await page.click('a[href="/web/tools/puppet
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!