How to use metrics method in Best

Best JavaScript code snippet using best

metrics_manager.67ee8bff0471.js

Source:metrics_manager.67ee8bff0471.js Github

copy

Full Screen

1/**2 * @license3 * Copyright 2021 Google LLC4 * SPDX-License-Identifier: Apache-2.05 */6/**7 * @fileoverview Calculates and reports workspace metrics.8 * @author aschmiedt@google.com (Abby Schmiedt)9 */10'use strict';11goog.provide('Blockly.FlyoutMetricsManager');12goog.provide('Blockly.MetricsManager');13goog.require('Blockly.IMetricsManager');14goog.require('Blockly.registry');15goog.require('Blockly.utils.Size');16goog.require('Blockly.utils.toolbox');17goog.requireType('Blockly.IFlyout');18goog.requireType('Blockly.IToolbox');19goog.requireType('Blockly.utils.Metrics');20goog.requireType('Blockly.WorkspaceSvg');21/**22 * The manager for all workspace metrics calculations.23 * @param {!Blockly.WorkspaceSvg} workspace The workspace to calculate metrics24 * for.25 * @implements {Blockly.IMetricsManager}26 * @constructor27 */28Blockly.MetricsManager = function(workspace) {29 /**30 * The workspace to calculate metrics for.31 * @type {!Blockly.WorkspaceSvg}32 * @protected33 */34 this.workspace_ = workspace;35};36/**37 * Describes the width, height and location of the toolbox on the main38 * workspace.39 * @typedef {{40 * width: number,41 * height: number,42 * position: !Blockly.utils.toolbox.Position43 * }}44 */45Blockly.MetricsManager.ToolboxMetrics;46/**47 * Describes where the viewport starts in relation to the workspace SVG.48 * @typedef {{49 * left: number,50 * top: number51 * }}52 */53Blockly.MetricsManager.AbsoluteMetrics;54/**55 * All the measurements needed to describe the size and location of a container.56 * @typedef {{57 * height: number,58 * width: number,59 * top: number,60 * left: number61 * }}62 */63Blockly.MetricsManager.ContainerRegion;64/**65 * Describes fixed edges of the workspace.66 * @typedef {{67 * top: (number|undefined),68 * bottom: (number|undefined),69 * left: (number|undefined),70 * right: (number|undefined)71 * }}72 */73Blockly.MetricsManager.FixedEdges;74/**75 * Common metrics used for UI elements.76 * @typedef {{77 * viewMetrics: !Blockly.MetricsManager.ContainerRegion,78 * absoluteMetrics: !Blockly.MetricsManager.AbsoluteMetrics,79 * toolboxMetrics: !Blockly.MetricsManager.ToolboxMetrics80 * }}81 */82Blockly.MetricsManager.UiMetrics;83/**84 * Gets the dimensions of the given workspace component, in pixel coordinates.85 * @param {?Blockly.IToolbox|?Blockly.IFlyout} elem The element to get the86 * dimensions of, or null. It should be a toolbox or flyout, and should87 * implement getWidth() and getHeight().88 * @return {!Blockly.utils.Size} An object containing width and height89 * attributes, which will both be zero if elem did not exist.90 * @protected91 */92Blockly.MetricsManager.prototype.getDimensionsPx_ = function(elem) {93 var width = 0;94 var height = 0;95 if (elem) {96 width = elem.getWidth();97 height = elem.getHeight();98 }99 return new Blockly.utils.Size(width, height);100};101/**102 * Gets the width and the height of the flyout on the workspace in pixel103 * coordinates. Returns 0 for the width and height if the workspace has a104 * category toolbox instead of a simple toolbox.105 * @param {boolean=} opt_own Whether to only return the workspace's own flyout.106 * @return {!Blockly.MetricsManager.ToolboxMetrics} The width and height of the107 * flyout.108 * @public109 */110Blockly.MetricsManager.prototype.getFlyoutMetrics = function(opt_own) {111 var flyoutDimensions =112 this.getDimensionsPx_(this.workspace_.getFlyout(opt_own));113 return {114 width: flyoutDimensions.width,115 height: flyoutDimensions.height,116 position: this.workspace_.toolboxPosition117 };118};119/**120 * Gets the width, height and position of the toolbox on the workspace in pixel121 * coordinates. Returns 0 for the width and height if the workspace has a simple122 * toolbox instead of a category toolbox. To get the width and height of a123 * simple toolbox @see {@link getFlyoutMetrics}.124 * @return {!Blockly.MetricsManager.ToolboxMetrics} The object with the width,125 * height and position of the toolbox.126 * @public127 */128Blockly.MetricsManager.prototype.getToolboxMetrics = function() {129 var toolboxDimensions = this.getDimensionsPx_(this.workspace_.getToolbox());130 return {131 width: toolboxDimensions.width,132 height: toolboxDimensions.height,133 position: this.workspace_.toolboxPosition134 };135};136/**137 * Gets the width and height of the workspace's parent SVG element in pixel138 * coordinates. This area includes the toolbox and the visible workspace area.139 * @return {!Blockly.utils.Size} The width and height of the workspace's parent140 * SVG element.141 * @public142 */143Blockly.MetricsManager.prototype.getSvgMetrics = function() {144 return this.workspace_.getCachedParentSvgSize();145};146/**147 * Gets the absolute left and absolute top in pixel coordinates.148 * This is where the visible workspace starts in relation to the SVG container.149 * @return {!Blockly.MetricsManager.AbsoluteMetrics} The absolute metrics for150 * the workspace.151 * @public152 */153Blockly.MetricsManager.prototype.getAbsoluteMetrics = function() {154 var absoluteLeft = 0;155 var toolboxMetrics = this.getToolboxMetrics();156 var flyoutMetrics = this.getFlyoutMetrics(true);157 var doesToolboxExist = !!this.workspace_.getToolbox();158 var doesFlyoutExist = !!this.workspace_.getFlyout(true);159 var toolboxPosition =160 doesToolboxExist ? toolboxMetrics.position : flyoutMetrics.position;161 var atLeft = toolboxPosition == Blockly.utils.toolbox.Position.LEFT;162 var atTop = toolboxPosition == Blockly.utils.toolbox.Position.TOP;163 if (doesToolboxExist && atLeft) {164 absoluteLeft = toolboxMetrics.width;165 } else if (doesFlyoutExist && atLeft) {166 absoluteLeft = flyoutMetrics.width;167 }168 var absoluteTop = 0;169 if (doesToolboxExist && atTop) {170 absoluteTop = toolboxMetrics.height;171 } else if (doesFlyoutExist && atTop) {172 absoluteTop = flyoutMetrics.height;173 }174 return {175 top: absoluteTop,176 left: absoluteLeft,177 };178};179/**180 * Gets the metrics for the visible workspace in either pixel or workspace181 * coordinates. The visible workspace does not include the toolbox or flyout.182 * @param {boolean=} opt_getWorkspaceCoordinates True to get the view metrics in183 * workspace coordinates, false to get them in pixel coordinates.184 * @return {!Blockly.MetricsManager.ContainerRegion} The width, height, top and185 * left of the viewport in either workspace coordinates or pixel186 * coordinates.187 * @public188 */189Blockly.MetricsManager.prototype.getViewMetrics = function(190 opt_getWorkspaceCoordinates) {191 var scale = opt_getWorkspaceCoordinates ? this.workspace_.scale : 1;192 var svgMetrics = this.getSvgMetrics();193 var toolboxMetrics = this.getToolboxMetrics();194 var flyoutMetrics = this.getFlyoutMetrics(true);195 var doesToolboxExist = !!this.workspace_.getToolbox();196 var toolboxPosition =197 doesToolboxExist ? toolboxMetrics.position : flyoutMetrics.position;198 if (this.workspace_.getToolbox()) {199 if (toolboxPosition == Blockly.utils.toolbox.Position.TOP ||200 toolboxPosition == Blockly.utils.toolbox.Position.BOTTOM) {201 svgMetrics.height -= toolboxMetrics.height;202 } else if (toolboxPosition == Blockly.utils.toolbox.Position.LEFT ||203 toolboxPosition == Blockly.utils.toolbox.Position.RIGHT) {204 svgMetrics.width -= toolboxMetrics.width;205 }206 } else if (this.workspace_.getFlyout(true)) {207 if (toolboxPosition == Blockly.utils.toolbox.Position.TOP ||208 toolboxPosition == Blockly.utils.toolbox.Position.BOTTOM) {209 svgMetrics.height -= flyoutMetrics.height;210 } else if (toolboxPosition == Blockly.utils.toolbox.Position.LEFT ||211 toolboxPosition == Blockly.utils.toolbox.Position.RIGHT) {212 svgMetrics.width -= flyoutMetrics.width;213 }214 }215 return {216 height: svgMetrics.height / scale,217 width: svgMetrics.width / scale,218 top: -this.workspace_.scrollY / scale,219 left: -this.workspace_.scrollX / scale,220 };221};222/**223 * Gets content metrics in either pixel or workspace coordinates.224 * The content area is a rectangle around all the top bounded elements on the225 * workspace (workspace comments and blocks).226 * @param {boolean=} opt_getWorkspaceCoordinates True to get the content metrics227 * in workspace coordinates, false to get them in pixel coordinates.228 * @return {!Blockly.MetricsManager.ContainerRegion} The229 * metrics for the content container.230 * @public231 */232Blockly.MetricsManager.prototype.getContentMetrics = function(233 opt_getWorkspaceCoordinates) {234 var scale = opt_getWorkspaceCoordinates ? 1 : this.workspace_.scale;235 // Block bounding box is in workspace coordinates.236 var blockBox = this.workspace_.getBlocksBoundingBox();237 return {238 height: (blockBox.bottom - blockBox.top) * scale,239 width: (blockBox.right - blockBox.left) * scale,240 top: blockBox.top * scale,241 left: blockBox.left * scale,242 };243};244/**245 * Returns whether the scroll area has fixed edges.246 * @return {boolean} Whether the scroll area has fixed edges.247 * @package248 */249Blockly.MetricsManager.prototype.hasFixedEdges = function() {250 // This exists for optimization of bump logic.251 return !this.workspace_.isMovableHorizontally() ||252 !this.workspace_.isMovableVertically();253};254/**255 * Computes the fixed edges of the scroll area.256 * @param {!Blockly.MetricsManager.ContainerRegion=} opt_viewMetrics The view257 * metrics if they have been previously computed. Passing in null may cause258 * the view metrics to be computed again, if it is needed.259 * @return {!Blockly.MetricsManager.FixedEdges} The fixed edges of the scroll260 * area.261 * @protected262 */263Blockly.MetricsManager.prototype.getComputedFixedEdges_ = function(264 opt_viewMetrics) {265 if (!this.hasFixedEdges()) {266 // Return early if there are no edges.267 return {};268 }269 var hScrollEnabled = this.workspace_.isMovableHorizontally();270 var vScrollEnabled = this.workspace_.isMovableVertically();271 var viewMetrics = opt_viewMetrics || this.getViewMetrics(false);272 var edges = {};273 if (!vScrollEnabled) {274 edges.top = viewMetrics.top;275 edges.bottom = viewMetrics.top + viewMetrics.height;276 }277 if (!hScrollEnabled) {278 edges.left = viewMetrics.left;279 edges.right = viewMetrics.left + viewMetrics.width;280 }281 return edges;282};283/**284 * Returns the content area with added padding.285 * @param {!Blockly.MetricsManager.ContainerRegion} viewMetrics The view286 * metrics.287 * @param {!Blockly.MetricsManager.ContainerRegion} contentMetrics The content288 * metrics.289 * @return {{top: number, bottom: number, left: number, right: number}} The290 * padded content area.291 * @protected292 */293Blockly.MetricsManager.prototype.getPaddedContent_ = function(294 viewMetrics, contentMetrics) {295 var contentBottom = contentMetrics.top + contentMetrics.height;296 var contentRight = contentMetrics.left + contentMetrics.width;297 var viewWidth = viewMetrics.width;298 var viewHeight = viewMetrics.height;299 var halfWidth = viewWidth / 2;300 var halfHeight = viewHeight / 2;301 // Add a padding around the content that is at least half a screen wide.302 // Ensure padding is wide enough that blocks can scroll over entire screen.303 var top =304 Math.min(contentMetrics.top - halfHeight, contentBottom - viewHeight);305 var left =306 Math.min(contentMetrics.left - halfWidth, contentRight - viewWidth);307 var bottom =308 Math.max(contentBottom + halfHeight, contentMetrics.top + viewHeight);309 var right =310 Math.max(contentRight + halfWidth, contentMetrics.left + viewWidth);311 return {top: top, bottom: bottom, left: left, right: right};312};313/**314 * Returns the metrics for the scroll area of the workspace.315 * @param {boolean=} opt_getWorkspaceCoordinates True to get the scroll metrics316 * in workspace coordinates, false to get them in pixel coordinates.317 * @param {!Blockly.MetricsManager.ContainerRegion=} opt_viewMetrics The view318 * metrics if they have been previously computed. Passing in null may cause319 * the view metrics to be computed again, if it is needed.320 * @param {!Blockly.MetricsManager.ContainerRegion=} opt_contentMetrics The321 * content metrics if they have been previously computed. Passing in null322 * may cause the content metrics to be computed again, if it is needed.323 * @return {!Blockly.MetricsManager.ContainerRegion} The metrics for the scroll324 * container.325 */326Blockly.MetricsManager.prototype.getScrollMetrics = function(327 opt_getWorkspaceCoordinates, opt_viewMetrics, opt_contentMetrics) {328 var scale = opt_getWorkspaceCoordinates ? this.workspace_.scale : 1;329 var viewMetrics = opt_viewMetrics || this.getViewMetrics(false);330 var contentMetrics = opt_contentMetrics || this.getContentMetrics();331 var fixedEdges = this.getComputedFixedEdges_(viewMetrics);332 // Add padding around content.333 var paddedContent = this.getPaddedContent_(viewMetrics, contentMetrics);334 // Use combination of fixed bounds and padded content to make scroll area.335 var top = fixedEdges.top !== undefined ?336 fixedEdges.top : paddedContent.top;337 var left = fixedEdges.left !== undefined ?338 fixedEdges.left : paddedContent.left;339 var bottom = fixedEdges.bottom !== undefined ?340 fixedEdges.bottom : paddedContent.bottom;341 var right = fixedEdges.right !== undefined ?342 fixedEdges.right : paddedContent.right;343 return {344 top: top / scale,345 left: left / scale,346 width: (right - left) / scale,347 height: (bottom - top) / scale,348 };349};350/**351 * Returns common metrics used by UI elements.352 * @return {!Blockly.MetricsManager.UiMetrics} The UI metrics.353 */354Blockly.MetricsManager.prototype.getUiMetrics = function() {355 return {356 viewMetrics: this.getViewMetrics(),357 absoluteMetrics: this.getAbsoluteMetrics(),358 toolboxMetrics: this.getToolboxMetrics()359 };360};361/**362 * Returns an object with all the metrics required to size scrollbars for a363 * top level workspace. The following properties are computed:364 * Coordinate system: pixel coordinates, -left, -up, +right, +down365 * .viewHeight: Height of the visible portion of the workspace.366 * .viewWidth: Width of the visible portion of the workspace.367 * .contentHeight: Height of the content.368 * .contentWidth: Width of the content.369 * .scrollHeight: Height of the scroll area.370 * .scrollWidth: Width of the scroll area.371 * .svgHeight: Height of the Blockly div (the view + the toolbox,372 * simple or otherwise),373 * .svgWidth: Width of the Blockly div (the view + the toolbox,374 * simple or otherwise),375 * .viewTop: Top-edge of the visible portion of the workspace, relative to376 * the workspace origin.377 * .viewLeft: Left-edge of the visible portion of the workspace, relative to378 * the workspace origin.379 * .contentTop: Top-edge of the content, relative to the workspace origin.380 * .contentLeft: Left-edge of the content relative to the workspace origin.381 * .scrollTop: Top-edge of the scroll area, relative to the workspace origin.382 * .scrollLeft: Left-edge of the scroll area relative to the workspace origin.383 * .absoluteTop: Top-edge of the visible portion of the workspace, relative384 * to the blocklyDiv.385 * .absoluteLeft: Left-edge of the visible portion of the workspace, relative386 * to the blocklyDiv.387 * .toolboxWidth: Width of the toolbox, if it exists. Otherwise zero.388 * .toolboxHeight: Height of the toolbox, if it exists. Otherwise zero.389 * .flyoutWidth: Width of the flyout if it is always open. Otherwise zero.390 * .flyoutHeight: Height of the flyout if it is always open. Otherwise zero.391 * .toolboxPosition: Top, bottom, left or right. Use TOOLBOX_AT constants to392 * compare.393 * @return {!Blockly.utils.Metrics} Contains size and position metrics of a top394 * level workspace.395 * @public396 */397Blockly.MetricsManager.prototype.getMetrics = function() {398 var toolboxMetrics = this.getToolboxMetrics();399 var flyoutMetrics = this.getFlyoutMetrics(true);400 var svgMetrics = this.getSvgMetrics();401 var absoluteMetrics = this.getAbsoluteMetrics();402 var viewMetrics = this.getViewMetrics();403 var contentMetrics = this.getContentMetrics();404 var scrollMetrics = this.getScrollMetrics(false, viewMetrics, contentMetrics);405 return {406 contentHeight: contentMetrics.height,407 contentWidth: contentMetrics.width,408 contentTop: contentMetrics.top,409 contentLeft: contentMetrics.left,410 scrollHeight: scrollMetrics.height,411 scrollWidth: scrollMetrics.width,412 scrollTop: scrollMetrics.top,413 scrollLeft: scrollMetrics.left,414 viewHeight: viewMetrics.height,415 viewWidth: viewMetrics.width,416 viewTop: viewMetrics.top,417 viewLeft: viewMetrics.left,418 absoluteTop: absoluteMetrics.top,419 absoluteLeft: absoluteMetrics.left,420 svgHeight: svgMetrics.height,421 svgWidth: svgMetrics.width,422 toolboxWidth: toolboxMetrics.width,423 toolboxHeight: toolboxMetrics.height,424 toolboxPosition: toolboxMetrics.position,425 flyoutWidth: flyoutMetrics.width,426 flyoutHeight: flyoutMetrics.height427 };428};429Blockly.registry.register(430 Blockly.registry.Type.METRICS_MANAGER, Blockly.registry.DEFAULT,431 Blockly.MetricsManager);432/**433 * Calculates metrics for a flyout's workspace.434 * The metrics are mainly used to size scrollbars for the flyout.435 * @param {!Blockly.WorkspaceSvg} workspace The flyout's workspace.436 * @param {!Blockly.IFlyout} flyout The flyout.437 * @extends {Blockly.MetricsManager}438 * @constructor439 */440Blockly.FlyoutMetricsManager = function(workspace, flyout) {441 /**442 * The flyout that owns the workspace to calculate metrics for.443 * @type {!Blockly.IFlyout}444 * @protected445 */446 this.flyout_ = flyout;447 Blockly.FlyoutMetricsManager.superClass_.constructor.call(this, workspace);448};449Blockly.utils.object.inherits(450 Blockly.FlyoutMetricsManager, Blockly.MetricsManager);451/**452 * Gets the bounding box of the blocks on the flyout's workspace.453 * This is in workspace coordinates.454 * @return {!SVGRect|{height: number, y: number, width: number, x: number}} The455 * bounding box of the blocks on the workspace.456 * @private457 */458Blockly.FlyoutMetricsManager.prototype.getBoundingBox_ = function() {459 try {460 var blockBoundingBox = this.workspace_.getCanvas().getBBox();461 } catch (e) {462 // Firefox has trouble with hidden elements (Bug 528969).463 // 2021 Update: It looks like this was fixed around Firefox 77 released in464 // 2020.465 var blockBoundingBox = {height: 0, y: 0, width: 0, x: 0};466 }467 return blockBoundingBox;468};469/**470 * @override471 */472Blockly.FlyoutMetricsManager.prototype.getContentMetrics = function(473 opt_getWorkspaceCoordinates) {474 // The bounding box is in workspace coordinates.475 var blockBoundingBox = this.getBoundingBox_();476 var scale = opt_getWorkspaceCoordinates ? 1 : this.workspace_.scale;477 return {478 height: blockBoundingBox.height * scale,479 width: blockBoundingBox.width * scale,480 top: blockBoundingBox.y * scale,481 left: blockBoundingBox.x * scale,482 };483};484/**485 * @override486 */487Blockly.FlyoutMetricsManager.prototype.getScrollMetrics = function(488 opt_getWorkspaceCoordinates, opt_viewMetrics, opt_contentMetrics) {489 var contentMetrics = opt_contentMetrics || this.getContentMetrics();490 var margin = this.flyout_.MARGIN * this.workspace_.scale;491 var scale = opt_getWorkspaceCoordinates ? this.workspace_.scale : 1;492 // The left padding isn't just the margin. Some blocks are also offset by493 // tabWidth so that value and statement blocks line up.494 // The contentMetrics.left value is equivalent to the variable left padding.495 var leftPadding = contentMetrics.left;496 return {497 height: (contentMetrics.height + 2 * margin) / scale,498 width: (contentMetrics.width + leftPadding + margin) / scale,499 top: 0,500 left: 0,501 };...

Full Screen

Full Screen

metrics_manager.js

Source:metrics_manager.js Github

copy

Full Screen

1/**2 * @license3 * Copyright 2021 Google LLC4 * SPDX-License-Identifier: Apache-2.05 */6/**7 * @fileoverview Calculates and reports workspace metrics.8 * @author aschmiedt@google.com (Abby Schmiedt)9 */10'use strict';11goog.provide('Blockly.FlyoutMetricsManager');12goog.provide('Blockly.MetricsManager');13goog.require('Blockly.IMetricsManager');14goog.require('Blockly.registry');15goog.require('Blockly.utils.Size');16goog.require('Blockly.utils.toolbox');17goog.requireType('Blockly.IFlyout');18goog.requireType('Blockly.IToolbox');19goog.requireType('Blockly.utils.Metrics');20goog.requireType('Blockly.WorkspaceSvg');21/**22 * The manager for all workspace metrics calculations.23 * @param {!Blockly.WorkspaceSvg} workspace The workspace to calculate metrics24 * for.25 * @implements {Blockly.IMetricsManager}26 * @constructor27 */28Blockly.MetricsManager = function(workspace) {29 /**30 * The workspace to calculate metrics for.31 * @type {!Blockly.WorkspaceSvg}32 * @protected33 */34 this.workspace_ = workspace;35};36/**37 * Describes the width, height and location of the toolbox on the main38 * workspace.39 * @typedef {{40 * width: number,41 * height: number,42 * position: !Blockly.utils.toolbox.Position43 * }}44 */45Blockly.MetricsManager.ToolboxMetrics;46/**47 * Describes where the viewport starts in relation to the workspace SVG.48 * @typedef {{49 * left: number,50 * top: number51 * }}52 */53Blockly.MetricsManager.AbsoluteMetrics;54/**55 * All the measurements needed to describe the size and location of a container.56 * @typedef {{57 * height: number,58 * width: number,59 * top: number,60 * left: number61 * }}62 */63Blockly.MetricsManager.ContainerRegion;64/**65 * Describes fixed edges of the workspace.66 * @typedef {{67 * top: (number|undefined),68 * bottom: (number|undefined),69 * left: (number|undefined),70 * right: (number|undefined)71 * }}72 */73Blockly.MetricsManager.FixedEdges;74/**75 * Common metrics used for UI elements.76 * @typedef {{77 * viewMetrics: !Blockly.MetricsManager.ContainerRegion,78 * absoluteMetrics: !Blockly.MetricsManager.AbsoluteMetrics,79 * toolboxMetrics: !Blockly.MetricsManager.ToolboxMetrics80 * }}81 */82Blockly.MetricsManager.UiMetrics;83/**84 * Gets the dimensions of the given workspace component, in pixel coordinates.85 * @param {?Blockly.IToolbox|?Blockly.IFlyout} elem The element to get the86 * dimensions of, or null. It should be a toolbox or flyout, and should87 * implement getWidth() and getHeight().88 * @return {!Blockly.utils.Size} An object containing width and height89 * attributes, which will both be zero if elem did not exist.90 * @protected91 */92Blockly.MetricsManager.prototype.getDimensionsPx_ = function(elem) {93 var width = 0;94 var height = 0;95 if (elem) {96 width = elem.getWidth();97 height = elem.getHeight();98 }99 return new Blockly.utils.Size(width, height);100};101/**102 * Gets the width and the height of the flyout on the workspace in pixel103 * coordinates. Returns 0 for the width and height if the workspace has a104 * category toolbox instead of a simple toolbox.105 * @param {boolean=} opt_own Whether to only return the workspace's own flyout.106 * @return {!Blockly.MetricsManager.ToolboxMetrics} The width and height of the107 * flyout.108 * @public109 */110Blockly.MetricsManager.prototype.getFlyoutMetrics = function(opt_own) {111 var flyoutDimensions =112 this.getDimensionsPx_(this.workspace_.getFlyout(opt_own));113 return {114 width: flyoutDimensions.width,115 height: flyoutDimensions.height,116 position: this.workspace_.toolboxPosition117 };118};119/**120 * Gets the width, height and position of the toolbox on the workspace in pixel121 * coordinates. Returns 0 for the width and height if the workspace has a simple122 * toolbox instead of a category toolbox. To get the width and height of a123 * simple toolbox @see {@link getFlyoutMetrics}.124 * @return {!Blockly.MetricsManager.ToolboxMetrics} The object with the width,125 * height and position of the toolbox.126 * @public127 */128Blockly.MetricsManager.prototype.getToolboxMetrics = function() {129 var toolboxDimensions = this.getDimensionsPx_(this.workspace_.getToolbox());130 return {131 width: toolboxDimensions.width,132 height: toolboxDimensions.height,133 position: this.workspace_.toolboxPosition134 };135};136/**137 * Gets the width and height of the workspace's parent SVG element in pixel138 * coordinates. This area includes the toolbox and the visible workspace area.139 * @return {!Blockly.utils.Size} The width and height of the workspace's parent140 * SVG element.141 * @public142 */143Blockly.MetricsManager.prototype.getSvgMetrics = function() {144 return this.workspace_.getCachedParentSvgSize();145};146/**147 * Gets the absolute left and absolute top in pixel coordinates.148 * This is where the visible workspace starts in relation to the SVG container.149 * @return {!Blockly.MetricsManager.AbsoluteMetrics} The absolute metrics for150 * the workspace.151 * @public152 */153Blockly.MetricsManager.prototype.getAbsoluteMetrics = function() {154 var absoluteLeft = 0;155 var toolboxMetrics = this.getToolboxMetrics();156 var flyoutMetrics = this.getFlyoutMetrics(true);157 var doesToolboxExist = !!this.workspace_.getToolbox();158 var doesFlyoutExist = !!this.workspace_.getFlyout(true);159 var toolboxPosition =160 doesToolboxExist ? toolboxMetrics.position : flyoutMetrics.position;161 var atLeft = toolboxPosition == Blockly.utils.toolbox.Position.LEFT;162 var atTop = toolboxPosition == Blockly.utils.toolbox.Position.TOP;163 if (doesToolboxExist && atLeft) {164 absoluteLeft = toolboxMetrics.width;165 } else if (doesFlyoutExist && atLeft) {166 absoluteLeft = flyoutMetrics.width;167 }168 var absoluteTop = 0;169 if (doesToolboxExist && atTop) {170 absoluteTop = toolboxMetrics.height;171 } else if (doesFlyoutExist && atTop) {172 absoluteTop = flyoutMetrics.height;173 }174 return {175 top: absoluteTop,176 left: absoluteLeft,177 };178};179/**180 * Gets the metrics for the visible workspace in either pixel or workspace181 * coordinates. The visible workspace does not include the toolbox or flyout.182 * @param {boolean=} opt_getWorkspaceCoordinates True to get the view metrics in183 * workspace coordinates, false to get them in pixel coordinates.184 * @return {!Blockly.MetricsManager.ContainerRegion} The width, height, top and185 * left of the viewport in either workspace coordinates or pixel186 * coordinates.187 * @public188 */189Blockly.MetricsManager.prototype.getViewMetrics = function(190 opt_getWorkspaceCoordinates) {191 var scale = opt_getWorkspaceCoordinates ? this.workspace_.scale : 1;192 var svgMetrics = this.getSvgMetrics();193 var toolboxMetrics = this.getToolboxMetrics();194 var flyoutMetrics = this.getFlyoutMetrics(true);195 var doesToolboxExist = !!this.workspace_.getToolbox();196 var toolboxPosition =197 doesToolboxExist ? toolboxMetrics.position : flyoutMetrics.position;198 if (this.workspace_.getToolbox()) {199 if (toolboxPosition == Blockly.utils.toolbox.Position.TOP ||200 toolboxPosition == Blockly.utils.toolbox.Position.BOTTOM) {201 svgMetrics.height -= toolboxMetrics.height;202 } else if (toolboxPosition == Blockly.utils.toolbox.Position.LEFT ||203 toolboxPosition == Blockly.utils.toolbox.Position.RIGHT) {204 svgMetrics.width -= toolboxMetrics.width;205 }206 } else if (this.workspace_.getFlyout(true)) {207 if (toolboxPosition == Blockly.utils.toolbox.Position.TOP ||208 toolboxPosition == Blockly.utils.toolbox.Position.BOTTOM) {209 svgMetrics.height -= flyoutMetrics.height;210 } else if (toolboxPosition == Blockly.utils.toolbox.Position.LEFT ||211 toolboxPosition == Blockly.utils.toolbox.Position.RIGHT) {212 svgMetrics.width -= flyoutMetrics.width;213 }214 }215 return {216 height: svgMetrics.height / scale,217 width: svgMetrics.width / scale,218 top: -this.workspace_.scrollY / scale,219 left: -this.workspace_.scrollX / scale,220 };221};222/**223 * Gets content metrics in either pixel or workspace coordinates.224 * The content area is a rectangle around all the top bounded elements on the225 * workspace (workspace comments and blocks).226 * @param {boolean=} opt_getWorkspaceCoordinates True to get the content metrics227 * in workspace coordinates, false to get them in pixel coordinates.228 * @return {!Blockly.MetricsManager.ContainerRegion} The229 * metrics for the content container.230 * @public231 */232Blockly.MetricsManager.prototype.getContentMetrics = function(233 opt_getWorkspaceCoordinates) {234 var scale = opt_getWorkspaceCoordinates ? 1 : this.workspace_.scale;235 // Block bounding box is in workspace coordinates.236 var blockBox = this.workspace_.getBlocksBoundingBox();237 return {238 height: (blockBox.bottom - blockBox.top) * scale,239 width: (blockBox.right - blockBox.left) * scale,240 top: blockBox.top * scale,241 left: blockBox.left * scale,242 };243};244/**245 * Returns whether the scroll area has fixed edges.246 * @return {boolean} Whether the scroll area has fixed edges.247 * @package248 */249Blockly.MetricsManager.prototype.hasFixedEdges = function() {250 // This exists for optimization of bump logic.251 return !this.workspace_.isMovableHorizontally() ||252 !this.workspace_.isMovableVertically();253};254/**255 * Computes the fixed edges of the scroll area.256 * @param {!Blockly.MetricsManager.ContainerRegion=} opt_viewMetrics The view257 * metrics if they have been previously computed. Passing in null may cause258 * the view metrics to be computed again, if it is needed.259 * @return {!Blockly.MetricsManager.FixedEdges} The fixed edges of the scroll260 * area.261 * @protected262 */263Blockly.MetricsManager.prototype.getComputedFixedEdges_ = function(264 opt_viewMetrics) {265 if (!this.hasFixedEdges()) {266 // Return early if there are no edges.267 return {};268 }269 var hScrollEnabled = this.workspace_.isMovableHorizontally();270 var vScrollEnabled = this.workspace_.isMovableVertically();271 var viewMetrics = opt_viewMetrics || this.getViewMetrics(false);272 var edges = {};273 if (!vScrollEnabled) {274 edges.top = viewMetrics.top;275 edges.bottom = viewMetrics.top + viewMetrics.height;276 }277 if (!hScrollEnabled) {278 edges.left = viewMetrics.left;279 edges.right = viewMetrics.left + viewMetrics.width;280 }281 return edges;282};283/**284 * Returns the content area with added padding.285 * @param {!Blockly.MetricsManager.ContainerRegion} viewMetrics The view286 * metrics.287 * @param {!Blockly.MetricsManager.ContainerRegion} contentMetrics The content288 * metrics.289 * @return {{top: number, bottom: number, left: number, right: number}} The290 * padded content area.291 * @protected292 */293Blockly.MetricsManager.prototype.getPaddedContent_ = function(294 viewMetrics, contentMetrics) {295 var contentBottom = contentMetrics.top + contentMetrics.height;296 var contentRight = contentMetrics.left + contentMetrics.width;297 var viewWidth = viewMetrics.width;298 var viewHeight = viewMetrics.height;299 var halfWidth = viewWidth / 2;300 var halfHeight = viewHeight / 2;301 // Add a padding around the content that is at least half a screen wide.302 // Ensure padding is wide enough that blocks can scroll over entire screen.303 var top =304 Math.min(contentMetrics.top - halfHeight, contentBottom - viewHeight);305 var left =306 Math.min(contentMetrics.left - halfWidth, contentRight - viewWidth);307 var bottom =308 Math.max(contentBottom + halfHeight, contentMetrics.top + viewHeight);309 var right =310 Math.max(contentRight + halfWidth, contentMetrics.left + viewWidth);311 return {top: top, bottom: bottom, left: left, right: right};312};313/**314 * Returns the metrics for the scroll area of the workspace.315 * @param {boolean=} opt_getWorkspaceCoordinates True to get the scroll metrics316 * in workspace coordinates, false to get them in pixel coordinates.317 * @param {!Blockly.MetricsManager.ContainerRegion=} opt_viewMetrics The view318 * metrics if they have been previously computed. Passing in null may cause319 * the view metrics to be computed again, if it is needed.320 * @param {!Blockly.MetricsManager.ContainerRegion=} opt_contentMetrics The321 * content metrics if they have been previously computed. Passing in null322 * may cause the content metrics to be computed again, if it is needed.323 * @return {!Blockly.MetricsManager.ContainerRegion} The metrics for the scroll324 * container.325 */326Blockly.MetricsManager.prototype.getScrollMetrics = function(327 opt_getWorkspaceCoordinates, opt_viewMetrics, opt_contentMetrics) {328 var scale = opt_getWorkspaceCoordinates ? this.workspace_.scale : 1;329 var viewMetrics = opt_viewMetrics || this.getViewMetrics(false);330 var contentMetrics = opt_contentMetrics || this.getContentMetrics();331 var fixedEdges = this.getComputedFixedEdges_(viewMetrics);332 // Add padding around content.333 var paddedContent = this.getPaddedContent_(viewMetrics, contentMetrics);334 // Use combination of fixed bounds and padded content to make scroll area.335 var top = fixedEdges.top !== undefined ?336 fixedEdges.top : paddedContent.top;337 var left = fixedEdges.left !== undefined ?338 fixedEdges.left : paddedContent.left;339 var bottom = fixedEdges.bottom !== undefined ?340 fixedEdges.bottom : paddedContent.bottom;341 var right = fixedEdges.right !== undefined ?342 fixedEdges.right : paddedContent.right;343 return {344 top: top / scale,345 left: left / scale,346 width: (right - left) / scale,347 height: (bottom - top) / scale,348 };349};350/**351 * Returns common metrics used by UI elements.352 * @return {!Blockly.MetricsManager.UiMetrics} The UI metrics.353 */354Blockly.MetricsManager.prototype.getUiMetrics = function() {355 return {356 viewMetrics: this.getViewMetrics(),357 absoluteMetrics: this.getAbsoluteMetrics(),358 toolboxMetrics: this.getToolboxMetrics()359 };360};361/**362 * Returns an object with all the metrics required to size scrollbars for a363 * top level workspace. The following properties are computed:364 * Coordinate system: pixel coordinates, -left, -up, +right, +down365 * .viewHeight: Height of the visible portion of the workspace.366 * .viewWidth: Width of the visible portion of the workspace.367 * .contentHeight: Height of the content.368 * .contentWidth: Width of the content.369 * .scrollHeight: Height of the scroll area.370 * .scrollWidth: Width of the scroll area.371 * .svgHeight: Height of the Blockly div (the view + the toolbox,372 * simple or otherwise),373 * .svgWidth: Width of the Blockly div (the view + the toolbox,374 * simple or otherwise),375 * .viewTop: Top-edge of the visible portion of the workspace, relative to376 * the workspace origin.377 * .viewLeft: Left-edge of the visible portion of the workspace, relative to378 * the workspace origin.379 * .contentTop: Top-edge of the content, relative to the workspace origin.380 * .contentLeft: Left-edge of the content relative to the workspace origin.381 * .scrollTop: Top-edge of the scroll area, relative to the workspace origin.382 * .scrollLeft: Left-edge of the scroll area relative to the workspace origin.383 * .absoluteTop: Top-edge of the visible portion of the workspace, relative384 * to the blocklyDiv.385 * .absoluteLeft: Left-edge of the visible portion of the workspace, relative386 * to the blocklyDiv.387 * .toolboxWidth: Width of the toolbox, if it exists. Otherwise zero.388 * .toolboxHeight: Height of the toolbox, if it exists. Otherwise zero.389 * .flyoutWidth: Width of the flyout if it is always open. Otherwise zero.390 * .flyoutHeight: Height of the flyout if it is always open. Otherwise zero.391 * .toolboxPosition: Top, bottom, left or right. Use TOOLBOX_AT constants to392 * compare.393 * @return {!Blockly.utils.Metrics} Contains size and position metrics of a top394 * level workspace.395 * @public396 */397Blockly.MetricsManager.prototype.getMetrics = function() {398 var toolboxMetrics = this.getToolboxMetrics();399 var flyoutMetrics = this.getFlyoutMetrics(true);400 var svgMetrics = this.getSvgMetrics();401 var absoluteMetrics = this.getAbsoluteMetrics();402 var viewMetrics = this.getViewMetrics();403 var contentMetrics = this.getContentMetrics();404 var scrollMetrics = this.getScrollMetrics(false, viewMetrics, contentMetrics);405 return {406 contentHeight: contentMetrics.height,407 contentWidth: contentMetrics.width,408 contentTop: contentMetrics.top,409 contentLeft: contentMetrics.left,410 scrollHeight: scrollMetrics.height,411 scrollWidth: scrollMetrics.width,412 scrollTop: scrollMetrics.top,413 scrollLeft: scrollMetrics.left,414 viewHeight: viewMetrics.height,415 viewWidth: viewMetrics.width,416 viewTop: viewMetrics.top,417 viewLeft: viewMetrics.left,418 absoluteTop: absoluteMetrics.top,419 absoluteLeft: absoluteMetrics.left,420 svgHeight: svgMetrics.height,421 svgWidth: svgMetrics.width,422 toolboxWidth: toolboxMetrics.width,423 toolboxHeight: toolboxMetrics.height,424 toolboxPosition: toolboxMetrics.position,425 flyoutWidth: flyoutMetrics.width,426 flyoutHeight: flyoutMetrics.height427 };428};429Blockly.registry.register(430 Blockly.registry.Type.METRICS_MANAGER, Blockly.registry.DEFAULT,431 Blockly.MetricsManager);432/**433 * Calculates metrics for a flyout's workspace.434 * The metrics are mainly used to size scrollbars for the flyout.435 * @param {!Blockly.WorkspaceSvg} workspace The flyout's workspace.436 * @param {!Blockly.IFlyout} flyout The flyout.437 * @extends {Blockly.MetricsManager}438 * @constructor439 */440Blockly.FlyoutMetricsManager = function(workspace, flyout) {441 /**442 * The flyout that owns the workspace to calculate metrics for.443 * @type {!Blockly.IFlyout}444 * @protected445 */446 this.flyout_ = flyout;447 Blockly.FlyoutMetricsManager.superClass_.constructor.call(this, workspace);448};449Blockly.utils.object.inherits(450 Blockly.FlyoutMetricsManager, Blockly.MetricsManager);451/**452 * Gets the bounding box of the blocks on the flyout's workspace.453 * This is in workspace coordinates.454 * @return {!SVGRect|{height: number, y: number, width: number, x: number}} The455 * bounding box of the blocks on the workspace.456 * @private457 */458Blockly.FlyoutMetricsManager.prototype.getBoundingBox_ = function() {459 try {460 var blockBoundingBox = this.workspace_.getCanvas().getBBox();461 } catch (e) {462 // Firefox has trouble with hidden elements (Bug 528969).463 // 2021 Update: It looks like this was fixed around Firefox 77 released in464 // 2020.465 var blockBoundingBox = {height: 0, y: 0, width: 0, x: 0};466 }467 return blockBoundingBox;468};469/**470 * @override471 */472Blockly.FlyoutMetricsManager.prototype.getContentMetrics = function(473 opt_getWorkspaceCoordinates) {474 // The bounding box is in workspace coordinates.475 var blockBoundingBox = this.getBoundingBox_();476 var scale = opt_getWorkspaceCoordinates ? 1 : this.workspace_.scale;477 return {478 height: blockBoundingBox.height * scale,479 width: blockBoundingBox.width * scale,480 top: blockBoundingBox.y * scale,481 left: blockBoundingBox.x * scale,482 };483};484/**485 * @override486 */487Blockly.FlyoutMetricsManager.prototype.getScrollMetrics = function(488 opt_getWorkspaceCoordinates, opt_viewMetrics, opt_contentMetrics) {489 var contentMetrics = opt_contentMetrics || this.getContentMetrics();490 var margin = this.flyout_.MARGIN * this.workspace_.scale;491 var scale = opt_getWorkspaceCoordinates ? this.workspace_.scale : 1;492 // The left padding isn't just the margin. Some blocks are also offset by493 // tabWidth so that value and statement blocks line up.494 // The contentMetrics.left value is equivalent to the variable left padding.495 var leftPadding = contentMetrics.left;496 return {497 height: (contentMetrics.height + 2 * margin) / scale,498 width: (contentMetrics.width + leftPadding + margin) / scale,499 top: 0,500 left: 0,501 };...

Full Screen

Full Screen

prometheus_metrics_spec.js

Source:prometheus_metrics_spec.js Github

copy

Full Screen

1import MockAdapter from 'axios-mock-adapter';2import axios from '~/lib/utils/axios_utils';3import PrometheusMetrics from '~/prometheus_metrics/prometheus_metrics';4import PANEL_STATE from '~/prometheus_metrics/constants';5import { metrics2 as metrics, missingVarMetrics } from './mock_data';6describe('PrometheusMetrics', () => {7 const FIXTURE = 'services/prometheus/prometheus_service.html';8 preloadFixtures(FIXTURE);9 beforeEach(() => {10 loadFixtures(FIXTURE);11 });12 describe('constructor', () => {13 let prometheusMetrics;14 beforeEach(() => {15 prometheusMetrics = new PrometheusMetrics('.js-prometheus-metrics-monitoring');16 });17 it('should initialize wrapper element refs on class object', () => {18 expect(prometheusMetrics.$wrapper).toBeDefined();19 expect(prometheusMetrics.$monitoredMetricsPanel).toBeDefined();20 expect(prometheusMetrics.$monitoredMetricsCount).toBeDefined();21 expect(prometheusMetrics.$monitoredMetricsLoading).toBeDefined();22 expect(prometheusMetrics.$monitoredMetricsEmpty).toBeDefined();23 expect(prometheusMetrics.$monitoredMetricsList).toBeDefined();24 expect(prometheusMetrics.$missingEnvVarPanel).toBeDefined();25 expect(prometheusMetrics.$panelToggle).toBeDefined();26 expect(prometheusMetrics.$missingEnvVarMetricCount).toBeDefined();27 expect(prometheusMetrics.$missingEnvVarMetricsList).toBeDefined();28 });29 it('should initialize metadata on class object', () => {30 expect(prometheusMetrics.backOffRequestCounter).toEqual(0);31 expect(prometheusMetrics.activeMetricsEndpoint).toContain('/test');32 });33 });34 describe('showMonitoringMetricsPanelState', () => {35 let prometheusMetrics;36 beforeEach(() => {37 prometheusMetrics = new PrometheusMetrics('.js-prometheus-metrics-monitoring');38 });39 it('should show loading state when called with `loading`', () => {40 prometheusMetrics.showMonitoringMetricsPanelState(PANEL_STATE.LOADING);41 expect(prometheusMetrics.$monitoredMetricsLoading.hasClass('hidden')).toBeFalsy();42 expect(prometheusMetrics.$monitoredMetricsEmpty.hasClass('hidden')).toBeTruthy();43 expect(prometheusMetrics.$monitoredMetricsList.hasClass('hidden')).toBeTruthy();44 });45 it('should show metrics list when called with `list`', () => {46 prometheusMetrics.showMonitoringMetricsPanelState(PANEL_STATE.LIST);47 expect(prometheusMetrics.$monitoredMetricsLoading.hasClass('hidden')).toBeTruthy();48 expect(prometheusMetrics.$monitoredMetricsEmpty.hasClass('hidden')).toBeTruthy();49 expect(prometheusMetrics.$monitoredMetricsList.hasClass('hidden')).toBeFalsy();50 });51 it('should show empty state when called with `empty`', () => {52 prometheusMetrics.showMonitoringMetricsPanelState(PANEL_STATE.EMPTY);53 expect(prometheusMetrics.$monitoredMetricsLoading.hasClass('hidden')).toBeTruthy();54 expect(prometheusMetrics.$monitoredMetricsEmpty.hasClass('hidden')).toBeFalsy();55 expect(prometheusMetrics.$monitoredMetricsList.hasClass('hidden')).toBeTruthy();56 });57 });58 describe('populateActiveMetrics', () => {59 let prometheusMetrics;60 beforeEach(() => {61 prometheusMetrics = new PrometheusMetrics('.js-prometheus-metrics-monitoring');62 });63 it('should show monitored metrics list', () => {64 prometheusMetrics.populateActiveMetrics(metrics);65 const $metricsListLi = prometheusMetrics.$monitoredMetricsList.find('li');66 expect(prometheusMetrics.$monitoredMetricsLoading.hasClass('hidden')).toBeTruthy();67 expect(prometheusMetrics.$monitoredMetricsList.hasClass('hidden')).toBeFalsy();68 expect(prometheusMetrics.$monitoredMetricsCount.text()).toEqual(69 '3 exporters with 12 metrics were found',70 );71 expect($metricsListLi.length).toEqual(metrics.length);72 expect(73 $metricsListLi74 .first()75 .find('.badge')76 .text(),77 ).toEqual(`${metrics[0].active_metrics}`);78 });79 it('should show missing environment variables list', () => {80 prometheusMetrics.populateActiveMetrics(missingVarMetrics);81 expect(prometheusMetrics.$monitoredMetricsLoading.hasClass('hidden')).toBeTruthy();82 expect(prometheusMetrics.$missingEnvVarPanel.hasClass('hidden')).toBeFalsy();83 expect(prometheusMetrics.$missingEnvVarMetricCount.text()).toEqual('2');84 expect(prometheusMetrics.$missingEnvVarPanel.find('li').length).toEqual(2);85 expect(prometheusMetrics.$missingEnvVarPanel.find('.flash-container')).toBeDefined();86 });87 });88 describe('loadActiveMetrics', () => {89 let prometheusMetrics;90 let mock;91 function mockSuccess() {92 mock.onGet(prometheusMetrics.activeMetricsEndpoint).reply(200, {93 data: metrics,94 success: true,95 });96 }97 function mockError() {98 mock.onGet(prometheusMetrics.activeMetricsEndpoint).networkError();99 }100 beforeEach(() => {101 jest.spyOn(axios, 'get');102 prometheusMetrics = new PrometheusMetrics('.js-prometheus-metrics-monitoring');103 mock = new MockAdapter(axios);104 });105 afterEach(() => {106 mock.restore();107 });108 it('should show loader animation while response is being loaded and hide it when request is complete', done => {109 mockSuccess();110 prometheusMetrics.loadActiveMetrics();111 expect(prometheusMetrics.$monitoredMetricsLoading.hasClass('hidden')).toBeFalsy();112 expect(axios.get).toHaveBeenCalledWith(prometheusMetrics.activeMetricsEndpoint);113 setImmediate(() => {114 expect(prometheusMetrics.$monitoredMetricsLoading.hasClass('hidden')).toBeTruthy();115 done();116 });117 });118 it('should show empty state if response failed to load', done => {119 mockError();120 prometheusMetrics.loadActiveMetrics();121 setImmediate(() => {122 expect(prometheusMetrics.$monitoredMetricsLoading.hasClass('hidden')).toBeTruthy();123 expect(prometheusMetrics.$monitoredMetricsEmpty.hasClass('hidden')).toBeFalsy();124 done();125 });126 });127 it('should populate metrics list once response is loaded', done => {128 jest.spyOn(prometheusMetrics, 'populateActiveMetrics').mockImplementation();129 mockSuccess();130 prometheusMetrics.loadActiveMetrics();131 setImmediate(() => {132 expect(prometheusMetrics.populateActiveMetrics).toHaveBeenCalledWith(metrics);133 done();134 });135 });136 });...

Full Screen

Full Screen

nsolid-probe.js

Source:nsolid-probe.js Github

copy

Full Screen

...74 agent.timers.setInterval(collectMetrics, 30000);75 collectMetrics();76 var cpuSpeedRecorded = false;77 function collectMetrics() {78 nsolid.metrics(function (err, results) {79 if (err) {80 agent.logger.warn('failed to retrieve N|Solid metrics: ' + err.message);81 return;82 }83 for (metric in METRIC_REPORTERS) {84 self.metrics[metric].addValue(METRIC_REPORTERS[metric](results));85 }86 // CPU speed is reported as a metric but, since it's constant,87 // we report it as agent metadata instead88 if (!cpuSpeedRecorded) {89 cpuSpeedRecorded = true;90 agent.meta.push({ name: 'CPU Speed', value: results.cpuSpeed });91 }92 });...

Full Screen

Full Screen

custom_metrics_spec.js

Source:custom_metrics_spec.js Github

copy

Full Screen

1import MockAdapter from 'axios-mock-adapter';2import CustomMetrics from '~/prometheus_metrics/custom_metrics';3import axios from '~/lib/utils/axios_utils';4import PANEL_STATE from '~/prometheus_metrics/constants';5import { metrics1 as metrics } from './mock_data';6describe('PrometheusMetrics', () => {7 const FIXTURE = 'services/prometheus/prometheus_service.html';8 const customMetricsEndpoint =9 'http://test.host/frontend-fixtures/services-project/prometheus/metrics';10 let mock;11 preloadFixtures(FIXTURE);12 beforeEach(() => {13 mock = new MockAdapter(axios);14 mock.onGet(customMetricsEndpoint).reply(200, {15 metrics,16 });17 loadFixtures(FIXTURE);18 });19 afterEach(() => {20 mock.restore();21 });22 describe('Custom Metrics', () => {23 let customMetrics;24 beforeEach(() => {25 customMetrics = new CustomMetrics('.js-prometheus-metrics-monitoring');26 });27 it('should initialize wrapper element refs on the class object', () => {28 expect(customMetrics.$wrapperCustomMetrics).not.toBeNull();29 expect(customMetrics.$monitoredCustomMetricsPanel).not.toBeNull();30 expect(customMetrics.$monitoredCustomMetricsCount).not.toBeNull();31 expect(customMetrics.$monitoredCustomMetricsLoading).not.toBeNull();32 expect(customMetrics.$monitoredCustomMetricsEmpty).not.toBeNull();33 expect(customMetrics.$monitoredCustomMetricsList).not.toBeNull();34 expect(customMetrics.$newCustomMetricButton).not.toBeNull();35 expect(customMetrics.$flashCustomMetricsContainer).not.toBeNull();36 });37 it('should contain api endpoints', () => {38 expect(customMetrics.activeCustomMetricsEndpoint).toEqual(customMetricsEndpoint);39 });40 it('should show loading state when called with `loading`', () => {41 customMetrics.showMonitoringCustomMetricsPanelState(PANEL_STATE.LOADING);42 expect(customMetrics.$monitoredCustomMetricsLoading.hasClass('hidden')).toEqual(false);43 expect(customMetrics.$monitoredCustomMetricsEmpty.hasClass('hidden')).toBeTruthy();44 expect(customMetrics.$monitoredCustomMetricsList.hasClass('hidden')).toBeTruthy();45 expect(46 customMetrics.$monitoredCustomMetricsNoIntegrationText.hasClass('hidden'),47 ).toBeTruthy();48 expect(customMetrics.$newCustomMetricButton.hasClass('hidden')).toBeTruthy();49 expect(customMetrics.$newCustomMetricText.hasClass('hidden')).toBeTruthy();50 });51 it('should show metrics list when called with `list`', () => {52 customMetrics.showMonitoringCustomMetricsPanelState(PANEL_STATE.LIST);53 expect(customMetrics.$monitoredCustomMetricsLoading.hasClass('hidden')).toBeTruthy();54 expect(customMetrics.$monitoredCustomMetricsEmpty.hasClass('hidden')).toBeTruthy();55 expect(customMetrics.$monitoredCustomMetricsList.hasClass('hidden')).toEqual(false);56 expect(57 customMetrics.$monitoredCustomMetricsNoIntegrationText.hasClass('hidden'),58 ).toBeTruthy();59 expect(customMetrics.$newCustomMetricButton.hasClass('hidden')).toEqual(false);60 expect(customMetrics.$newCustomMetricText.hasClass('hidden')).toBeTruthy();61 });62 it('should show empty state when called with `empty`', () => {63 customMetrics.showMonitoringCustomMetricsPanelState(PANEL_STATE.EMPTY);64 expect(customMetrics.$monitoredCustomMetricsLoading.hasClass('hidden')).toBeTruthy();65 expect(customMetrics.$monitoredCustomMetricsEmpty.hasClass('hidden')).toEqual(false);66 expect(customMetrics.$monitoredCustomMetricsList.hasClass('hidden')).toBeTruthy();67 expect(68 customMetrics.$monitoredCustomMetricsNoIntegrationText.hasClass('hidden'),69 ).toBeTruthy();70 expect(customMetrics.$newCustomMetricButton.hasClass('hidden')).toEqual(false);71 expect(customMetrics.$newCustomMetricText.hasClass('hidden')).toEqual(false);72 });73 it('should show monitored metrics list', () => {74 customMetrics.customMetrics = metrics;75 customMetrics.populateCustomMetrics();76 const $metricsListLi = customMetrics.$monitoredCustomMetricsList.find('li');77 expect(customMetrics.$monitoredCustomMetricsLoading.hasClass('hidden')).toBeTruthy();78 expect(customMetrics.$monitoredCustomMetricsList.hasClass('hidden')).toEqual(false);79 expect(80 customMetrics.$monitoredCustomMetricsNoIntegrationText.hasClass('hidden'),81 ).toBeTruthy();82 expect(customMetrics.$newCustomMetricButton.hasClass('hidden')).toEqual(false);83 expect(customMetrics.$newCustomMetricText.hasClass('hidden')).toBeTruthy();84 expect($metricsListLi.length).toEqual(metrics.length);85 });86 it('should show the NO-INTEGRATION empty state', () => {87 customMetrics.setNoIntegrationActiveState();88 expect(customMetrics.$monitoredCustomMetricsEmpty.hasClass('hidden')).toEqual(false);89 expect(customMetrics.$monitoredCustomMetricsNoIntegrationText.hasClass('hidden')).toEqual(90 false,91 );92 expect(customMetrics.$monitoredCustomMetricsLoading.hasClass('hidden')).toBeTruthy();93 expect(customMetrics.$monitoredCustomMetricsList.hasClass('hidden')).toBeTruthy();94 expect(customMetrics.$newCustomMetricButton.hasClass('hidden')).toBeTruthy();95 expect(customMetrics.$newCustomMetricText.hasClass('hidden')).toBeTruthy();96 });97 });...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1import IndexedArray from 'ui/indexed_array';2import 'ui/agg_types/agg_params';3import AggTypesMetricsCountProvider from 'ui/agg_types/metrics/count';4import AggTypesMetricsAvgProvider from 'ui/agg_types/metrics/avg';5import AggTypesMetricsSumProvider from 'ui/agg_types/metrics/sum';6import AggTypesMetricsMedianProvider from 'ui/agg_types/metrics/median';7import AggTypesMetricsMinProvider from 'ui/agg_types/metrics/min';8import AggTypesMetricsMaxProvider from 'ui/agg_types/metrics/max';9import AggTypesMetricsTopHitProvider from 'ui/agg_types/metrics/top_hit';10import AggTypesMetricsStdDeviationProvider from 'ui/agg_types/metrics/std_deviation';11import AggTypesMetricsCardinalityProvider from 'ui/agg_types/metrics/cardinality';12import AggTypesMetricsPercentilesProvider from 'ui/agg_types/metrics/percentiles';13import AggTypesMetricsGeoCentroidProvider from 'ui/agg_types/metrics/geo_centroid';14import AggTypesMetricsPercentileRanksProvider from 'ui/agg_types/metrics/percentile_ranks';15import AggTypesMetricsDerivativeProvider from 'ui/agg_types/metrics/derivative';16import AggTypesMetricsCumulativeSumProvider from 'ui/agg_types/metrics/cumulative_sum';17import AggTypesMetricsMovingAvgProvider from 'ui/agg_types/metrics/moving_avg';18import AggTypesMetricsSerialDiffProvider from 'ui/agg_types/metrics/serial_diff';19import AggTypesBucketsDateHistogramProvider from 'ui/agg_types/buckets/date_histogram';20import AggTypesBucketsHistogramProvider from 'ui/agg_types/buckets/histogram';21import AggTypesBucketsRangeProvider from 'ui/agg_types/buckets/range';22import AggTypesBucketsDateRangeProvider from 'ui/agg_types/buckets/date_range';23import AggTypesBucketsIpRangeProvider from 'ui/agg_types/buckets/ip_range';24import AggTypesBucketsTermsProvider from 'ui/agg_types/buckets/terms';25import AggTypesBucketsFiltersProvider from 'ui/agg_types/buckets/filters';26import AggTypesBucketsSignificantTermsProvider from 'ui/agg_types/buckets/significant_terms';27import AggTypesBucketsGeoHashProvider from 'ui/agg_types/buckets/geo_hash';28import AggTypesMetricsBucketSumProvider from 'ui/agg_types/metrics/bucket_sum';29import AggTypesMetricsBucketAvgProvider from 'ui/agg_types/metrics/bucket_avg';30import AggTypesMetricsBucketMinProvider from 'ui/agg_types/metrics/bucket_min';31import AggTypesMetricsBucketMaxProvider from 'ui/agg_types/metrics/bucket_max';32import 'ui/directives/validate_agg';33export default function AggTypeService(Private) {34 const aggs = {35 metrics: [36 Private(AggTypesMetricsCountProvider),37 Private(AggTypesMetricsAvgProvider),38 Private(AggTypesMetricsSumProvider),39 Private(AggTypesMetricsMedianProvider),40 Private(AggTypesMetricsMinProvider),41 Private(AggTypesMetricsMaxProvider),42 Private(AggTypesMetricsStdDeviationProvider),43 Private(AggTypesMetricsCardinalityProvider),44 Private(AggTypesMetricsPercentilesProvider),45 Private(AggTypesMetricsPercentileRanksProvider),46 Private(AggTypesMetricsTopHitProvider),47 Private(AggTypesMetricsDerivativeProvider),48 Private(AggTypesMetricsCumulativeSumProvider),49 Private(AggTypesMetricsMovingAvgProvider),50 Private(AggTypesMetricsSerialDiffProvider),51 Private(AggTypesMetricsBucketAvgProvider),52 Private(AggTypesMetricsBucketSumProvider),53 Private(AggTypesMetricsBucketMinProvider),54 Private(AggTypesMetricsBucketMaxProvider),55 Private(AggTypesMetricsGeoCentroidProvider)56 ],57 buckets: [58 Private(AggTypesBucketsDateHistogramProvider),59 Private(AggTypesBucketsHistogramProvider),60 Private(AggTypesBucketsRangeProvider),61 Private(AggTypesBucketsDateRangeProvider),62 Private(AggTypesBucketsIpRangeProvider),63 Private(AggTypesBucketsTermsProvider),64 Private(AggTypesBucketsFiltersProvider),65 Private(AggTypesBucketsSignificantTermsProvider),66 Private(AggTypesBucketsGeoHashProvider),67 ]68 };69 Object.keys(aggs).forEach(function (type) {70 aggs[type].forEach(function (agg) {71 agg.type = type;72 });73 });74 /**75 * IndexedArray of Aggregation Types.76 *77 * These types form two groups, metric and buckets.78 *79 * @module agg_types80 * @type {IndexedArray}81 */82 return new IndexedArray({83 /**84 * @type {Array}85 */86 index: ['name'],87 /**88 * [group description]89 * @type {Array}90 */91 group: ['type'],92 initialSet: aggs.metrics.concat(aggs.buckets)93 });94}...

Full Screen

Full Screen

DOMMetrics.js

Source:DOMMetrics.js Github

copy

Full Screen

1const React = require('react');2const shallowCloneObject = require('./shallowCloneObject');3let contextTypes = {4 metricsComputator: React.PropTypes.object5};6let MetricsComputatorMixin = {7 childContextTypes: contextTypes,8 getChildContext(): {metricsComputator: any} {9 return {metricsComputator: this};10 },11 getMetricImpl(name: string): any {12 return this._DOMMetrics.metrics[name].value;13 },14 registerMetricsImpl(component: ReactComponent, metrics: any): {[key:string]: any} {15 let getters = {};16 let s = this._DOMMetrics;17 for (let name in metrics) {18 if (s.metrics[name] !== undefined) {19 throw new Error('DOM metric ' + name + ' is already defined');20 }21 s.metrics[name] = {component, computator: metrics[name].bind(component)};22 getters[name] = this.getMetricImpl.bind(null, name);23 }24 if (s.components.indexOf(component) === -1) {25 s.components.push(component);26 }27 return getters;28 },29 unregisterMetricsFor(component: ReactComponent) {30 let s = this._DOMMetrics;31 let idx = s.components.indexOf(component);32 if (idx > -1) {33 s.components.splice(idx, 1);34 let name;35 let metricsToDelete = {};36 for (name in s.metrics) {37 if (s.metrics[name].component === component) {38 metricsToDelete[name] = true;39 }40 }41 for (name in metricsToDelete) {42 if (metricsToDelete.hasOwnProperty(name)) {43 delete s.metrics[name];44 }45 }46 }47 },48 updateMetrics() {49 let s = this._DOMMetrics;50 let needUpdate = false;51 for (let name in s.metrics) {52 if (!s.metrics.hasOwnProperty(name)) continue;53 let newMetric = s.metrics[name].computator();54 if (newMetric !== s.metrics[name].value) {55 needUpdate = true;56 }57 s.metrics[name].value = newMetric;58 }59 if (needUpdate) {60 for (let i = 0, len = s.components.length; i < len; i++) {61 if (s.components[i].metricsUpdated) {62 s.components[i].metricsUpdated();63 }64 }65 }66 },67 componentWillMount() {68 this._DOMMetrics = {69 metrics: {},70 components: []71 };72 },73 componentDidMount() {74 if (window.addEventListener) {75 window.addEventListener('resize', this.updateMetrics);76 } else {77 window.attachEvent('resize', this.updateMetrics);78 }79 this.updateMetrics();80 },81 componentWillUnmount() {82 window.removeEventListener('resize', this.updateMetrics);83 }84};85let MetricsMixin = {86 contextTypes: contextTypes,87 componentWillMount() {88 if (this.DOMMetrics) {89 this._DOMMetricsDefs = shallowCloneObject(this.DOMMetrics);90 this.DOMMetrics = {};91 for (let name in this._DOMMetricsDefs) {92 if (!this._DOMMetricsDefs.hasOwnProperty(name)) continue;93 this.DOMMetrics[name] = () => {};94 }95 }96 },97 componentDidMount() {98 if (this.DOMMetrics) {99 this.DOMMetrics = this.registerMetrics(this._DOMMetricsDefs);100 }101 },102 componentWillUnmount(): any {103 if (!this.registerMetricsImpl) {104 return this.context.metricsComputator.unregisterMetricsFor(this);105 }106 if (this.hasOwnProperty('DOMMetrics')) {107 delete this.DOMMetrics;108 }109 },110 registerMetrics(metrics: any): any {111 if (this.registerMetricsImpl) {112 return this.registerMetricsImpl(this, metrics);113 }114 return this.context.metricsComputator.registerMetricsImpl(this, metrics);115 },116 getMetric(name: string): any {117 if (this.getMetricImpl) {118 return this.getMetricImpl(name);119 }120 return this.context.metricsComputator.getMetricImpl(name);121 }122};123module.exports = {124 MetricsComputatorMixin,125 MetricsMixin...

Full Screen

Full Screen

Metrics.js

Source:Metrics.js Github

copy

Full Screen

1// @if DEBUG2/**3* _Internal Class_, not generally used outside of the engine's internals.4*5*/6var Metrics = {};7module.exports = Metrics;8var Composite = require('../body/Composite');9var Common = require('./Common');10(function() {11 /**12 * Creates a new metrics.13 * @method create14 * @private15 * @return {metrics} A new metrics16 */17 Metrics.create = function(options) {18 var defaults = {19 extended: false,20 narrowDetections: 0,21 narrowphaseTests: 0,22 narrowReuse: 0,23 narrowReuseCount: 0,24 midphaseTests: 0,25 broadphaseTests: 0,26 narrowEff: 0.0001,27 midEff: 0.0001,28 broadEff: 0.0001,29 collisions: 0,30 buckets: 0,31 bodies: 0,32 pairs: 033 };34 return Common.extend(defaults, false, options);35 };36 /**37 * Resets metrics.38 * @method reset39 * @private40 * @param {metrics} metrics41 */42 Metrics.reset = function(metrics) {43 if (metrics.extended) {44 metrics.narrowDetections = 0;45 metrics.narrowphaseTests = 0;46 metrics.narrowReuse = 0;47 metrics.narrowReuseCount = 0;48 metrics.midphaseTests = 0;49 metrics.broadphaseTests = 0;50 metrics.narrowEff = 0;51 metrics.midEff = 0;52 metrics.broadEff = 0;53 metrics.collisions = 0;54 metrics.buckets = 0;55 metrics.pairs = 0;56 metrics.bodies = 0;57 }58 };59 /**60 * Updates metrics.61 * @method update62 * @private63 * @param {metrics} metrics64 * @param {engine} engine65 */66 Metrics.update = function(metrics, engine) {67 if (metrics.extended) {68 var world = engine.world,69 bodies = Composite.allBodies(world);70 metrics.collisions = metrics.narrowDetections;71 metrics.pairs = engine.pairs.list.length;72 metrics.bodies = bodies.length;73 metrics.midEff = (metrics.narrowDetections / (metrics.midphaseTests || 1)).toFixed(2);74 metrics.narrowEff = (metrics.narrowDetections / (metrics.narrowphaseTests || 1)).toFixed(2);75 metrics.broadEff = (1 - (metrics.broadphaseTests / (bodies.length || 1))).toFixed(2);76 metrics.narrowReuse = (metrics.narrowReuseCount / (metrics.narrowphaseTests || 1)).toFixed(2);77 //var broadphase = engine.broadphase[engine.broadphase.current];78 //if (broadphase.instance)79 // metrics.buckets = Common.keys(broadphase.instance.buckets).length;80 }81 };82})();...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var bestBuy = require('./bestBuy');2var myBestBuy = new bestBuy();3var myMetrics = myBestBuy.metrics();4console.log(myMetrics);5var BestBuy = function() {6 this.metrics = function() {7 return 'metrics';8 };9};10module.exports = BestBuy;11var bestBuy = require('./bestBuy');12var myBestBuy = new bestBuy();13var myMetrics = myBestBuy.metrics();14console.log(myMetrics);15var BestBuy = function() {16 this.metrics = function() {17 return 'metrics';18 };19};20module.exports = BestBuy;21The problem is that myBestBuy.metrics() is a function. It returns a function, not the function itself. So it should be:

Full Screen

Using AI Code Generation

copy

Full Screen

1var bestMatch = require('best-match');2var metrics = require('best-match/metrics');3var bm = bestMatch(metrics.cosineSimilarity);4var list = ['I like apples', 'I like oranges', 'I like bananas', 'I hate apples', 'I hate oranges', 'I hate bananas'];5var target = 'I like apples';6var result = bm(list, target);7console.log(result);8var bestMatch = require('best-match');9var metrics = require('best-match/metrics');10var bm = bestMatch(metrics.jaccardSimilarity);11var list = ['I like apples', 'I like oranges', 'I like bananas', 'I hate apples', 'I hate oranges', 'I hate bananas'];12var target = 'I like apples';13var result = bm(list, target);14console.log(result);15var bestMatch = require('best-match');16var metrics = require('best-match/metrics');17var bm = bestMatch(metrics.levenshteinDistance);18var list = ['I like apples', 'I like oranges', 'I like bananas', 'I hate apples', 'I hate oranges', 'I hate bananas'];19var target = 'I like apples';20var result = bm(list, target);21console.log(result);22var bestMatch = require('best-match');23var metrics = require('best-match/metrics');24var bm = bestMatch(metrics.needlemanWunsch);25var list = ['I like apples', 'I like oranges', 'I like bananas', 'I hate apples', 'I hate oranges', 'I hate bananas'];26var target = 'I like apples';27var result = bm(list, target);28console.log(result);

Full Screen

Using AI Code Generation

copy

Full Screen

1var request = require('request');2var queryParams = '?format=json&show=sku,name,salePrice&apiKey=6wz2yf2g6r8j7d7r6jx9g9p9';3var sku = process.argv[2];4request(url + queryParams + '&sku=' + sku, function(err, response, body) {5 if (err) {6 console.log(err);7 } else if (response.statusCode == 200) {8 var data = JSON.parse(body);9 console.log(data.products[0].name);10 }11});12var category = process.argv[2];13request(url + '(categoryPath.id=' + category + ')' + queryParams, function(err, response, body) {

Full Screen

Using AI Code Generation

copy

Full Screen

1import BestBuy from './BestBuy.js';2let bb = new BestBuy();3let metrics = [];4metrics = bb.metrics();5console.log("The average price of all items is $" + metrics[0]);6let category = prompt("Enter a category");7metrics = bb.metrics(category);8console.log("The average price of items in the " + category + " category is $" + metrics[0]);9console.log("There are " + metrics[1] + " items in the " + category + " category");10import Product from './Product.js';11class BestBuy {12 constructor() {13 this.products = [];14 this.products.push(new Product("TV", 499.99, "Electronics"));15 this.products.push(new Product("DVD Player", 149.99, "Electronics"));16 this.products.push(new Product("CD Player", 99.99, "Electronics"));17 this.products.push(new Product("VCR", 99.99, "Electronics"));18 this.products.push(new Product("Stereo", 199.99, "Electronics"));19 this.products.push(new Product("Socks", 9.99, "Clothing"));20 this.products.push(new Product("T-Shirt", 19.99, "Clothing"));21 this.products.push(new Product("Pants", 29.99, "Clothing"));22 this.products.push(new Product("Shoes", 49.99, "Clothing"));23 this.products.push(new Product("Hat", 19.99, "Clothing

Full Screen

Using AI Code Generation

copy

Full Screen

1var metrics = require('best-practices').metrics;2var n = 5;3var sum = 0;4for (var i = 1; i <= n; i++) {5 sum = sum + i;6}7console.log('sum = ' + sum);8var complexity = metrics.complexity(sum);9console.log('complexity = ' + complexity);10n = 10;11sum = 0;12for (var i = 1; i <= n; i++) {13 sum = sum + i;14}15console.log('sum = ' + sum);16complexity = metrics.complexity(sum);17console.log('complexity = ' + complexity);18n = 100;19sum = 0;20for (var i = 1; i <= n; i++) {21 sum = sum + i;22}23console.log('sum = ' + sum);24complexity = metrics.complexity(sum);25console.log('complexity = ' + complexity);26n = 1000;27sum = 0;28for (var i = 1; i <= n; i++) {29 sum = sum + i;30}31console.log('sum = ' + sum);32complexity = metrics.complexity(sum);33console.log('complexity = ' + complexity);34n = 10000;35sum = 0;36for (var i = 1; i <= n; i++) {37 sum = sum + i;38}39console.log('sum = ' + sum);40complexity = metrics.complexity(sum);41console.log('complexity = ' + complexity);42n = 100000;43sum = 0;44for (var i = 1; i <= n; i++) {45 sum = sum + i;46}47console.log('sum = ' + sum);

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 Best 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