Best JavaScript code snippet using taiko
gis.js
Source:gis.js
1//setup django csrftoken cookie for ajax2//get crsf token cookie3function getCookie(name) {4 var cookieValue = null;5 if (document.cookie && document.cookie !== '') {6 var cookies = document.cookie.split(';');7 for (var i = 0; i < cookies.length; i++) {8 var cookie = jQuery.trim(cookies[i]);9 // Does this cookie string begin with the name we want?10 if (cookie.substring(0, name.length + 1) === (name + '=')) {11 cookieValue = decodeURIComponent(cookie.substring(name.length + 1));12 break;13 }14 }15 }16 return cookieValue;17}18//setup ajax crsf header19function csrfSafeMethod(method) {20// these HTTP methods do not require CSRF protection21 return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));22}23//globals24var lastInvokerWidget;25function getID() {26 id = getRandomColor();27 widget_lst = Object.keys(all_widgets);28 if (id.split('#')[1] in widget_lst) {29 return getID();30 }else{31 return id.split('#')[1];32 };33}34function getFileList(){35 $.ajax({36 method: "GET",37 url: 'file-list',38 dataType: 'json'39 }).done(function(fileList) {40 //update file select41 $('select#file-select').empty();42 $.each(fileList, function (index, file){43 var fileName = file.fields.file.split('/')[file.fields.file.split('/').length-1];44 $('select#file-select').append('<option value="'+file.pk+'" url="'+file.fields.file+'">'+fileName+'</option>');45 });46 }).fail(function(msg){47 alert('Failed to retreive files');48 });49}50function importFeatures(){51 var selectedFiles = $.map($('select#file-select option:selected'), function (el, i) {52 return $(el).attr("url");53 });54 if (selectedFiles.length > 1){55 alert('Please select one file at a time.');56 return;57 }58 //check for existing vector layers59 var vectorLayer = new ol.layer.Vector({60 source: new ol.source.Vector({61 format: new ol.format.KML({62 extractStyles:false63 }),64 url: selectedFiles[0]65 })66 });67 var map = lastInvokerWidget.data('map');68 map.addLayer(vectorLayer);69 var targetElement = $(map.getTargetElement());70 var parser = new ol.format.GeoJSON();71 vectorLayer.once('change', function (){72 var features = vectorLayer.getSource().getFeatures();73 74 features.forEach(function(feature, index, array){75 var GeoJSONFeature = parser.writeFeatureObject(feature);76 //add loading icon on import feature button77 $('#btn-import-features i').toggleClass('fa-map-marker', false);78 $('#btn-import-features i').toggleClass('fa-spin fa-spinner', true);79 $.ajax({80 method: "POST",81 url: 'save-feature',82 dataType: 'json',83 data: JSON.stringify({84 widget: targetElement.attr('id'),85 feature: GeoJSONFeature86 })87 }).done(function(response) {88 //remove loading icon on import feature button89 $('#btn-import-features i').toggleClass('fa-spin fa-spinner', false);90 $('#btn-import-features i').toggleClass('fa-map-marker', true);91 //set feature id92 feature.setId(response.fid);93 }).fail(function(msg){94 $('#btn-import-features i').toggleClass('fa-spin fa-spinner', false);95 $('#btn-import-features i').toggleClass('fa-map-marker', true);96 alert('Failed to save features to database.');97 });98 });99 //load features from database100 loadMapFeatures(targetElement);101 });102}103var downloadMapAsPNG = function(){104 console.log(lastInvokerWidget.attr('id'));105 var canvas = lastInvokerWidget.find('canvas').get(0);106 canvas.toBlob(function(blob){107 saveAs(blob, 'map.png');108 });109};110var downloadMapAsGJSON = function(){111 var map = lastInvokerWidget.data('map');112 var layers = map.getLayers();113 var vectorLayer;114 layers.forEach(function (layer) {115 116 if (layer instanceof ol.layer.Vector)117 vectorLayer = layer;118 });119 var features = vectorLayer.getSource().getFeatures();120 if (features.length < 1){121 alert('Map contains no features that can be exported as KML');122 return;123 }124 var parser = new ol.format.GeoJSON();125 var geojson = parser.writeFeatures(features);126 // console.log(geojson);127 var blob = new Blob([geojson], {type: "text/json;charset=utf-8"});128 saveAs(blob, 'map-features.geojson');129};130var downloadMapAsKML = function(){131 var map = lastInvokerWidget.data('map');132 var layers = map.getLayers();133 var vectorLayer;134 layers.forEach(function (layer) {135 136 if (layer instanceof ol.layer.Vector)137 vectorLayer = layer;138 });139 var features = vectorLayer.getSource().getFeatures();140 if (features.length < 1){141 alert('Map contains no features that can be exported as KML');142 return;143 }144 var parser = new ol.format.KML({145 writeStyles: false, 146 extractStyles:true147 });148 // var kml = '<?xml version="1.0" encoding="UTF-8"?>\n' + parser.writeFeaturesNode(features);149 var kml = parser.writeFeaturesNode(features);150 var kmlStyle = '<Style id="PolyStyle"><LineStyle><width>1.5</width></LineStyle><PolyStyle><color>7d0000ff</color></PolyStyle></Style>';151 $(kml).find('Document').prepend(kmlStyle);152 $(kml).find('styleUrl').replaceWith('<styleUrl>#PolyStyle</styleUrl>');153 console.log(kml);154 var kmlString = (new XMLSerializer()).serializeToString(kml);155 // console.log(typeof kmlString);156 // console.log(kmlString);157 var blob = new Blob (['<?xml version="1.0" encoding="UTF-8"?>\n' + kmlString], {type: "text/xml;charset=utf-8"});158 saveAs(blob, 'map-features.kml');159};160function drawPolygon(){161 alert('drawing polygon');162}163function drawSquare(){164 alert('drawing square');165}166function saveDrawings(){167 console.log($(this).closest('div.gis-container').attr('id'));168}169function createMapWidget(mapWidgetID, options){170 var newWidget = false;171 if (typeof mapWidgetID == 'undefined'){172 var mapWidgetID = getID();173 var html = '<div class="col-lg-6">\174 <section id="main-panel-" class="panel main-panel">\175 <header class="panel-heading">\176 <span class="title">New GIS widget <i id="map-widget-progress" class="fa fa-spin fa-cog"></i></span>\177 <span class="tools pull-right">\178 <a href="javascript:;" class="fa fa-chevron-down"></a>\179 <a href="#GISModal" data-toggle="modal" class="fa fa-wrench"></a>\180 <a href="javascript:;" class="fa fa-times" id="map-widget-delete-button"></a>\181 </span>\182 </header>\183 <div class="panel-body gis-panel" id="gis-panel-'+mapWidgetID+'">\184 <div id="'+mapWidgetID+'" class="gis-container chart-container">\185 <div class="nosupport">Loading map tiles please wait. <i class="fa fa-spin fa-spinner"></i> </div>\186 </div>\187 <div id="pieChart-'+mapWidgetID+'" class="map-pie-chart"></div>\188 <div id="map-popup-container" style="display: hidden;">\189 </div>\190 </div>\191 </section>\192 </div>';193 $('.chart-row').append(html);194 options = {195 center: [0,0],196 zoom: 2,197 tile_source: 'XYZ',198 tile_url: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer/tile/{z}/{y}/{x}',199 tile_attribution: '',200 };201 newWidget = true;202 }203 //create map tile source204 var tile_source;205 switch (options.tile_source){206 case 'ArcGIS':207 tile_source = new ol.source.XYZ({208 attributions: [new ol.Attribution({209 html: ''210 })],211 url: options.tile_url212 });213 break;214 case 'XYZ':215 tile_source = new ol.source.XYZ({216 attributions: options.tile_attribution,217 url: options.tile_url218 });219 break;220 case 'BingMapsAerial+Labels':221 tile_source = new ol.source.BingMaps({222 key: 'AnST1eDSeRY_VRrb86ud4B1Y_iS1OnD2NMs7EKYN8JvtRNoMt5ZjGWGsE8bNkTlJ', 223 imagerySet: 'AerialWithLabels'224 });225 break;226 default:227 tile_source = new ol.source.XYZ({228 attributions: options.tile_attribution,229 url: options.tile_url230 });231 break;232 }233 //create controls234 var DownloadMap = function(opt_options){235 var options = opt_options || {};236 var button = document.createElement('button');237 button.innerHTML = '<i class="fa fa-download"></i>';238 button.title = 'Download map as';239 var this_ = this;240 button.addEventListener('click', function(){241 lastInvokerWidget = $(this.closest('div.gis-container'));242 $('#map-dialog').data('kendoDialog').open();243 }, false);244 button.addEventListener('touchstart', function(){245 lastInvokerWidget = $(this.closest('div.gis-container'));246 $('#map-dialog').data('kendoDialog').open();247 }, false);248 var element = document.createElement('div');249 element.className = 'download-map ol-unselectable ol-control';250 element.appendChild(button);251 ol.control.Control.call(this, {252 element: element, 253 target: options.target254 });255 };256 ol.inherits(DownloadMap, ol.control.Control);257 var DrawPolygon = function(opt_options){258 var options = opt_options || {};259 var button = document.createElement('button');260 button.title = 'Draw polygon';261 button.innerHTML = '<img src="/static/visualizer/img/drawpolygon.png">';262 var this_ = this;263 button.addEventListener('click', drawPolygon, false);264 button.addEventListener('touchstart', drawPolygon, false);265 var element = document.createElement('div');266 element.className = 'draw-polygon ol-unselectable ol-control';267 element.appendChild(button);268 ol.control.Control.call(this, {269 element: element, 270 target: options.target271 });272 };273 ol.inherits(DrawPolygon, ol.control.Control);274 var DrawSquare = function(opt_options){275 var options = opt_options || {};276 var button = document.createElement('button');277 button.innerHTML = '<img src="/static/visualizer/img/drawsquare.png">';278 button.title = 'Draw rectangle';279 var this_ = this;280 button.addEventListener('click', drawSquare, false);281 button.addEventListener('touchstart', drawSquare, false);282 var element = document.createElement('div');283 element.className = 'draw-square ol-unselectable ol-control';284 element.appendChild(button);285 ol.control.Control.call(this, {286 element: element, 287 target: options.target288 });289 };290 ol.inherits(DrawSquare, ol.control.Control);291 var SaveDrawings = function(opt_options){292 var options = opt_options || {};293 var button = document.createElement('button');294 button.innerHTML = '<i class="fa fa-save"></i>';295 button.title = 'Save drawings';296 var this_ = this;297 button.addEventListener('click', saveDrawings, false);298 button.addEventListener('touchstart', saveDrawings, false);299 var element = document.createElement('div');300 element.className = 'save-drawings ol-unselectable ol-control';301 element.appendChild(button);302 ol.control.Control.call(this, {303 element: element, 304 target: options.target305 });306 };307 ol.inherits(SaveDrawings, ol.control.Control);308 var map = new ol.Map({309 target: mapWidgetID,310 layers: [311 new ol.layer.Tile({312 source: tile_source313 }),314 ],315 controls: [316 //Define the default controls317 new ol.control.Zoom(),318 new ol.control.Rotate(),319 new ol.control.Attribution(),320 new ol.control.FullScreen({321 source: 'gis-panel-'+mapWidgetID322 }),323 //Define some new controls324 new ol.control.ZoomSlider(),325 new DownloadMap(),326 new DrawPolygon(),327 new DrawSquare(),328 new SaveDrawings(),329 // new ol.control.MousePosition({330 // coordinateFormat: function (coordinates){331 // var coordX = coordinates[0].toFixed(3);332 // var coordY = coordinates[1].toFixed(3);333 // return coordX + ', ' + coordY;334 // }335 // }),336 // new ol.control.ScaleLine({337 // units: 'degrees'338 // }),339 // new ol.control.OverviewMap()340 ],341 interactions: ol.interaction.defaults({342 mouseWheelZoom: false343 }).extend([344 new ol.interaction.Select({345 layers: [new ol.layer.Vector()]346 })347 ]),348 view: new ol.View({349 center: ol.proj.fromLonLat(options.center),350 zoom: options.zoom351 }), 352 });353 //change text size on zoom change354 map.getView().on('propertychange', function (e) {355 if(e.key == 'resolution'){356 var layers = map.getLayers();357 layers.forEach(function (layer, index, array) {358 if(layer instanceof ol.layer.Vector){359 var features = layer.getSource().getFeatures();360 var fontSize = map.getView().getZoom() - 7;361 362 features.forEach(function (feature, index, array) {363 if(feature.getStyle() != null)364 feature.getStyle().getText().setFont(fontSize + 'px Hind Madurai');365 });366 }367 });368 }369 });370 //bring popover to front when feature is click on371 map.on('click', function(e){372 map.forEachFeatureAtPixel(e.pixel, function(feature, layer){373 if (feature == null)374 return;375 var overlays = map.getOverlays();376 overlays.forEach(function(overlay, index, array) {377 var position = overlay.getPosition();378 if(feature.getGeometry().intersectsCoordinate(position)){379 //decrease z-index of all popovers with 'popover-front' class380 $('.popover').removeClass("popover-front");381 //increase z-index of clicked feature's popover.382 //popover element is generated next to overlay's element.383 $(overlay.getElement()).next('div.popover').addClass("popover-front");384 }385 })386 });387 });388 //associate map with element389 $('#'+mapWidgetID).data('map',map);390 //create pie chart391 var chart = AmCharts.makeChart("pieChart-"+mapWidgetID,{392 "type" : "pie",393 "titleField" : "range",394 "valueField" : "value",395 "colorField" : "color",396 "labelText" : "[[percents]]%",397 "balloonText" : "[[title]]: [[value]]",398 "outlineAlpha": 0.5,399 "outlineThickness": 2,400 "labelRadius": -10,401 "radius": 40,402 "dataProvider" : []403 });404 //associate chart with element405 $('#pieChart-'+mapWidgetID).data('pieChart', chart);406 //save new widget407 if (newWidget){408 options['wid'] = mapWidgetID;409 $('#')410 $.ajax({411 method: 'POST', 412 url: 'save-map-widget',413 dataType: 'json',414 data: JSON.stringify(options)415 }).done(function(response){416 $('#'+mapWidgetID).closest('section.main-panel').find('i#map-widget-progress').toggleClass('fa-spin fa-cog', false);417 }).fail(function(response){418 alert('Failed to save GIS widget to database. Please referesh page and try again.');419 });420 }421}422function loadMapWidgets(){423 $.ajax({424 method: 'POST', 425 url: 'get-map-widgets',426 dataType: 'json',427 }).done(function(response){428 $.each(response, function(index, widget) {429 createMapWidget(widget.wid, widget);430 var widgetElement = $('#'+widget.wid);431 loadMapFeatures(widgetElement);432 });433 }).fail(function(response){434 alert('Failed to save GIS widget to database. Please referesh page and try again.');435 });436}437function loadMapFeatures(mapWidget){438 var mapWidgetID = mapWidget.attr('id');439 $.ajax({440 method: 'POST', 441 url: 'get-feature-list',442 dataType: 'json',443 data: JSON.stringify({'wid': mapWidgetID})444 }).done(function(response){445 //if no features return immediately446 if (response.features.length < 1)447 return;448 var map = mapWidget.data('map');449 var parser = new ol.format.GeoJSON();450 var mapLayers = map.getLayers();451 var features = parser.readFeatures(response);452 var existingVectorLayer = false;453 mapLayers.forEach(function (layer, index, array) {454 if(layer instanceof ol.layer.Vector){455 var source = layer.getSource();456 features.forEach(function (feature, index, array) {457 var existingFeature;458 existingFeature = source.getFeatureById(feature.getId());459 if(existingFeature == null)460 source.addFeature(feature);461 })462 existingVectorLayer = true;463 }464 })465 if(!existingVectorLayer){466 var vectorLayer = new ol.layer.Vector({467 style: styleMap(map),468 source: new ol.source.Vector({469 format: new ol.format.GeoJSON(),470 features: features471 })472 });473 map.addLayer(vectorLayer); 474 }475 features.forEach(function(feature, index, array){476 //asynchronously load and render stats for each feature477 loadMapFeatureStats(feature.getId(), mapWidget);478 });479 }).fail(function(response){480 alert('Failed to load feature list.');481 });482}483function loadMapFeatureStats(featureId, mapWidget){484 $.ajax({485 method: 'POST', 486 url: 'get-feature-stats',487 dataType: 'json',488 data: JSON.stringify({'fid': featureId})489 }).done(function(response){490 var map = mapWidget.data('map');491 var mapLayers = map.getLayers();492 var feature, source;493 mapLayers.forEach(function (layer, index, array) {494 if (layer instanceof ol.layer.Vector){495 source = layer.getSource();496 feature = source.getFeatureById(featureId);497 }498 });499 //remove paw stat from polygon500 // if(!response.paw.hasOwnProperty('fsid'))501 // feature.setStyle(null);502 //feature not found503 if (feature == null)504 return;505 // don't create popup for non-polygon features506 if (feature.getGeometry().getType() != 'Polygon')507 return;508 //style polygon according to paw value509 var style, color;510 // , featureStyle = feature.getStyle();511 //get chart object512 var pieChart = $('#pieChart-'+mapWidget.attr('id')).data('pieChart');513 var dataProvider = pieChart.dataProvider;514 var featureArea = feature.getGeometry().getArea();515 if (response.paw.value != null){516 if (response.paw.value < 30){517 color = [254,180,186,0.9]518 var rangeExists = false;519 for (var i in dataProvider){520 if (dataProvider[i].range == 'Red range'){521 if (dataProvider[i].features.indexOf(featureId) < 0){522 dataProvider[i].value += featureArea;523 dataProvider[i].features.push(featureId);524 }525 rangeExists = true526 } 527 }528 if (rangeExists){529 pieChart.dataProvider = dataProvider;530 }else{531 pieChart.dataProvider.push({532 range: "Red range",533 value: featureArea,534 color: "#feb4ba",535 features: [featureId]536 });537 }538 }else if(response.paw.value > 30 && response.paw.value < 70){539 color = [255,255,187,0.9]540 var rangeExists = false;541 for (var i in dataProvider){542 if (dataProvider[i].range == 'Yellow range'){543 if (dataProvider[i].features.indexOf(featureId) < 0){544 dataProvider[i].value += featureArea;545 dataProvider[i].features.push(featureId);546 }547 rangeExists = true548 } 549 }550 if (rangeExists){551 pieChart.dataProvider = dataProvider;552 }else{553 pieChart.dataProvider.push({554 range: "Yellow range",555 value: featureArea,556 color: "#ffffbb",557 features: [featureId]558 });559 }560 }else if(response.paw.value > 70 && response.paw.value < 100){561 color = [186,255,202,0.9]562 var rangeExists = false;563 for (var i in dataProvider){564 if (dataProvider[i].range == 'Green range'){565 if (dataProvider[i].features.indexOf(featureId) < 0){566 dataProvider[i].value += featureArea;567 dataProvider[i].features.push(featureId);568 }569 rangeExists = true570 } 571 }572 if (rangeExists){573 pieChart.dataProvider = dataProvider;574 }else{575 pieChart.dataProvider.push({576 range: "Green range",577 value: featureArea,578 color: "#baffca",579 features: [featureId]580 });581 }582 }else{583 color = [109,192,255,0.9]584 var rangeExists = false;585 for (var i in dataProvider){586 if (dataProvider[i].range == 'Blue range'){587 if (dataProvider[i].features.indexOf(featureId) < 0){588 dataProvider[i].value += featureArea;589 dataProvider[i].features.push(featureId);590 }591 rangeExists = true592 } 593 }594 if (rangeExists){595 pieChart.dataProvider = dataProvider;596 }else{597 pieChart.dataProvider.push({598 range: "Blue range",599 value: featureArea,600 color: "#6dc0ff",601 features: [featureId]602 });603 }604 }605 }else{606 //update pie chart data to remove non-existing area values607 for(var i in dataProvider){608 if (dataProvider[i].features.indexOf(featureId) > -1){609 for(var j in dataProvider[i].features){610 if (dataProvider[i].features[j] == featureId)611 dataProvider[i].features.pop(j);612 }613 if (dataProvider[i].features.length < 1){614 dataProvider.pop(i);615 }else{616 dataProvider[i].value -= featureArea;617 }618 }619 }620 pieChart.dataProvider = dataProvider;621 }622 //redraw chart623 pieChart.validateData();624 var statsText, fill, stroke, text;625 for (var i in response.stats){626 //do not concatenate with 'undefined'627 if(statsText == null){628 statsText = response.stats[i].data +': '+ response.stats[i].value +'\n';629 }else{630 statsText += response.stats[i].data +': '+ response.stats[i].value +'\n';631 }632 633 }634 if (statsText == null)635 statsText = '';636 var fontSize = map.getView().getZoom() - 7;637 style = new ol.style.Style({638 fill: new ol.style.Fill({639 color: color != null ? color : [255,255,255,0],640 }),641 stroke: new ol.style.Stroke({642 color: [51,153,204, 0.7]643 }),644 text: new ol.style.Text({645 font: fontSize + 'px Hind Madurai',646 overflow: true,647 // placement: 'line',648 rotateWithView: true,649 // textAlign: 'left',650 fill: new ol.style.Fill({651 color: [0,0,0,1]652 }),653 text: response.paw.value == null ? statsText :response.paw.widget + '\nPAW: ' + 654 response.paw.value + '\n' + statsText, 655 })656 });657 feature.setStyle(style);658 }).fail(function(response){659 alert('Failed to load feature list.');660 });661}662function changeMapWidget(mapWidget){663 var mapWidgetID = mapWidget.attr('id');664 $.ajax({665 method: 'POST', 666 url: 'get-map-widget',667 dataType: 'json',668 data: JSON.stringify({wid:mapWidgetID})669 }).done(function(response){670 var map = mapWidget.data('map');671 map.getView().setZoom(response.zoom);672 map.getView().setCenter(ol.proj.fromLonLat(response.center));673 var layers = map.getLayers();674 var tileSource;675 layers.forEach(function(layer, index, array){676 if(layer instanceof ol.layer.Tile){677 var tileSource = layer.getSource();678 switch (response.tile_source){679 case 'ArcGIS':680 tileSource = new ol.source.XYZ({681 attributions: [new ol.Attribution({682 html: ''683 })],684 url: response.tile_url685 });686 break;687 case 'XYZ':688 tileSource = new ol.source.XYZ({689 attributions: response.tile_attribution,690 url: response.tile_url691 });692 break;693 case 'BingMapsAerial+Labels':694 tileSource = new ol.source.BingMaps({695 key: 'AnST1eDSeRY_VRrb86ud4B1Y_iS1OnD2NMs7EKYN8JvtRNoMt5ZjGWGsE8bNkTlJ', 696 imagerySet: 'AerialWithLabels'697 });698 break;699 default:700 tileSource = new ol.source.XYZ({701 attributions: response.tile_attribution,702 url: response.tile_url703 });704 break;705 }706 layer.setSource(tileSource);707 } 708 });709 }).fail(function(response){710 alert('Failed to load GIS widget settings.');711 });712}713function getMapWidgetOptions(mapWidgetID){714 $.ajax({715 method: 'POST', 716 url: 'get-map-widget',717 dataType: 'json',718 data: JSON.stringify({wid:mapWidgetID})719 }).done(function(response){720 $('#map-widget-title').val(response.name);721 $('#map-index').val(response.index);722 $('#map-zoom').val(response.zoom);723 $('#map-center-lat').val(response.center[0]);724 $('#map-center-long').val(response.center[1]);725 $('select#map-tile-source-select').data('kendoMultiSelect').value([response.tile_source]);726 }).fail(function(response){727 alert('Failed to load GIS widget settings.');728 });729 $.ajax({730 method: 'POST', 731 url: 'get-feature-list',732 dataType: 'json',733 data: JSON.stringify({'wid': mapWidgetID})734 }).done(function(response){735 //parse response for dropdown widget736 var dataSource = [];737 $.each(response.features, function(index, item){738 dataSource.push({fid:item.id,name:item.properties.name})739 })740 var select = $('select#map-feature-select').data('kendoMultiSelect');741 select.setDataSource(dataSource);742 if (dataSource.length > 1){743 select.value(dataSource[0].fid);744 select.trigger('change');745 }746 }).fail(function(response){747 alert('Failed to load feature list.');748 });749}750function getChartWidgetList(){751 $.ajax({752 method: 'POST', 753 url: 'get-chart-widget-list',754 dataType: 'json',755 }).done(function(response){756 var select = $('select#map-paw-select').data('kendoMultiSelect');757 select.setDataSource(response);758 }).fail(function(response){759 alert('Failed to chart widget list.');760 });761}762function getDataWidgetList(){763 $.ajax({764 method: 'POST', 765 url: 'get-data-widget-list',766 dataType: 'json',767 }).done(function(response){768 var select = $('select#map-stat-select').data('kendoMultiSelect');769 var dataSource = new kendo.data.DataSource({770 data: response,771 group: {field: 'widget'}772 })773 select.setDataSource(dataSource);774 }).fail(function(response){775 alert('Failed to load feature list.');776 });777}778function styleMap(map){779 var zoom = map.getView().getZoom();780 var font_size = zoom * 10; // arbitrary value781 return [782 new ol.style.Style({783 text: new ol.style.Text({784 font: font_size + 'px Calibri,sans-serif'785 })786 })787 ];788}789$(function(){790 //setup django csrftoken cookie for ajax791 //get crsf token cookie792 var csrftoken = getCookie('csrftoken');793 $.ajaxSetup({794 beforeSend: function(xhr, settings) {795 if (!csrfSafeMethod(settings.type) && !this.crossDomain) {796 xhr.setRequestHeader("X-CSRFToken", csrftoken);797 }798 }799 });800 getFileList();801 $('#add-gis-widget').on('click', function(e){802 createMapWidget();803 });804 805 $("#fileUpload").kendoUpload({806 async: {807 saveUrl: "upload",808 removeUrl: "remove",809 autoUpload: true810 },811 upload: function(e){812 // insert csrftoken into form before upload813 e.data = {csrfmiddlewaretoken: csrftoken} 814 },815 success: function (response){816 getFileList();817 }, 818 remove: function (event){819 event.preventDefault();820 //remove uploaded file from UI821 this.clearFileByUid(event.files[0].uid);822 }, 823 localization: {824 select: 'Upload files...'825 }826 });827 $('#btn-delete-file').on('click', function(e){828 var selectedFiles = $.map($('select#file-select'), function (el, i) {829 return $(el).val();830 });831 if (!confirm('Are you sure you want to delete '+ selectedFiles.length +' file(s) ?')){832 return;833 }834 $.ajax({835 method: 'POST', 836 url: 'remove',837 dataType: 'json',838 data: JSON.stringify(selectedFiles)839 }).done(function(response){840 getFileList();841 }).fail(function(response){842 alert('Delete operation failed.');843 });844 });845 $('#btn-download-file').on('click', function(e){846 var selectedFiles = $.map($('select#file-select option:selected'), function (el, i) {847 return $(el).attr("url");848 });849 for (var i = 0; i < selectedFiles.length; i++)850 window.open(selectedFiles[i]);851 });852 853 $('#btn-import-features').on('click', function(e){854 if (lastInvokerWidget == null){855 alert('No GIS widget selected');856 return;857 }858 importFeatures();859 });860 $('#GISModal').on('shown.bs.modal', function (e){861 lastInvokerWidget = $(e.relatedTarget).closest('section.main-panel').find('div.gis-container');862 //get map widget options863 getMapWidgetOptions(lastInvokerWidget.attr('id'));864 });865 $('select#map-feature-select').kendoMultiSelect({866 maxSelectedItems: 1,867 dataTextField: "name",868 dataValueField: "fid",869 change: function (e){870 var value = this.value();871 if (value.length < 1)872 return873 $.ajax({874 method: 'POST', 875 url: 'get-feature-stat-widgets',876 dataType: 'json',877 data: JSON.stringify({'fid': value[0]})878 }).done(function(response){879 $('select#map-paw-select').data('kendoMultiSelect').value(response.paw);880 $('select#map-stat-select').data('kendoMultiSelect').value(response.stats);881 }).fail(function(response){882 alert('Failed to load feature stat.');883 });884 },885 filter: "contains",886 filtering: function (e) {887 //custom filtering logic888 if (e.filter != null){889 e.preventDefault();890 var filterWords = e.filter.value.split(" ");891 var filters = [];892 for(var i = 0; i < filterWords.length; i++){893 filters.push({field:"name", operator:"contains", value:filterWords[i]});894 }895 e.sender.dataSource.filter([896 {"logic":"and",897 "filters": filters898 }]); 899 } 900 }901 }).data('kendoMultiSelect');902 $('select#map-paw-select').kendoMultiSelect({903 maxSelectedItems: 1,904 value: [],905 dataValueField: 'value', 906 dataTextField: 'text',907 change: function (e){908 var value = this.value();909 var feature = $('select#map-feature-select').data('kendoMultiSelect').value();910 $.ajax({911 method: 'POST', 912 url: 'change-paw-feature-stat',913 dataType: 'json',914 data: JSON.stringify({'widget': value, 'feature_id':feature[0]})915 }).done(function(response){916 changeMapWidget(lastInvokerWidget);917 loadMapFeatureStats(feature[0], lastInvokerWidget);918 }).fail(function(response){919 alert('Failed to change feature stat.');920 });921 }, 922 filter:"contains",923 filtering: function (e) {924 //custom filtering logic925 if (e.filter != null){926 e.preventDefault();927 var filterWords = e.filter.value.split(" ");928 var filters = [];929 for(var i = 0; i < filterWords.length; i++){930 filters.push({field:"text", operator:"contains", value:filterWords[i]});931 }932 e.sender.dataSource.filter([933 {"logic":"and",934 "filters": filters935 }]); 936 } 937 }938 }).data('kendoMultiSelect');939 $('select#map-stat-select').kendoMultiSelect({940 maxSelectedItems: 3,941 value: [],942 dataValueField: 'value', 943 dataTextField: 'text',944 change: function (e){945 var value = this.value();946 var feature = $('select#map-feature-select').data('kendoMultiSelect').value();947 $.ajax({948 method: 'POST', 949 url: 'change-feature-stat',950 dataType: 'json',951 data: JSON.stringify({'data_ids': value, 'feature_id': feature[0]})952 }).done(function(response){953 changeMapWidget(lastInvokerWidget);954 loadMapFeatureStats(feature[0], lastInvokerWidget);955 }).fail(function(response){956 alert('Failed to change feature stat.');957 });958 }, 959 filter:"contains",960 filtering: function (e) {961 //custom filtering logic962 if (e.filter != null){963 e.preventDefault();964 var filterWords = e.filter.value.split(" ");965 var filters = [];966 for(var i = 0; i < filterWords.length; i++){967 filters.push({field:"text", operator:"contains", value:filterWords[i]});968 }969 e.sender.dataSource.filter([970 {"logic":"and",971 "filters": filters972 }]); 973 } 974 }975 }).data('kendoMultiSelect');976 //initialize paw and stat selects977 getChartWidgetList();978 getDataWidgetList();979 $('select#map-tile-source-select').kendoMultiSelect({980 maxSelectedItems: 1, 981 change: function(e){982 var value = this.value();983 var widget = lastInvokerWidget.attr('id');984 }, 985 filter: "contains",986 filtering: function (e) {987 //custom filtering logic988 if (e.filter != null){989 e.preventDefault();990 var filterWords = e.filter.value.split(" ");991 var filters = [];992 for(var i = 0; i < filterWords.length; i++){993 filters.push({field:"text", operator:"contains", value:filterWords[i]});994 }995 e.sender.dataSource.filter([996 {"logic":"and",997 "filters": filters998 }]); 999 } 1000 }1001 }).data('kendoMultiSelect');1002 $('#map-dialog').kendoDialog({1003 width: "250px",1004 // title: "Download format",1005 closable: true,1006 modal: false,1007 content: "Please choose a format.",1008 actions: [1009 { text: 'PNG', action: downloadMapAsPNG },1010 { text: 'GeoJSON', action: downloadMapAsGJSON },1011 { text: 'KML', action: downloadMapAsKML },1012 // { text: 'Cancel', primary: true }1013 ],1014 // close: onClose1015 }).data('kendoDialog').close();1016 //customize tooltips with bootstrap1017 $('.ol-zoom-in, .ol-zoom-out').tooltip({1018 placement: 'right'1019 });1020 $('.ol-rotate-reset, .ol-attribution button[title]').tooltip({1021 placement: 'left'1022 });1023 $('div.chart-row').on('click', 'a#map-widget-delete-button', function(e){1024 if(!confirm("Are you sure you want to delete map widget ?")){1025 return1026 }1027 var main_panel = $(this).closest('section.main-panel') 1028 var widget_id = main_panel.find('div.gis-container').attr('id');1029 $.ajax({1030 method: 'POST', 1031 url: 'delete-map-widget',1032 dataType: 'json',1033 data: JSON.stringify({'wid': widget_id})1034 }).done(function(response){1035 main_panel.parent().remove();1036 }).fail(function(response){1037 alert('Delete operation failed.');1038 });1039 });1040 $('#GISModal').find('button#save-map-changes').on('click', function(e){1041 var title = $('#map-widget-title').val();1042 var index = $('#map-index').val();1043 var zoom = $('#map-zoom').val();1044 var lat = $('#map-center-lat').val();1045 var long = $('#map-center-long').val();1046 var tile_source = $('select#map-tile-source-select').data('kendoMultiSelect').value();1047 var data = {1048 'wid': lastInvokerWidget.attr('id'),1049 'name': title,1050 'index': index,1051 'zoom': zoom,1052 'lat': lat,1053 'long': long,1054 'tile_source': tile_source[0],1055 }1056 $.ajax({1057 method: 'POST', 1058 url: 'change-map-widget',1059 dataType: 'json',1060 data: JSON.stringify(data)1061 }).done(function(response){1062 $('#GISModal').modal('hide');1063 changeMapWidget(lastInvokerWidget);1064 }).fail(function(response){1065 alert('Failed. Widget not modified.');1066 });1067 });1068 loadMapWidgets();...
RangePicker.js
Source:RangePicker.js
1import PropTypes from 'prop-types';2import React from 'react';3import { FlatButton, Menu } from 's1-ui';4import Popover from 'material-ui/Popover';5import muiThemeable from 'material-ui/styles/muiThemeable';6import CalendarButton from './CalendarButton';7class RangePicker extends React.Component {8 constructor(props) {9 super(props);10 this.state = {11 open: false,12 defaultLabel: props.defaultLabel,13 start: null,14 end: null,15 };16 this.handleSelectMonth = this.handleSelectMonth.bind(this);17 }18 handleClick = (event) => {19 // This prevents ghost click.20 event.preventDefault();21 this.setState({22 open: true,23 anchorEl: event.currentTarget24 });25 };26 handleRequestClose = () => {27 this.setState({28 open: false,29 });30 };31 handleSelectMonth(row, col) {32 const month = col;33 const year = this.props.years[row];34 const date = new Date(year, month, 1);35 if (this.state.start && this.state.end) {36 this.setState({ start: null, end: null });37 } else if (this.state.start) {38 let minDate;39 let maxDate;40 if (this.state.start <= date) {41 minDate = this.state.start;42 maxDate = date;43 } else {44 minDate = date;45 maxDate = this.state.start;46 }47 if (this.props.input) {48 this.props.input.onChange({ StartDate: minDate, EndDate: maxDate });49 }50 if (this.props.onChange) {51 this.props.onChange({ StartDate: minDate, EndDate: maxDate });52 }53 this.setState({ end: maxDate, start: minDate });54 } else {55 this.setState({ start: date });56 }57 }58 handleYearSelect(row) {59 const year = this.props.years[row];60 if (this.props.input) {61 this.props.input.onChange(year);62 }63 if (this.props.onChange) {64 this.props.onChange(year);65 }66 this.setState({67 start: new Date(year, 0, 1),68 end: new Date(year, this.props.months.length - 1, 1)69 });70 }71 renderMonthBtns = (month, col, year, row) => {72 const {start, end} = this.state;73 const rangeExists = end && start;74 const btnDate = new Date(year, col, 1);75 const btnDateString = btnDate.toDateString();76 const isSingleDate = start && start.toDateString() === btnDateString;77 return (78 <CalendarButton79 date={month[0]}80 id={btnDateString}81 selected={((start <= btnDate && end >= btnDate)) || isSingleDate}82 onClick={() => this.handleSelectMonth(row, col)}83 key={btnDateString}84 range85 min={ rangeExists && start.toDateString() === btnDateString}86 max={rangeExists && end.toDateString() === btnDateString}87 center={rangeExists && (start <= btnDate && end >= btnDate)}88 />);89 }90 renderSelectedPeriod = () => {91 let string;92 if (this.state.start && this.state.end) {93 const options = { year: 'numeric', month: 'long' };94 string = `${this.state.start.toLocaleDateString('pt-br', options)} - ${this.state.end.toLocaleDateString('en-US', options)}`95 }96 return string;97 }98 99 render() {100 const styles = {101 row: {102 display: 'flex',103 flexDirection: 'column',104 padding: '15px'105 },106 week: {107 display: 'flex',108 flexDirection: 'row',109 //justifyContent: 'space-around',110 height: 34,111 marginBottom: 2,112 }113 };114 const { months, years, isYearPicker } = this.props;115 return (116 <div>117 <FlatButton118 onClick={this.handleClick}119 style={{ height: 50, backgroundColor: 'white', width: '100%' }}120 id="calendar"121 >122 <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>123 <div style={{ color: this.props.muiTheme.palette.secondaryColor }}>124 {this.renderSelectedPeriod()}125 </div>126 </div>127 </FlatButton>128 <Popover129 open={this.state.open}130 anchorEl={this.state.anchorEl}131 anchorOrigin={{ horizontal: 'left', vertical: 'bottom' }}132 targetOrigin={{ horizontal: 'left', vertical: 'top' }}133 onRequestClose={this.handleRequestClose}134 id="calendar-popover"135 >136 <Menu>137 <div style={styles.row}>138 {years.map((year, row) => <div key={row} style={styles.week}>139 <CalendarButton140 date={year}141 onClick={() => this.handleYearSelect(row)}142 />143 {months.map((month, col) => this.renderMonthBtns(month, col, year, row))}144 </div>)}145 </div>146 {/* <div>147 <FlatButton label="View all" labelStyle={ { textTransform: 'none', fontSize: 13 } } onClick={ () => { } } secondary />148 </div> */}149 </Menu>150 </Popover>151 </div>152 );153 }154}155RangePicker.propTypes = {156 month: PropTypes.string,157 year: PropTypes.number,158 defaultLabel: PropTypes.oneOfType([PropTypes.string.isRequired, PropTypes.number.isRequired]),159 muiTheme: PropTypes.object,160 input: PropTypes.object,161 onChange: PropTypes.func,162 months: PropTypes.array,163 years: PropTypes.array,164 isYearPicker: PropTypes.bool,165 locale: PropTypes.string166};167RangePicker.defaultProps = {168 locale: 'en-US'169};...
create-vacation-period-dialog.component.ts
Source:create-vacation-period-dialog.component.ts
1import { Component, Inject } from '@angular/core';2import { FormControl, FormGroup, Validators } from '@angular/forms';3import { MatDialogRef, MAT_DIALOG_DATA, MatDialog } from '@angular/material/dialog';4@Component({5 selector: 'app-create-vacation-period-dialog',6 templateUrl: './create-vacation-period-dialog.component.html',7 styleUrls: ['./create-vacation-period-dialog.component.less']8})9export class CreateVacationPeriodDialogComponent{10 minDate: Date;11 firstName: FormControl;12 lastName: FormControl;13 notes: FormControl;14 constructor(15 public dialogRef: MatDialogRef<CreateVacationPeriodDialogComponent, VacationPeriodDialogModel>,16 @Inject(MAT_DIALOG_DATA) public vacationPeriod: VacationPeriodDialogModel17 ){18 var today = new Date();19 this.minDate = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 0, 0, 0); // TODO: check if setHours works20 this.firstName = new FormControl(vacationPeriod.firstName, [Validators.maxLength(50), Validators.required]);21 this.lastName = new FormControl(vacationPeriod.firstName, [Validators.maxLength(50), Validators.required]);22 this.notes = new FormControl(vacationPeriod.firstName, [Validators.maxLength(200)]);23 }24 onNoClick(): void{25 this.dialogRef.close();26 }27 getFirstNameErrorMessage(): string{28 if (this.firstName.hasError('required')){29 return "First name is required";30 }31 return this.firstName.hasError('maxlength') ? 'Max length of first name is 50.' : '';32 }33 getLastNameErrorMessage(): string{34 if (this.lastName.hasError('required')){35 return "Last name is required";36 }37 return this.lastName.hasError('maxlength') ? 'Max length of last name is 50.' : '';38 }39 getNotesErrorMessage(): string{40 return this.notes.hasError('maxlength') ? 'Max length of notes is 50.' : '';41 }42 isFormInvalid(){43 var rangeExists = this.vacationPeriod.range !== undefined; // TODO: just a workaround ...44 return this.firstName.invalid || this.lastName.invalid || this.notes.invalid 45 || (rangeExists && (this.vacationPeriod.range.controls['from'].value === null || this.vacationPeriod.range.controls['to'].value === null));46 }47}48// TODO: change it to cleaner implementation49export class VacationPeriodDialogModel {50 public range: FormGroup;51 constructor(52 public firstName: string,53 public lastName: string,54 public notes: string,55 ) {56 this.range = new FormGroup({57 from: new FormControl<Date | null>(null),58 to: new FormControl<Date | null>(null),59 });60 }...
Using AI Code Generation
1const { rangeExists } = require('taiko');2const { openBrowser, goto, closeBrowser } = require('taiko');3(async () => {4 try {5 await openBrowser();6 await rangeExists({ start: "Google", end: "Gmail" });7 await closeBrowser();8 } catch (e) {9 console.error(e);10 } finally {11 }12})();13const { rangeExists } = require('taiko');14const { openBrowser, goto, closeBrowser } = require('taiko');15(async () => {16 try {17 await openBrowser();18 await rangeExists({ start: "Google", end: "Gmail" });19 await closeBrowser();20 } catch (e) {21 console.error(e);22 } finally {23 }24})();25`rangeDoesNotExist({ start: string, end: string, within: ElementHandle })`26const { rangeDoesNotExist } = require('taiko');27const { openBrowser, goto, closeBrowser } = require('taiko');28(async () => {29 try {30 await openBrowser();31 await rangeDoesNotExist({ start: "Google", end: "Gmail" });32 await closeBrowser();33 } catch (e) {34 console.error(e);35 } finally {36 }37})();38const { rangeDoesNotExist } = require('taiko');39const { openBrowser, goto, closeBrowser
Using AI Code Generation
1const { rangeExists, openBrowser, goto, closeBrowser } = require('taiko');2(async () => {3 try {4 await openBrowser();5 await goto("google.com");6 if (await rangeExists("Google")) {7 console.log("Google exists in the page");8 }9 } catch (e) {10 console.error(e);11 } finally {12 await closeBrowser();13 }14})();15const { rangeExists, openBrowser, goto, closeBrowser } = require('taiko');16(async () => {17 try {18 await openBrowser();19 await goto("google.com");20 if (!(await rangeExists("Google123"))) {21 console.log("Google123 does not exist in the page");22 }23 } catch (e) {24 console.error(e);25 } finally {26 await closeBrowser();27 }28})();29const { rangeExists, openBrowser, goto, closeBrowser } = require('taiko');30(async () => {31 try {32 await openBrowser();33 await goto("google.com");34 if (await rangeExists("Google", { within: "#hplogo" })) {35 console.log("Google exists in the page");36 }37 } catch (e) {38 console.error(e);39 } finally {40 await closeBrowser();41 }42})();43const { rangeExists, openBrowser, goto, closeBrowser } = require('taiko');44(async () => {45 try {46 await openBrowser();47 await goto("google.com");48 if (!(await rangeExists("Google123", { within: "#hplogo" }))) {49 console.log("Google123 does not exist in the page");50 }51 } catch (e) {52 console.error(e);53 } finally {54 await closeBrowser();55 }56})();
Using AI Code Generation
1var assert = require("assert");2var { openBrowser, goto, closeBrowser, rangeExists } = require("taiko");3(async () => {4 try {5 await openBrowser();6 await goto("google.com");7 assert.ok(await rangeExists("1", "100"));8 } catch (e) {9 console.error(e);10 } finally {11 await closeBrowser();12 }13})();14var assert = require("assert");15var { openBrowser, goto, closeBrowser, rangeExists } = require("taiko");16(async () => {17 try {18 await openBrowser();19 await goto("google.com");20 assert.ok(await rangeExists("1", "100"));21 } catch (e) {22 console.error(e);23 } finally {24 await closeBrowser();25 }26})();27var assert = require("assert");28var { openBrowser, goto, closeBrowser, rangeExists } = require("taiko");29(async () => {30 try {31 await openBrowser();32 await goto("google.com");33 assert.ok(await rangeExists("1", "100"));34 } catch (e) {35 console.error(e);36 } finally {37 await closeBrowser();38 }39})();40var assert = require("assert");41var { openBrowser, goto, closeBrowser, rangeExists } = require("taiko");42(async () => {43 try {44 await openBrowser();45 await goto("google.com");46 assert.ok(await rangeExists("1", "100"));47 } catch (e) {48 console.error(e);49 } finally {50 await closeBrowser();51 }52})();
Using AI Code Generation
1const { rangeExists } = require('taiko');2(async () => {3 try {4 await openBrowser();5 await goto("google.com");6 await rangeExists({from: 1, to: 3});7 } catch (e) {8 console.error(e);9 } finally {10 await closeBrowser();11 }12})();13### rangeExists(options[, options]) ⇒ <code>Promise.<boolean></code>14**Returns**: <code>Promise.<boolean></code> - true if the range exists, false otherwise. 15const { rangeExists } = require('taiko');16(async () => {17 try {18 await openBrowser();19 await goto("google.com");20 await rangeExists({from: 1, to: 3});21 } catch (e) {22 console.error(e);23 } finally {24 await closeBrowser();25 }26})();27### select(options[, options]) ⇒ <code>Promise.<ElementWrapper></code>28**Returns**: <code>Promise.<ElementWrapper></code> - Promise which resolves to the selected option.
Using AI Code Generation
1const { openBrowser, goto, closeBrowser } = require('taiko');2(async () => {3 try {4 await openBrowser();5 console.log(await rangeExists({start: 1, end: 2}));6 } catch (e) {7 console.error(e);8 } finally {9 await closeBrowser();10 }11})();12exists(selector, options)13exists(selector, options, cb)14exists(selector, cb)15exists(selector)16exists(selector, options, timeout)17exists(selector, options, timeout, cb)18exists(selector, timeout)19exists(selector, timeout, cb)20exists(selector, cb)21exists(selector)22exists(selector, options)23exists(selector, options, cb)24exists(selector, cb)25exists(selector)26exists(selector, options, timeout)27exists(selector, options, timeout, cb)28exists(selector, timeout)29exists(selector, timeout, cb)30exists(selector, cb)31exists(selector)32exists(selector, options)33exists(selector, options, cb)34exists(selector, cb)35exists(selector)36exists(selector, options, timeout)37exists(selector, options, timeout, cb)38exists(selector, timeout)39exists(selector, timeout, cb)40exists(selector, cb)41exists(selector)42exists(selector, options)43exists(selector, options, cb)44exists(selector, cb)45exists(selector)46exists(selector, options, timeout)47exists(selector, options, timeout, cb)48exists(selector, timeout)49exists(selector, timeout, cb)50exists(selector, cb)51exists(selector)52exists(selector, options)53exists(selector, options, cb)54exists(selector, cb)55exists(selector)56exists(selector, options, timeout)57exists(selector, options, timeout, cb)58exists(selector, timeout)59exists(selector, timeout, cb)60exists(selector, cb)61exists(selector)62exists(selector, options)63exists(selector, options, cb)64exists(selector, cb)65exists(selector)66exists(selector, options, timeout)67exists(selector, options, timeout, cb)68exists(selector, timeout)69exists(selector, timeout, cb)70exists(selector, cb)71exists(selector)72exists(selector, options)73exists(selector, options, cb)74exists(selector, cb)75exists(selector)76exists(selector, options, timeout)77exists(selector, options, timeout, cb)78exists(selector, timeout)79exists(selector, timeout, cb)80exists(selector, cb)81exists(selector)82exists(selector, options)83exists(selector, options, cb)84exists(selector, cb)85exists(selector)
Using AI Code Generation
1const { rangeExists, goto, openBrowser } = require('taiko');2(async () => {3 try {4 await openBrowser();5 let range = { start: { line: 0, column: 0 }, end: { line: 0, column: 0 } };6 console.log(await rangeExists(range));7 } catch (e) {8 console.error(e);9 } finally {10 await closeBrowser();11 }12})();13exists(selector, options?)14isVisible(selector, options?)15isHidden(selector, options?)16isDisabled(selector, options?)17isEditable(selector, options?)18isNotVisible(selector, options?)19isNotHidden(selector, options?)20isNotDisabled(selector, options?)21isNotEditable(selector, options?)22isFocused(selector, options?)23isNotFocused(selector, options?)24isChecked(selector, options?)25isNotChecked(selector, options?)26isPresent(selector, options?)27isNotPresent(selector, options?)
Using AI Code Generation
1const { openBrowser, goto, rangeExists } = require('taiko');2(async () => {3 try {4 await openBrowser();5 let exists = await rangeExists('myRange');6 exists = await rangeExists('myRange1');7 } catch (e) {8 console.error(e);9 } finally {10 await closeBrowser();11 }12})();
Using AI Code Generation
1const { rangeExists } = require('taiko');2const assert = require("assert");3(async () => {4 try {5 } catch (error) {6 console.error(error);7 } finally {8 closeBrowser();9 }10})();11const { textExists } = require('taiko');12const assert = require("assert");13(async () => {14 try {15 } catch (error) {16 console.error(error);17 } finally {18 closeBrowser();19 }20})();21const { textContent } = require('taiko');22const assert = require("assert");23(async () => {24 try {25 assert.equal(await textContent("Welcome"), "Welcome");26 } catch (error) {27 console.error(error);28 } finally {29 closeBrowser();30 }31})();32const { toRightOf, link } = require('taiko');33const assert = require("assert");34(async () => {35 try {36 assert.ok(await link("Get Started").exists());37 assert.ok(await link("Get Started").is(toRightOf("Welcome")));38 } catch (error) {39 console.error(error);40 } finally {41 closeBrowser();42 }43})();44const { toLeftOf, link } = require('taiko');
Using AI Code Generation
1const assert = require("assert");2const { goto, openBrowser, closeBrowser, $, button, text, write, click, into, dropDown, textBox, link, image, focus, toRightOf, toLeftOf, below, above, near, evaluate, reload, rangeExists } = require('taiko');3(async () => {4 try {5 await openBrowser({ headless: false });6 await focus($("#iframeResult"));7 await click("Try it");8 await write("50", into(textBox({id:"myRange"})));9 assert.ok(await rangeExists({id:"myRange"}));10 await closeBrowser();11 } catch (error) {12 console.error(error);13 } finally {14 }15})();
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!