How to use visitClass method in Playwright Internal

Best JavaScript code snippet using playwright-internal

Run Playwright Internal automation tests on LambdaTest cloud grid

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

escope.js

Source: escope.js Github

copy
1const referencer = require("escope/lib/referencer").default;
2
3const { visitClass, visitProperty } = referencer.prototype;
4
5// visit decorators on classes/properties to resolve their identifiers
6referencer.prototype.visitClass = function(node) {
7  visitDecorators.call(this, node);
8  visitClass.call(this, node);
9};
10
11referencer.prototype.visitProperty = function(node) {
12  visitDecorators.call(this, node);
13  visitProperty.call(this, node);
14};
15
16function visitDecorators(node) {
17  if (!node.decorators) {
18    return;
19  }
20  node.decorators.forEach(d => this.visit(d));
21}
22
23// register class properties by visiting them as regular properties
24referencer.prototype.ClassProperty = function(node) {
25  this.visitProperty(node);
26};
27
28module.exports = require("escope");
29
Full Screen

experiment.js

Source: experiment.js Github

copy
1var setup = {
2	
3	controllers: [
4		
5		//experimentController
6		{	name: 		"experimentController",
7		
8			taskTextButtonTime: 10,
9			taskTime: 5,
10		
11			stepOrder:	[ 	10, 20 ],
12						
13			steps:		[				
14							{ 	number:	10,
15								
16								text: 	[
17										"Willkommen beim Experiment LazyDog.",
18										"Im Folgenden Verlauf wird die Interaktion mit einer Visualisierung eines Softwaresystems untersucht.",
19										"Dazu lösen Sie 6 Aufgaben, bei denen die Zeit und die Fehlerrate gemessen wird.",
20										"Zunächst starten Sie jedoch mit einem Tutorial.",
21										"Betrachten Sie die Visualisierung kurz im Überblick und betätigen Sie anschließend die \"Aufgabe abgeschlossen!\"-Schaltfläche oben rechts zwei mal."
22								],		
23
24								ui: 	"UI0"
25							},
26							
27							{ 	number:	20,
28								
29								text: 	[
30										"Sie sehen die Darstellung des Softwaresystems als Stadt(City).",
31										"Klassen sind als dunkelblaue Gebäude in hellgrauen Stadtteilen, den Paketen, dargestellt.",
32										"Jedes hellblaue Stockwerk ist eine Methode und jeder gelber Schornstein auf dem Dach des Gebäudes ein Attribut.",
33										"Beim überfahren der Elemente mit der Maus wird der Name in einem Tooltip angezeigt.",
34										"Versuchen Sie sich in der Visualisierung zu bewegen und beenden Sie die Aufgabe wieder über die Schaltfläche."
35								],		
36
37								ui: 	"UI1",
38
39								entities : [
40									"edu_umd_cs_findbugs_visitclass_PreorderVisitor_className",
41									"edu_umd_cs_findbugs_visitclass_PreorderVisitor_dottedSuperclassName",
42									"edu_umd_cs_findbugs_visitclass_PreorderVisitor_superclassName",
43									"edu_umd_cs_findbugs_visitclass_PreorderVisitor_sourceFile",
44									"edu_umd_cs_findbugs_visitclass_PreorderVisitor_dottedClassName",
45									"edu_umd_cs_findbugs_visitclass_PreorderVisitor_thisClassInfo",
46									"edu_umd_cs_findbugs_visitclass_PreorderVisitor_packageName",
47									"edu_umd_cs_findbugs_FindBugs_isNoAnalysis___",
48									"edu_umd_cs_findbugs_classfile_DescriptorFactory_createClassDescriptor__java_lang_String_____"
49								]
50							},
51			]
52			
53		},
54
55		{ 	name: 	"defaultLogger",
56
57			logActionConsole	: false,
58			logEventConsole		: false
59		},		
60
61		
62		{	name: 	"canvasHoverController",
63		},
64
65		{	name: 	"canvasSelectController" 
66		},	
67
68		{ 	name: 	"canvasResetViewController" 
69		},
70		
71		
72	],
73	
74	
75	
76
77	uis: [
78
79		{	name: "UI0",
80		
81			navigation: {
82				//examine, walk, fly, helicopter, lookAt, turntable, game
83				type:	"none",
84				//speed: 10
85			},	
86					
87		
88							
89			area: {
90				name: "top",
91				orientation: "horizontal",
92				
93				first: {			
94					size: "200px",	
95					
96					controllers: [					
97						{ name: "experimentController" },
98						{ name: "canvasResetViewController" },
99					],							
100				},
101				second: {
102					size: "90%",	
103					collapsible: false,
104					
105					
106							
107					canvas: { },
108					
109					controllers: [
110						
111						{ name: "defaultLogger" },											
112
113					],						
114				}
115			}
116			
117		},
118
119		{	name: "UI1",
120		
121			navigation: {
122				//examine, walk, fly, helicopter, lookAt, turntable, game
123				type:	"examine",
124				//speed: 10
125			},	
126					
127		
128							
129			area: {
130				name: "top",
131				orientation: "horizontal",
132				
133				first: {			
134					size: "200px",	
135					
136					controllers: [	
137						{ name: "experimentController" },				
138						{ name: "canvasResetViewController" },
139					],							
140				},
141				second: {
142					size: "90%",	
143					collapsible: false,
144					
145					
146							
147					canvas: { },
148					
149					controllers: [
150						{ name: "defaultLogger" },											
151
152						{ name: "canvasHoverController" },
153						{ name: "canvasSelectController" },
154					],						
155				}
156			}
157			
158		}
159	
160	]
161};
Full Screen

calculator.js

Source: calculator.js Github

copy
1(function ($) {
2  var patientCount;
3  var storedRows;
4  var shouldClearOnFocus = false;
5  var app;
6  Drupal.behaviors.calculator = {
7    attach: function (context, settings) {
8      // if ie browser version is older than ie7
9      if($.browser.msie && parseInt($.browser.version, 10) <= 7) {
10        $(".overlay-bg", context).show();
11        $("#popup-oldbrowser", context).show();
12        $("#start-popup", context).hide();
13      }
14
15      //Handle printing
16      $(".print", context).click(function(event) {
17        var type = $(this).hasClass('individual') ? 'individual' : 'simplified';
18        Drupal.behaviors.calculator.gaPush(['_trackEvent', 'Print', type]);
19        if(settings.monofer.app) {
20          window.location = 'print://now';
21        } else if(!settings.monofer.printSupported) {
22          Drupal.behaviors.calculator.showPopup(Drupal.t('To print, please use your browser\'s built-in print functionality, usually found under settings', {}, {context:'Printing'}), context);
23        } else {
24          window.print();
25        }
26      });
27
28      //Handle/init settings if php has not been run (if offline) assume mobile
29      if(!window.location.origin) {
30        window.location.origin = window.location.protocol+"//"+window.location.host;
31      }
32
33      app = settings.monofer.app;
34
35      //Handle disclaimer popup
36      var acceptPopup = $.cookie('accept-popup');
37      var noPrompt = location.href.indexOf('noprompt')!=-1;
38      if(app || noPrompt || acceptPopup!=undefined) {
39        $("#start-popup", context).hide();
40        $(".overlay-bg", context).hide();
41
42        //Show video for noprompt/app users on first visit
43        // if(acceptPopup==undefined && (settings.monofer.app || noPrompt)) {
44        //   Drupal.behaviors.calculator.setVideoSrc(context, settings);
45        //   $("body", context).addClass('mobile-overlay');
46        //   $("#video-prompt", context).show();
47        // } else {
48          var player = videojs('instruction-video');
49          player.dispose();
50        // }
51
52        //Extend life of accept-popup cookie
53        $.cookie('accept-popup', 'YES', { expires: Drupal.behaviors.calculator.dateWithDaysFromNow(365), path: '/' });
54      } else {
55        $("body", context).addClass('mobile-prompt');
56      }
57
58      $("#video-close", context).click(function(event) {
59        var player = videojs('instruction-video');
60        player.pause();
61        player.dispose();
62        $("#video-prompt", context).hide();
63
64        //Show download-app popup if applicable
65        if(Drupal.behaviors.calculator.isTouchDevice() && !app) {
66          var downloadPopup = $("#popup-downloadapp", context);
67          $("#close-downloadapp", context).click(function(event) {
68            $(".overlay-bg", context).hide();
69            $("body", context).removeClass('mobile-overlay');
70            downloadPopup.hide();
71          });
72          $(".appgo", context).click(function(event) {
73            $(".overlay-bg", context).hide();
74            $("body", context).removeClass('mobile-overlay');
75            downloadPopup.hide();
76          });
77          downloadPopup.show();
78        } else {
79          $(".overlay-bg", context).hide();
80          $("body", context).removeClass('mobile-overlay');
81        }
82      });
83
84      $("#start-ok", context).click(function(event) {
85        $("#start-popup", context).hide();
86
87        $(".overlay-bg", context).hide();
88        $("body", context).removeClass('mobile-prompt');
89        $.cookie('accept-popup', 'YES', { expires: Drupal.behaviors.calculator.dateWithDaysFromNow(365), path: '/' });
90
91        //Handle instruction video
92        Drupal.behaviors.calculator.setVideoSrc(context, settings);
93        $("body", context).addClass('mobile-overlay');
94        $("#video-prompt", context).show();
95      });
96
97      //Handle tabs
98      var activeIndex = 0;
99      if(window.location.href.indexOf("simplified-page")!=-1) {
100        activeIndex = 1;
101      } else if(window.location.href.indexOf("individual-page")!=-1) {
102        activeIndex = 0;
103      } else {
104        var activeTab = $.cookie('active-tab');
105        activeIndex = activeTab==undefined ? 0 : activeTab;
106      }
107      var page = activeIndex == 0 ? 'individual-page' : 'simplified-page';
108      Drupal.behaviors.calculator.gaPush(['_trackPageview', '/?' + page]);
109      $(".tabs li.last", context).click(function(event) {
110       $("body", context).addClass('simplified-isactive');
111      });
112      $('.tabs li.first', context).click(function(event) {
113       $("body", context).removeClass('simplified-isactive');
114      });
115      $(".content", context).tabs({
116        create: function( event, ui ) {
117          if ($(".tabs li.last.ui-state-active", context)[0]){
118             $("body").addClass('simplified-isactive');
119          }
120        }, active: activeIndex,
121        activate: function(event, ui) {
122            $.cookie('active-tab', ui.newTab.index(), { expires: Drupal.behaviors.calculator.dateWithDaysFromNow(365), path: '/' });
123            var page = ui.newTab.index() == 0 ? 'individual-page' : 'simplified-page';
124            Drupal.behaviors.calculator.gaPush(['_trackPageview', '/?' + page]);
125        }
126      });
127
128      //Handle tooltips/info popups in general
129      $('.tooltip', context).each(function(index, el) {
130        var content = '<h3>' + $(this).data("title") + '</h3><p>' + $(this).data("content") + '</p>';
131        $(this).tooltipsy({
132          className: 'tooltipsy standard',
133          content: content,
134          show:function(e, $el) {
135            if(Drupal.behaviors.calculator.isTouchDevice()) { //Use popup for mobile
136              Drupal.behaviors.calculator.showPopup($el.find('.tooltipsy').html(), context);
137            } else {
138              $el.show();
139            }
140          }
141        });
142      });
143      $(".close-button", context).click(function(event) {
144        $("body").removeClass('mobile-overlay');
145        $("#popup").hide();
146        $('body').unbind('touchmove');
147      });
148
149      //Handle scrolling
150      $(".totop", context).click(function() {
151        $("html, body", context).animate({ scrollTop: 0 }, "slow");
152      });
153
154      //Handle accordion
155      $("#acc-wrap", context).accordion({
156        header: ".acc-header",
157        collapsible: true,
158        active: false
159      });
160
161      //Handle input types
162      $(".integer-only", context).on('keydown',function(e) {
163        var allowedKeys = [8, 9, 13, 37, 38, 39, 40, 46, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 110, 188, 190];
164        if (allowedKeys.indexOf(e.keyCode)==-1) {
165          return(false); //stop processing
166        }
167      });
168      //Handle focus
169      $(".integer-only", context).on('focus',function(e) {
170        if(shouldClearOnFocus) { //Clear input
171          shouldClearOnFocus = false;
172          $("input[name='irons']", context).val('');
173          $("input[name='targethb']", context).val('');
174          $("input[name='actualhb']", context).val('');
175          $("input[name='idealbw']", context).val('');
176          $("input[name='patient-id']", context).val('');
177          //Patient Iron Need
178          $('#iron-need-result', context).html('–');
179          //Recommendation
180          $(".iron-recommendation-result", context).hide();
181          $(".empty-result", context).show();
182          $(".recommendation .result-image", context).hide();
183          $(".info-followup", context).hide();
184          //Monofer Dose
185          $(".monofer-dose-result", context).html('–');
186        }
187      });
188
189      //Submit handling
190      patientCount = 0;
191      $(".patient-submit", context).click(function(event) {
192        event.preventDefault();
193        if(storedRows.length>0) {
194          var patientID = $("input[name='patient-id']", context).val();
195          Drupal.behaviors.calculator.gaPush(['_trackEvent', 'Patient ID', 'Individual', patientID]);
196          $('.result-table tr:eq(1) .patient', context).html(patientID);
197          $(".mobile-patient", context).first().html(patientID);
198          storedRows[0].id = patientID;
199          Drupal.behaviors.calculator.updateCookie();
200        }
201      });
202      $(".calculate-btn", context).click(function(event) {
203        event.preventDefault(); //Avoid submit/refresh
204        Drupal.behaviors.calculator.calculate(context, settings);
205      });
206
207      //Handle deletion of rows
208      $('.delete', context).live('click', function () {
209        var index = $(".delete", context).index(this);
210        Drupal.behaviors.calculator.deleteRow(index, context);
211      });
212      $(".mobile-delete", context).live('click', function() {
213        var index = $(".mobile-delete", context).index(this);
214        Drupal.behaviors.calculator.deleteRow(index, context);
215      });
216
217      $("select[name='units']", context).bind($.browser.msie ? 'click' : 'change', function(event) {
218        var unitVal = $(this).val();
219        $("select[name='units-simplified']", context).val(unitVal);
220        $.cookie('unit', unitVal, { expires: Drupal.behaviors.calculator.dateWithDaysFromNow(365), path: '/' });
221        Drupal.behaviors.calculator.gaPush(['_trackEvent', 'Unit Selection', 'Individual', unitVal]);
222      });
223
224      //Handle custom unit selection
225      $(".active-unit", context).click(function(event) {
226        $(this).next().show();
227      });
228      $(".unit-select.individual .unit-list li", context).click(function(event) {
229        var unitContainer = $(this).parent().prev().find('.unit-value');
230        unitContainer.html($(this).text());
231        var data = $(this).data('val');
232        unitContainer.data('val', data);
233
234        var simpleContainer = $(".unit-select.simplified .unit-value", context);
235        simpleContainer.html($(this).text());
236        simpleContainer.data('val', data);
237
238        $(this).parent().hide();
239        $.cookie('unit', data, { expires: Drupal.behaviors.calculator.dateWithDaysFromNow(365), path: '/' });
240        Drupal.behaviors.calculator.gaPush(['_trackEvent', 'Unit Selection', 'Individual', data]);
241      });
242
243      var unit = $.cookie('unit');
244      if(unit!==undefined) {
245        if(settings.monofer.mobile) { //Use native selects
246          $("select[name='units']", context).val(unit);
247          $("select[name='units-simplified']", context).val(unit);
248          var unitText = $("select[name='units-simplified'] option:selected", context).text();
249          Drupal.behaviors.calculator.updateSimplifiedUnits(unit, unitText, settings, context);
250        } else {
251          var unitText = $(".unit-select.individual ul").find("[data-val='" + unit + "']").html();
252          var commonContainer = $(".unit-select .active-unit .unit-value", context);
253          commonContainer.html(unitText);
254          commonContainer.data('val', unit);
255        }
256      }
257      //And unselection
258      $(document).mouseup(function (e) {
259        var container = $(".unit-select");
260        var child = $(".unit-list");
261        if (!container.is(e.target) // if the target of the click isn't the container...
262            && container.has(e.target).length === 0) // ... nor a descendant of the container
263        {
264          child.hide();
265        }
266      });
267
268      //Simplified table
269      $(".simplified-table td.clickable", context).click(function(event) {
270        var index = $(this).data("index");
271        var simplifiedText = $(".simplified-table tr.simplified-content:eq(" + index + ")", context);
272        var action;
273        if($(this).hasClass('active')) {
274          $(this).removeClass('active');
275          simplifiedText.hide();
276          action = 'close';
277        } else {
278          $("td.active", context).removeClass('active');
279          $('tr.simplified-content', context).hide();
280          $(this).addClass('active');
281          simplifiedText.show();
282          action = 'open';
283        }
284        var simplifiedLabel;
285        if(index=="0") {
286          simplifiedLabel = "1000mg >= 10";
287        } else if(index=="1") {
288          simplifiedLabel = "1500mg >= 10";
289        } else if(index=="2") {
290          simplifiedLabel = "1500mg < 10";
291        } else {
292          simplifiedLabel = "2000mg < 10";
293        }
294        Drupal.behaviors.calculator.gaPush(['_trackEvent', 'Patient Iron Need', action, simplifiedLabel]);
295      });
296
297      $("select[name='units-simplified']", context).bind($.browser.msie ? 'click' : 'change', function(event) {
298        var unitVal = $(this).val();
299        $("select[name='units']", context).val(unitVal);
300        var unitText = $(this).find("option:selected").text();
301        Drupal.behaviors.calculator.updateSimplifiedUnits(unitVal, unitText, settings, context);
302        Drupal.behaviors.calculator.gaPush(['_trackEvent', 'Unit Selection', 'Simplified', unitVal]);
303      });
304
305      $(".unit-select.simplified .unit-list li", context).click(function(event) {
306        var unitContainer = $(this).parent().prev().find('.unit-value');
307        var unitVal = $(this).data('val');
308        var unitText = $(this).text();
309        unitContainer.html(unitText);
310        unitContainer.data('val', unitVal);
311
312        var individualContainer = $(".unit-select.individual .unit-value", context);
313        individualContainer.html(unitText);
314        individualContainer.data('val', unitVal);
315
316        Drupal.behaviors.calculator.updateSimplifiedUnits(unitVal, unitText, settings, context);
317        $(this).parent().hide();
318        Drupal.behaviors.calculator.gaPush(['_trackEvent', 'Unit Selection', 'Simplified', unitVal]);
319      });
320      $('#mobile-info-tooltip', context).tooltipsy({
321        className: 'tooltipsy',
322        show:function(e, $el) {
323          Drupal.behaviors.calculator.showPopup($("#mobile-info-tooltip-content", context).html(), context, 'mobile-tooltipsy');
324        }
325      });
326
327      var infotextTable = '<h3>' + Drupal.t('Recommendation') + '</h3>';
328      infotextTable += '<p>' + Drupal.t('Monofer can be administered up to 20 mg/kg.') + '</p>';
329      infotextTable += '<div class="result-image one-visit"></div>';
330      infotextTable += '<p>' + Drupal.t('Full iron correction can be achieved in just one visit') + '</p>';
331      infotextTable += '<div class="result-image follow-up"></div>';
332      infotextTable += '<p>' + Drupal.t('If the patient’s need for iron exceeds 20 mg/kg body weight, the dose must be divided and administered at intervals of at least one week. It is recommended to administer maximum dose at the first visit.') + '</p>';
333      $('#info-followup-table', context).tooltipsy({
334        content: infotextTable,
335        className: 'tooltipsy info-wide',
336        show: function(e, $el) {
337          if(Drupal.behaviors.calculator.isTouchDevice()) {
338            Drupal.behaviors.calculator.showPopup(infotextTable, context);
339          } else {
340            $el.show();
341          }
342        }
343      });
344      $('.first-dose-tooltip', context).live('click', function() {
345        Drupal.behaviors.calculator.showPopup(infotextTable, context);
346      });
347
348      //Import stored data from cookie
349      storedRows = [];
350      if(settings.monofer.app || document.referrer.indexOf(window.location.origin)!=-1) { //Only use stored data if on same domain or an app
351        var count = $.cookie('counter');
352        if(count!=undefined) {
353          patientCount = parseInt(count);
354        }
355        var rows = $.cookie('rows');
356        if(rows!=undefined) {
357          rows = JSON.parse(rows);
358          var row;
359          for (var i = 0; i < rows.length; i++) {
360            row = rows[i];
361            Drupal.behaviors.calculator.addRow(context,row.id,row.ironNeed,row.dose,row.firstDose,row.stores,row.target,row.actual,row.ideal,row.visitClass);
362          }
363          if(rows.length>0 && row!=undefined) { //Add info to boxes on recommendation etc.
364            //Patient iron need
365            $('#iron-need-result', context).html(row.ironNeed + ' mg');
366
367            //Recommendation
368            var infotext = '<h3>' + Drupal.t('Recommendation', {}, {context:'Recommendation tooltip'}) + '</h3>' + '<p>' + Drupal.t('Monofer can be administered up to 20 mg/kg.', {}, {context:'Recommendation tooltip'}) + '</p>';
369            if(row.visitClass=="one-visit") {
370              recommendation = Drupal.t('Full iron correction can be achieved in just one visit', {}, {context:'Recommendation box'});
371              $(".info-followup", context).show();
372              infotext += '<div class="result-image one-visit"></div>' + '<p>' + Drupal.t('Full iron correction can be achieved in just one visit.', {}, {context:'Recommendation tooltip'}) + '</p>';
373              Drupal.behaviors.calculator.updateInfoFollowup(true, infotext, recommendation, row.visitClass, context);
374            } else {
375              recommendation = Drupal.t('Maximum dose at first visit', {}, {context:'Recommendation box'});
376              $(".info-followup", context).show();
377              infotext += '<div class="result-image follow-up"></div>' + '<p>' + Drupal.t('If the patient’s need for iron exceeds 20 mg/kg body weight, the dose must be divided and administered at intervals of at least one week. It is recommended to administer maximum dose at the first visit.', {}, {context:'Recommendation tooltip'}) + '</p>';
378              recommendation += '<span class="bold">' + Drupal.t(' @d&nbsp;ml', {'@d':row.firstDose}, {context:'Recommendation dose'}) + '</span>';
379              Drupal.behaviors.calculator.updateInfoFollowup(false, infotext, recommendation, row.visitClass, context);
380            }
381            //Monofer Dose
382            $('.monofer-dose-result', context).html(row.dose + ' ml');
383          }
384        }
385      } else {
386        $.removeCookie('counter');
387        $.removeCookie('rows');
388      }
389    },
390    calculate: function(context, settings) {
391      //Remove old errors if any
392      $('input.error', context).removeClass('error');
393
394      //Verify input values
395      var error = false;
396      var ironStores = $("input[name='irons']", context).val();
397      ironStores = Drupal.behaviors.calculator.parseNumber(ironStores);
398      if(!Drupal.behaviors.calculator.isNumber(ironStores)) {
399        error = true;
400        $("input[name='irons']", context).addClass('error');
401      } else {
402        ironStores = parseFloat(ironStores);
403      }
404      var target = $("input[name='targethb']", context).val();
405      target = Drupal.behaviors.calculator.parseNumber(target);
406      if(!Drupal.behaviors.calculator.isNumber(target)) {
407        error = true;
408        $("input[name='targethb']", context).addClass('error');
409      } else {
410        target = parseFloat(target);
411      }
412      var actual = $("input[name='actualhb']", context).val();
413      actual = Drupal.behaviors.calculator.parseNumber(actual);
414      if(!Drupal.behaviors.calculator.isNumber(actual)) {
415        error = true;
416        $("input[name='actualhb']", context).addClass('error');
417      } else {
418        actual = parseFloat(actual);
419      }
420      var ideal = $("input[name='idealbw']", context).val();
421      ideal = Drupal.behaviors.calculator.parseNumber(ideal);
422      if(!Drupal.behaviors.calculator.isNumber(ideal)) {
423        error = true;
424        $("input[name='idealbw']", context).addClass('error');
425      } else {
426        ideal = parseFloat(ideal);
427      }
428
429      if(!error) { //Verify that
430        if(actual>=target) {
431          error = true;
432          if(Drupal.behaviors.calculator.isTouchDevice()) { //Use popup for mobile
433            Drupal.behaviors.calculator.showPopup($(".calc-row.actual-hb .tooltip", context).data('content'), context);
434          } else {
435            $(".calc-row.actual-hb .tooltip", context).data('tooltipsy').show();
436            setTimeout(function() { //timeout and hide popup again
437                  $(".calc-row.actual-hb .tooltip", context).data('tooltipsy').hide();
438            }, 3000);
439          }
440        }
441      }
442
443      if(!error) {
444        var unit = $("select[name='units'] option:selected", context).val();
445        if(unit==undefined) { //Use the custom select's value
446          unit = $(".unit-select.individual .unit-value").data('val');
447        }
448        var unitScale = unit=='g-dl' ? 1 : unit=='g-l' ? 0.1 : 1.61; //Scale Hb
449        var totalIronNeed = ideal * (target*unitScale-actual*unitScale) * 2.4 + ironStores;
450        var roundedIronNeed = Math.round(totalIronNeed/100) * 100; //To nearest 100
451        var dose = roundedIronNeed/ideal;
452        var roundedDose = dose.toFixed(2);
453
454        //Patient iron need
455        $('#iron-need-result', context).html(roundedIronNeed + ' mg');
456        var recommendation = '';
457        var visitClass;
458        var infotext = '<h3>' + Drupal.t('Recommendation', {}, {context:'Recommendation tooltip'}) + '</h3>' + '<p>' + Drupal.t('Monofer can be administered up to 20 mg/kg.', {}, {context:'Recommendation tooltip'}) + '</p>';
459        var firstDose;
460        if(roundedDose<=20) {
461          recommendation = Drupal.t('Full iron correction can be achieved in just one visit', {}, {context:'Recommendation box'});
462          visitClass = "one-visit";
463          $(".info-followup", context).show();
464          infotext += '<div class="result-image one-visit"></div>' + '<p>' + Drupal.t('Full iron correction can be achieved in just one visit.', {}, {context:'Recommendation tooltip'}) + '</p>';
465          firstDose = roundedIronNeed/100;
466          Drupal.behaviors.calculator.updateInfoFollowup(true, infotext, recommendation, visitClass, context);
467        } else {
468          recommendation = Drupal.t('Dose must be split. Maximum dose at first visit', {}, {context:'Recommendation box'});
469          visitClass = "follow-up";
470          $(".info-followup", context).show();
471          infotext += '<div class="result-image follow-up"></div>' + '<p>' + Drupal.t('If the patient’s need for iron exceeds 20 mg/kg body weight, the dose must be divided and administered at intervals of at least one week. It is recommended to administer maximum dose at the first visit.', {}, {context:'Recommendation tooltip'}) + '</p>';
472          // firstDose = Math.round(ideal*20/100);
473          firstDose = Math.floor(ideal*20/100);
474          recommendation += '<span class="bold">' + Drupal.t(' @d&nbsp;ml', {'@d':firstDose}, {context:'Recommendation dose'}) + '</span>';
475          Drupal.behaviors.calculator.updateInfoFollowup(false, infotext, recommendation, visitClass, context);
476        }
477
478        patientCount ++;
479        var patientID = $("input[name='patient-id']", context).val();
480        if(patientID=="") {
481          patientID = Drupal.t("ID @id", {'@id':patientCount}, {context:'Patient ID'});
482        }
483
484        //Monofer Dose
485        roundedDose = roundedIronNeed/100;
486        $('.monofer-dose-result', context).html(roundedDose + ' ml');
487
488        Drupal.behaviors.calculator.addRow(context, patientID, roundedIronNeed, roundedDose, firstDose, ironStores, target, actual, ideal, visitClass);
489
490        shouldClearOnFocus = true;
491
492        if(screen.width<768) {
493          $('html, body', context).animate({scrollTop:$('#result-anchor', context).offset().top}, 'slow');
494        } else {
495          $('html, body', context).animate({scrollTop:0}, 'slow');
496        }
497        Drupal.behaviors.calculator.gaPush(['_trackEvent', 'Dose calculation status', 'Calculate', 'Calculation success']);
498        Drupal.behaviors.calculator.gaPush(['_trackEvent', 'Dose calculation input', 'Unit Selection', unit]);
499        Drupal.behaviors.calculator.gaPush(['_trackEvent', 'Dose calculation input', 'Iron Stores', '', ironStores]);
500        Drupal.behaviors.calculator.gaPush(['_trackEvent', 'Dose calculation input', 'Target Hb', '', target]);
501        Drupal.behaviors.calculator.gaPush(['_trackEvent', 'Dose calculation input', 'Actual Hb', '', actual]);
502        Drupal.behaviors.calculator.gaPush(['_trackEvent', 'Dose calculation input', 'Body weight', '', ideal]);
503        Drupal.behaviors.calculator.gaPush(['_trackEvent', 'Dose calculation input', 'Patient Iron Need', '', roundedIronNeed]);
504        Drupal.behaviors.calculator.gaPush(['_trackEvent', 'Dose calculation input', 'Monofer Dose', '', roundedDose]);
505        Drupal.behaviors.calculator.gaPush(['_trackEvent', 'Dose calculation input', 'Recommendation', visitClass]);
506      } else {
507        Drupal.behaviors.calculator.gaPush(['_trackEvent', 'Dose calculation status', 'Calculate', 'Calculation input error']);
508      }
509    },
510    addRow: function(context, id, ironNeed, dose, firstDose, stores, target, actual, ideal, visitClass) {
511      $('.result-table .first-row', context).show();
512      $('.result-table .last-row', context).removeClass('last-row');
513      var unit = $("select[name='units'] option:selected", context).text();
514      if(unit=='') { //Use the custom select's value
515        unit = $(".unit-select.individual .unit-value").text();
516      }
517      unit = ' ' + unit;
518      var row = '<tr>' +
519            '<td class="first-cell"><span class="' + visitClass + '"></span></td>' +
520            // '<td class="patient">' + id + '</td>' +
521            '<td class="ironneed">' + ironNeed + ' mg</td>' +
522            '<td class="monoferdose">' + dose + ' ml</td>' +
523            '<td class="firstdose">' + firstDose + ' ml</td>' +
524            '<td class="stores">' + stores + ' mg</td>' +
525            '<td>' + target + unit + '</td>' +
526            '<td>' + actual + unit + '</td>' +
527            '<td>' + ideal + ' kg</td>' +
528            '<td class="last-cell"><span class="delete"></span></td>' +
529          '</tr>';
530      $(".result-table tr", context).first().after(row);
531      $(".result-table tr:gt(5)", context).remove();
532      $(".result-table tr", context).last().addClass('last-row');
533
534      //Mobile table
535      $(".history-title", context).show();
536      var mobileRow =    '<div class="mobile-row">' +
537                        '<div class="acc-header"><span class="mobile-patient">' + id + '</span><span class="' + visitClass + '"></span><span class="mobile-delete"></span><span class="arrow"></span></div>' +
538                        '<div class="acc-content">' +
539                          '<div class="data-row ironneed"><label>' + Drupal.t('Patient iron need', {}, {'context':'Mobile row'}) + '</label><span class="data">' + ironNeed + ' mg</span></div>' +
540                          '<div class="data-row monoferdose"><label>' + Drupal.t('Monofer dose', {}, {context:'Mobile row'}) + '</label><span class="data">' + dose + ' ml</span></div>' +
541                          '<div class="data-row firstdose"><label>' + Drupal.t('First dose', {}, {context:'Mobile row'}) + '</label><span class="data">' + firstDose + ' ml</span><span class="first-dose-tooltip"></span></div>' +
542                          '<div class="data-row stores"><label>' + Drupal.t('Iron stores', {}, {context:'Mobile row'}) + '</label><span class="data">' + stores + ' mg</span></div>' +
543                          '<div class="data-row"><label>' + Drupal.t('Target Hb', {}, {context:'Mobile row'}) + '</label><span class="data">' + target + unit + '</span></div>' +
544                          '<div class="data-row"><label>' + Drupal.t('Actual Hb', {}, {context:'Mobile row'}) + '</label><span class="data">' + actual + unit + '</span></div>' +
545                          '<div class="data-row"><label>' + Drupal.t('Ideal bw', {}, {context:'Mobile row'}) + '</label><span class="data">' + ideal + ' kg</span></div>' +
546                        '</div>' +
547                      '</div>';
548      $(".mobile-result-table .history-title", context).after(mobileRow);
549      $(".mobile-row:gt(4)", context).remove();
550      $("#acc-wrap", context).accordion('destroy').accordion({
551        header: ".acc-header",
552        collapsible: true,
553        active: false
554      });
555
556      //Maintain storedRows
557      storedRows.push({
558        'id':id,
559        'ironNeed':ironNeed,
560        'dose':dose,
561        'firstDose':firstDose,
562        'stores':stores,
563        'target':target,
564        'actual':actual,
565        'ideal':ideal,
566        'visitClass':visitClass
567      });
568      if(storedRows.length>5) {
569        storedRows.splice(0, storedRows.length-5);
570      }
571      Drupal.behaviors.calculator.updateCookie();
572    },
573    deleteRow: function(index, context) {
574      var row = $(".delete", context).eq(index).closest('tr').remove();
575      var rows = $(".result-table tr", context);
576      if(rows.length>1) {
577        rows.last().addClass('last-row');
578      }
579      //Delete mobile row
580      $(".mobile-row", context)[index].remove();
581
582      storedRows.splice(storedRows.length-index-1, 1);
583      Drupal.behaviors.calculator.updateCookie();
584    },
585    showPopup: function(content, context, customClass) {
586      $("#popup-message", context).removeClass();
587      if(customClass!==undefined) {
588        $("#popup-message", context).addClass(customClass);
589      }
590      $("#popup-message", context).html(content);
591      $("#popup", context).show();
592      $("body").addClass('mobile-overlay');
593      $('body').bind('touchmove', function(e){e.preventDefault()});
594    },
595    parseNumber: function(n) {
596      if(n!==undefined) {
597        n = n.replace(",", ".");
598      }
599      return n;
600    },
601    isNumber: function(n) {
602      return !isNaN(parseFloat(n)) && isFinite(n);
603    },
604    updateCookie: function() {
605      $.cookie('rows', JSON.stringify(storedRows));
606      $.cookie('counter', '' + patientCount);
607      $.cookie('counter', Number);
608    },
609    isTouchDevice: function() {
610      //DEBUG
611      //return true;
612      if(Drupal.behaviors.calculator.isIE()) {
613        return false;
614      }
615      return 'ontouchstart' in window // works on most browsers
616          || 'onmsgesturechange' in window; // works on ie10
617    },
618    updateSimplifiedUnits: function(unitVal, unitText, settings, context) {
619      $("#simple-unit-header").html(Drupal.t("Hb (@unit)", {'@unit':unitText}, {context:'Simple unit'}));
620      var unitScale = unitVal=='g-dl' ? 1 : unitVal=='g-l' ? 10 : 0.62; //Scale Hb
621      var threshold = (10*unitScale);
622      $("#simplified-hb-1", context).html('≥ ' + threshold);
623      $("#simplified-hb-2", context).html('< ' + threshold);
624      $.cookie('unit', unitVal, { expires: Drupal.behaviors.calculator.dateWithDaysFromNow(365), path: '/' });
625    },
626    updateInfoFollowup:function(singleVisit, infotext, recommendation, visitClass, context) {
627      if($('.recommendation-tooltip.info-followup', context).data('tooltipsy')!==undefined) {
628        $('.tooltipsy.info-wide.info-left', context).parent().remove();
629      }
630      $('.recommendation-tooltip.info-followup', context).tooltipsy({
631         content: infotext,
632         className: 'tooltipsy info-wide info-left ' + visitClass + '-tooltip',
633         offset: [-1, 0], //Show to the left of the info icon
634         show:function(e, $el) {
635          if(Drupal.behaviors.calculator.isTouchDevice()) { //Use popup for mobile
636            Drupal.behaviors.calculator.showPopup(infotext, context);
637          } else {
638            $el.show();
639          }
640         }
641      });
642      $('.empty-result', context).hide();
643      $('.result-box .result-image', context).attr("class",'result-image ' + visitClass);
644      $('.result-box .result-image', context).show();
645
646      $('.iron-recommendation-result', context).html(recommendation);
647      $('.iron-recommendation-result', context).show(); //Show if it was hidden
648    },
649    isIE: function() {
650      var myNav = navigator.userAgent.toLowerCase();
651      // return (myNav.indexOf('msie') != -1) ? parseInt(myNav.split('msie')[1]) : false;
652      return (myNav.indexOf('msie') != -1) ? true : false;
653    },
654    gaPush: function(vars) {
655      if(app) {
656        var customUrl = 'analytics://' + vars;
657        Drupal.behaviors.calculator.execute(customUrl);
658      } else {
659        try{
660          _gaq.push(vars);
661        } catch(err) {
662        }
663      }
664    },
665    execute:function(url) {
666      var iframe = document.createElement("IFRAME");
667      iframe.setAttribute("src", url);
668      document.documentElement.appendChild(iframe);
669      iframe.parentNode.removeChild(iframe);
670      iframe = null;
671    },
672    dateWithDaysFromNow:function(days) {
673      var date = new Date();
674      date.setTime(date.getTime() + (days*24*60*60*1000));
675      return date;
676    },
677    setVideoSrc:function(context, settings) {
678      var src;
679      if(window.screen.width > 760) {
680        src = settings.monofer.ipad_video;
681      } else {
682        src = settings.monofer.mobile_video;
683      }
684      var player = videojs('instruction-video');
685      player.src({ type: "video/mp4", src: src });
686    }
687  };
688})(jQuery);
689
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run JavaScript Tests on LambdaTest Cloud Grid

Execute automation tests with Playwright Internal on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)