Best JavaScript code snippet using playwright-internal
jquery.selectbox.min.js
Source:jquery.selectbox.min.js
1(function($) {2 $.extend($.fn, {3 selectBox : (function(){4 var typeTimer, typeSearch = '';56 var currentOpenedSelect;78 /**9 * Gets random string with 'n' characters10 */11 var randomString = function(n){12 var s= '';13 var randomchar=function(){14 var n= Math.floor(Math.random()*62);15 if(n<10) return n; //1-1016 if(n<36) return String.fromCharCode(n+55); //A-Z17 return String.fromCharCode(n+61); //a-z18 }19 while(s.length< n) s+= randomchar();20 return s;21 }2223 var keepOptionInView = function (select, li, center) {24 if (!li || li.length === 0) return;25 select = $(select);26 var control = select.selectBox('control'),27 options = select.selectBox('options'),28 scrollBox = select.selectBox('options'),29 top = parseInt(li.offset().top - scrollBox.position().top),30 bottom = parseInt(top + li.outerHeight());31 if (center) {32 scrollBox.scrollTop(li.offset().top - scrollBox.offset().top + scrollBox.scrollTop() - (scrollBox.height() / 2))33 } else {34 if (top < 0) {35 scrollBox.scrollTop(li.offset().top - scrollBox.offset().top + scrollBox.scrollTop())36 }37 if (bottom > scrollBox.height()) {38 scrollBox.scrollTop((li.offset().top + li.outerHeight()) - scrollBox.offset().top + scrollBox.scrollTop() - scrollBox.height())39 }40 }41 };4243 var escapeRegEx = function(text) {44 return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");45 };4647 /**48 * Private method to open options in generated selectbox49 */50 var openOptions = function(select){5152 if (select.is("[disabled]")){53 return false;54 }5556 //hide all other selected options57 $(".selectBox-dropdown-menu").hide();5859 //if options have been generated once show them, otherwise generate60 var optId = "opt-" + select.data("selectId");61 if ($("#"+optId).length > 0){62 options = $("#"+optId);6364 var id = select.data("selectId");65 var genSelect = $("#"+id);6667 /**68 * Hack to has minimum the width of the parents span69 */70 var selectWidth = select.innerWidth();71 var optionWidth;72 if(genSelect.innerWidth() > selectWidth ) {73 optionWidth = select.parents("span").innerWidth() ;74 }else {75 optionWidth = selectWidth;76 }7778 /**79 * Hack to have the selectbox opening in the right order80 */81 var topSelect = genSelect.offset().top + genSelect.outerHeight();8283 if( $(window).height() + $(window).scrollTop() - (topSelect + options.outerHeight()) < 0){84 topSelect = genSelect.offset().top - options.outerHeight();85 }86 options.width(optionWidth).css({87 top: topSelect,88 left: genSelect.offset().left89 });90 options.show();91 keepOptionInView(select, $("#"+optId).find("li.selectBox-selected"), true);92 }else{93 //generate new options for select - regexp incredible fast94 var optionsString = $.trim(select.html());9596 optionsString = optionsString.replace(/<(\s)*option/gim, '<li');97 optionsString = optionsString.replace(/option(\s)*>/gim, 'li>');98 optionsString = optionsString.replace(/>([^<>]+)<\//gim, '><a>$1</a></');99 var val = select.val();100101 //set current selected value102 var regExVal = RegExp("(value\\s*=\\s*['\"]"+escapeRegEx(val)+"\\s*['\"])", "im");103 var regExpInside = RegExp("(><a>"+escapeRegEx(val)+"</a)", "im");104105 if (regExVal.test(optionsString)){106 optionsString = optionsString.replace(regExVal, '$1 data-selected="true"');107 }else if(regExpInside.test(optionsString)){108 optionsString = optionsString.replace(regExpInside, ' data-selected="true"$1');109 }110111 //inform about option value112 var regExVal = RegExp("(value\\s*=\\s*['\"]?([^'\"<>]+)\\s*['\"]?)([\\s>]{1})", "gim");113 var regExpInside = RegExp("(><a>([^<>]+)</a)", "gim");114 if (regExVal.test(optionsString)){115 optionsString = optionsString.replace(regExVal, '$1 data-val="$2"$3');116 }else if(regExpInside.test(optionsString)){117 optionsString = optionsString.replace(regExpInside, ' data-val="$2"$1');118 }119 var options = $('<ul id="'+optId+'" class="selectBox-dropdown-menu selectBox-options" />').append(optionsString);120 if (typeof select.attr('class') !== 'undefined'){121 var classes = select.attr('class').split(" ");122 for (var i =0; i < classes.length - 1; i++){123 if (classes[i] != 'selectBox'){124 options.addClass(classes[i]+"-selectBox-dropdown-menu");125 }126 };127 }128129 options.find('li[data-selected="true"]').addClass("selectBox-selected");130131 var id = select.data("select-id");132 var genSelect = $("#"+id);133134135 options.find("li").on({136 click: function(){137 select.val($(this).attr("data-val")).trigger("selectBox-change", $(this));138 closeOptions(options);139 },140 mouseenter: function(){141 $(this).addClass("selectBox-hover");142 },143 mouseleave: function(){144 $(this).removeClass("selectBox-hover");145 }146 });147148 options.hide().appendTo("body");149150 /**151 * Hack to has minimum the width of the parents span152 */153 var selectWidth = select.innerWidth();154 var optionWidth;155 if(genSelect.innerWidth() > selectWidth ) {156 optionWidth = genSelect.innerWidth();157 }else {158 optionWidth = selectWidth;159 }160161 /**162 * Hack to have the selectbox opening in the right order163 */164 var topSelect = genSelect.offset().top + genSelect.outerHeight();165166 if( $(window).height() + $(window).scrollTop() - (topSelect + options.outerHeight()) < 0){167 topSelect = genSelect.offset().top - options.outerHeight();168 }169 options.width(optionWidth).css({170 top: topSelect,171 left: genSelect.offset().left172 });173 options.show();174 keepOptionInView(select, $("#"+optId).find("li.selectBox-selected"), true);175 }176177 }178179 var closeOptions = function(options){180 options.hide();181 }182183 var init = function(select){184185 var id = randomString(15);186187 var val = select.find('option:selected:first').text();188 if (typeof val === 'undefined' || val == ''){189 val = select.find('option:first').text();190 }191192 //created select193 var c_select = '<a tabindex="'+~~(select.attr('tabindex'))+'" class="selectBox selectBox-dropdown '+select.attr('class')+'" id="'+id+'">' +194 '<span class="selectBox-label">'+ val +'</span>'+195 '<span class="selectBox-arrow"></span>'+196 '</a>';197198 select.data('select-id', id);199 select.after(c_select).hide();200201 //listeners202 select.off("selectBox-change").on("selectBox-change", function(event, selectedLi) {203 refresh($(this));204 var id = select.data("select-id");205 $("#opt-"+id).find('.selectBox-selected').removeClass("selectBox-selected");206 $(selectedLi).addClass("selectBox-selected");207 $("#"+id).find(".selectBox-label").text($(selectedLi).find('a').text());208 select.trigger("change");209 if($.browser.msie && parseInt($.browser.version, 10) == 7){210 var selectedValue = $(selectedLi).attr('data-val').substring(0,2);211 $(select).find("option[value='" + selectedValue + "']").trigger("focus");212 }213 });214215216 $("#"+id).on("click focus", function(event){217 currentOpenedSelect = select;218 event.preventDefault()219 if (event.type == 'mousedown'){220 $(this).focus();221 return false;222 }223 openOptions(select);224 var id = select.data("select-id");225 $(".selectBox.em3").removeClass("em3");226 if (!$("#"+id).hasClass("disabled")){227 $("#"+id).addClass("em3");228 }229 select.focus();230 return false;231 });232233 }234235 var refresh = function(select){236 var id = select.data("select-id");237238 var el = $("#"+id).width(select.outerWidth()).attr("class","selectBox selectBox-dropdown")239 .addClass(select.attr('class')).attr('title', select.attr('title') || '')240 .attr('tabindex', ~~(select.attr('tabindex'))).css('display', 'inline-block');241242 var val = select.find("option[value='"+select.val()+"']:first").text();243 if (val === ''){244 val = select.val();245 }246247 el.find(".selectBox-label").text(val);248 }249250 var destroy = function(select){251 var id = select.data("select-id");252 $("#"+id).remove();253 $("#opt-"+id).remove();254 }255256 var setValues = function(select, data){257 select.val(data);258 destroy(select);259 init(select);260 }261262 var handleKeyDown = function (event) {263 options = $(".selectBox-dropdown-menu:visible");264 if (options.length == 0) return true;265266 var id = options.attr("id").replace('opt-','');267 var control = $("#"+id);268 var select = control.prev();269 if (control.hasClass('selectBox-disabled')) return true;270271272 switch (event.keyCode) {273 case 27:274 event.preventDefault();275 closeOptions(options);276 break;277 case 9:278 case 13:279280 //PTR 06861172 [Medium]: WWW-JJWDS-PROD QA flying dropdown list back281 if ($(".blockOverlay").length >= 1){282 event.preventDefault();283 return false;284 }285286 $(".selectBox.em3").removeClass("em3");287 var id = options.attr('id').replace('opt-','');288289 var nextTabIndex = event.shiftKey?~~$("#"+id).attr('tabindex') - 1:~~$("#"+id).attr('tabindex') + 1;290 var selected = options.find(".selectBox-selected");291 if (selected.length != 0){292 selected.trigger('click');293 }else{294 closeOptions(options);295 }296297 var next = $("[tabindex='"+nextTabIndex+"']:visible").not(".disabled, :disabled");298 if (next.length > 1){299 next.eq(1).focus();300 return false;301 }else if (next.length == 1){302 next.eq(0).focus();303 return false;304 }else{305 nextTabIndex++;306 var stopWhile = false;307 while(nextTabIndex != 500 && !stopWhile){308 if(($("[tabindex='"+nextTabIndex+"']").length > 0 && $("[tabindex='"+nextTabIndex+"']").is(":visible")) || nextTabIndex == 500){309 if(nextTabIndex == 500){ nextTabIndex = 1; } //reseting tabindex if finished310 stopWhile = true;311 } else {312 nextTabIndex++;313 }314 }315 $("[tabindex='"+nextTabIndex+"']:visible").not(".disabled, :disabled").focus();316 return false;317 }318 break;319 case 38:320 case 37:321 event.preventDefault();322 var selected = options.find(".selectBox-selected");323 if (selected.length == 0) selected = options.find('li:first');324325 var prev = selected.prev();326 if (prev.length == 0){327 prev = options.find('li:last');328 }329 selected.removeClass("selectBox-selected");330 prev.addClass("selectBox-selected");331 keepOptionInView(currentOpenedSelect, prev);332 break;333 case 40:334 case 39:335 event.preventDefault();336 var selected = options.find(".selectBox-selected");337 if (selected.length == 0) selected = options.find('li:first');338339 var next = selected.next();340 if (next.length == 0){341 next = options.find('li:first');342 }343 selected.removeClass("selectBox-selected");344 next.addClass("selectBox-selected");345 keepOptionInView(currentOpenedSelect, next);346 break347 default:348 // Type to find349 //if (!control.hasClass('selectBox-menuShowing')) showMenu(select);350 event.preventDefault();351 clearTimeout(typeTimer);352 typeSearch += String.fromCharCode(event.charCode || event.keyCode);353354 options.find('A').each(function() {355 if ($.trim($(this).text()).substr(0, typeSearch.length).toLowerCase() === typeSearch.toLowerCase()) {356 //addHover(select, $(this).parent());357 var selected = options.find(".selectBox-selected");358 if (selected.length == 0) selected = options.find('li:first');359360 selected.removeClass("selectBox-selected");361 $(this).parent().addClass("selectBox-selected");362363 keepOptionInView(select, $(this).parent());364 return false;365 }366 });367368 // Clear after a brief pause369 typeTimer = setTimeout(function() {370 typeSearch = '';371 }, 500);372 break;373 }374 return false;375 };376377 $(document).on("keydown", handleKeyDown);378379 $(document).on('mousedown', function(event) {380 if ($(event.target).is(".selectBox-dropdown-menu") || $(event.target).parents(".selectBox-dropdown-menu").length > 0)381 return;382 $(".selectBox-dropdown-menu").hide();383 $(".selectBox.em3").removeClass("em3");384 });385386 return function(action, data) {387388 switch (action) {389 case 'control':390 return $("#"+$(this).data("selectId"));391 break;392 case 'options':393 return $("#opt-"+$(this).data("selectId"));394 break;395 case 'value':396 $(this).each(function () {397 setValues($(this), data);398 });399 break;400 case 'refresh':401 $(this).each(function () {402 refresh($(this));403 });404 break;405 case 'destroy':406 $(this).each(function () {407 destroy($(this));408 });409 break;410 case 'generate':411 openOptions($(this));412 $(".selectBox-dropdown-menu").hide();413 break;414 default:415 $(this).each(function () {416 init($(this));417 });418 break;419 }420421 return $(this);422 }423 })()424 });
...
gen_ui.js
Source:gen_ui.js
1var dayjs = require('dayjs');2const List = require('list.js');3var ribbon = require('./ribbon');4const buildDay = (d) => {5 let new_elem = document.createElement("div");6 new_elem.id = d.format("DDMMYYYY");7 new_elem.innerHTML = `<p class="day_of_week">${d.format("ddd").toUpperCase()}</p><p class="short_date">${d.format("MMM D")}</p>`;8 9 new_elem.classList.add("week_day");10 if( d.isBefore(dayjs().subtract(1, 'day')) ){11 new_elem.classList.add("in_past");12 }13 return new_elem;14}15const buildEventListContainer = () => {16 let elc = document.createElement('div');17 elc.innerHTML = "<ul class='list' id='inner_list'></ul>"18 elc.classList.add("event_list_container");19 elc.id = "event_list_container";20 return elc;21}22const buildPrevButton = () => {23 let prevButton = document.createElement("div");24 prevButton.classList.add("prevButton")25 prevButton.innerHTML = `<button onClick="bundle.toggleWeek(0)">â</button>`;26 return prevButton;27}28const buildNextButton = () => {29 let nextButton = document.createElement("div");30 nextButton.classList.add("nextButton")31 nextButton.innerHTML = `<button onClick="bundle.toggleWeek(1)">â</button>`;32 return nextButton;33}34const buildEventLineItem = (e) => {35 let live_or_location;36 if(e.online === false){37 live_or_location = e.location;38 } else live_or_location = `<img height="20px" width="20px" src="https://cdn.jsdelivr.net/gh/WebPrismCo/Ribbon-Schedule-Widget@main/assets/noun_streaming_55528.png" alt="streaming by Javier Sánchez - javyliu from the Noun Project" ><span class="livestream_label">Livestream</span>`39 let onlineFlag = e.online == true ? "livestream" : "inperson";40 let lineItem = document.createElement("li");41 lineItem.setAttribute("data-id", dayjs(e.dateTime).format("DDMMYYYY"));42 lineItem.setAttribute("data-classtime", e.dateTime);43 // lineItem.setAttribute("data-online", e.online == true ? "livestream" : "inperson");44 lineItem.classList.add('schedule_item');45 lineItem.innerHTML = `<div class="time_dur">46 <span class="class_time">${dayjs(e.dateTime).format("hh:mm A")}</span><br>47 <span class="class_duration">${e.duration} min</span>48 <span class="class_location mobile_loc">${live_or_location}</span>49 <span class="livestream_inperson">${onlineFlag}</span>50 </div>51 <div class="class_location_container desktop_loc">52 <span class="class_location">${live_or_location}</span>53 </div>`;54 let signUpButton = document.createElement("div");55 signUpButton.classList.add("sign_up_button_container");56 signUpButton.innerHTML = `<a class="sign_up_button" href="${e.link}">Sign Up</a>`;57 if( e.image2 !== null){58 let teacherImg = document.createElement('div');59 teacherImg.classList.add("teacher_img");60 teacherImg.style.backgroundImage = `url("${encodeURI(e.image2)}")`;61 teacherImg.style.backgroundSize = 'cover';62 lineItem.appendChild(teacherImg);63 }64 let eTitle = document.createElement("div");65 eTitle.classList.add("event_title");66 eTitle.innerHTML = `<span>${e.title}</span><br><span class="teacher_name">${e.teacher || "No Teacher"}</span>`;67 lineItem.appendChild(eTitle);68 if(dayjs(e.dateTime).isBefore(dayjs()) == false ){69 lineItem.appendChild(signUpButton);70 } else {71 let passedButton = document.createElement("div");72 passedButton.classList.add("sign_up_button_container");73 passedButton.innerHTML = "<div class='sign_up_button disabled_sign_up'>Closed</div>";74 passedButton.disabled = true;75 lineItem.append(passedButton);76 }77 return lineItem;78}79const returnEmptyMessage = () => {80 if(document.querySelectorAll(".no_events").length !== 0 ){81 let emr = document.querySelectorAll(".no_events");82 if (emr.length > 0){83 emr[0].parentNode.removeChild(emr[0]);84 }85 }86 return `<div class="no_events"><img height='100px' width='100px' src="https://cdn.jsdelivr.net/gh/WebPrismCo/Ribbon-Schedule-Widget@latest/assets/noun_empty_glass_1245571.png" alt='empty glass by Waiyi Fung from the Noun Project'><p>No Matching Events</p></div>`87}88const buildEventList = (ribbonEvents) => {89 let list_container = document.getElementById("inner_list");90 list_container.innerHTML = "";91 if(ribbonEvents.length == 0){92 list_container.innerHTML = returnEmptyMessage();93 } else {94 ribbonEvents.forEach((rEvent) => {95 list_container.appendChild(buildEventLineItem(rEvent))96 });97 }98 buildDropdowns(ribbon.getUniqueTeachers(ribbonEvents), ribbonEvents.length, ribbonEvents);99}100const createUI = (elem, week, refDay) => {101 let week_container = document.createElement("div");102 week_container.id = "week_container";103 week_container.appendChild(buildPrevButton());104 week.forEach((day) => {105 let elem = buildDay(day);106 week_container.appendChild(elem);107 });108 week_container.appendChild(buildNextButton());109 110 let today_container = document.createElement("div");111 today_container.classList.add('today_container');112 today_container.innerHTML = `<span id="selected_date">${refDay.format("dddd, MMMM D, YYYY")}</span><button onClick='bundle.backToToday()'>Today</button>`;113 let filter_container = document.createElement("div");114 filter_container.id = "filter_container";115 filter_container.classList.add("filter_container");116 elem.appendChild(week_container);117 elem.appendChild(today_container);118 elem.appendChild(filter_container);119 elem.appendChild(buildEventListContainer());120}121const buildTeacherDropdown = (t) => {122 let genSelect = document.createElement("select");123 genSelect.classList.add("list_filter");124 genSelect.id = "teacher_filter";125 let selectAll = document.createElement("option");126 selectAll.value = "";127 selectAll.innerHTML = "All";128 genSelect.appendChild(selectAll);129 t.forEach((name) => {130 let genOption = document.createElement("option");131 genOption.value = name;132 genOption.innerHTML = name;133 genSelect.appendChild(genOption);134 })135 switch (t.length) {136 case 0:137 return undefined138 default:139 return genSelect140 }141}142const buildEventTypeDropdown = () => {143 let genSelect = document.createElement("select");144 genSelect.classList.add("list_filter");145 genSelect.id = "eventType_filter";146 genSelect.innerHTML = `<option value="">All</option><option value="inperson">In Person</option><option value="livestream">Livestream</option>`;147 return genSelect;148}149const buildLocationDropdown = (ev) => {150 let genSelect = document.createElement("select");151 genSelect.classList.add("list_filter");152 genSelect.id = "location_filter";153 let selectAll = document.createElement("option");154 selectAll.value = "";155 selectAll.innerHTML = "All";156 genSelect.appendChild(selectAll);157 let locations = ev.map((e) => e.location || null);158 let locSet = new Set(locations.filter(l => l !== null));159 locSet.forEach((loc) => {160 let genOption = document.createElement("option");161 genOption.value = loc;162 genOption.innerHTML = loc;163 genSelect.appendChild(genOption);164 });165 let fakeSelect = document.createElement("select");166 fakeSelect.classList.add("list_filter");167 fakeSelect.disabled = true;168 fakeSelect.innerHTML = "<option>Location</option>";169 switch (locSet.size) {170 case 0:171 return fakeSelect;172 default:173 return genSelect;174 }175}176const buildDropdowns = (teachers, length, events) => {177 let filter_container = document.getElementById("filter_container");178 if(filter_container.innerHTML !== ""){179 filter_container.innerHTML = ""180 }181 if(length > 0){182 let teachDrop = buildTeacherDropdown(teachers);183 if(teachDrop !== undefined) filter_container.appendChild(teachDrop);184 185 let stream_or_in_person = buildEventTypeDropdown();186 187 filter_container.appendChild(stream_or_in_person);188 let location_dropdown = buildLocationDropdown(events);189 if(location_dropdown !== undefined) filter_container.appendChild(location_dropdown);190 }191}192module.exports = {193 createUI: createUI,194 buildEventList: buildEventList,195 buildDropdowns: buildDropdowns,196 returnEmptyMessage: returnEmptyMessage...
script.js
Source:script.js
1$(document).ready(function() {2 // key needed to make calls to the moviesdb api3 const apikey = "ae0dcedd2f7e08d9767c06107fcd436d"4 let genre;5 let genres;6 // Set up genre selector7 $.get(`https://api.themoviedb.org/3/genre/movie/list?api_key=${apikey}&language=en-US`, function(data) {8 // set the data returned to a variable9 genre = data.genres10 // for each array returned by the genre call11 $.each(genre, function(index) {12 // Add it as an option in the 'genre' selector13 $('#genSelect').append(14 `15 <option value="${genre[index].id}">${genre[index].name}</option>16 `17 )18 })19 })20 // Get movies by rating/genre21 $(document).on('click', '#btn', function() {22 // Clear any posters that might be there23 $('.card').remove();24 // fetch 20 most popular movies25 $.get(`https://api.themoviedb.org/3/discover/movie?api_key=${apikey}&language=en-US&sort_by=popularity.desc&include_adult=false&include_video=false&page=1&with_watch_monetization_types=flatrate`, function(data) {26 // Grab the value of our rating/genre selectors27 let rating = $('#rating').val();28 let genSelect = $('#genSelect').val();29 30 // put the results from the api fetch into a variable31 let movie = data.results;32 // compares each movies genre ID's with the selected Genre's ID33 // If they match, return true34 function genCmp(genres) {35 for(let i = 0; i < genres.length; i++) {36 if(genres[i] == genSelect) {37 return true;38 }39 }40 }41 // For each movie that we returned42 $.each(movie, function(index) {43 genres = movie[index].genre_ids;44 // call the function comparing each movies genres with the selected one45 genCmp(genres);46 // if both the selectors are their default values47 if((rating == 'Rating') && (genSelect == 'undefined')) {48 // just return every movie49 $('#container').append(50 `51 <div class="card m-3 pt-1" style="width: 18rem;">52 <a target="_blank" href="https://www.themoviedb.org/movie/${movie[index].id}">53 <img src="https://image.tmdb.org/t/p/w500${movie[index].poster_path}" class="card-img-top" alt="...">54 </a> 55 <div class="card-body">56 <h5 class="card-title">${movie[index].title}</h5>57 <p class="card-text">${movie[index].overview}</p>58 </div>59 </div>60 `61 )62 // else, if rating is default but the genre matches63 } else if((rating == 'Rating') && genCmp(genres)){64 $('#container').append(65 `66 <div class="card m-3 pt-1" style="width: 18rem;">67 <a target="_blank" href="https://www.themoviedb.org/movie/${movie[index].id}">68 <img src="https://image.tmdb.org/t/p/w500${movie[index].poster_path}" class="card-img-top" alt="...">69 </a> 70 <div class="card-body">71 <h5 class="card-title">${movie[index].title}</h5>72 <p class="card-text">${movie[index].overview}</p>73 </div>74 </div>75 `76 )77 // else, if the movies rating avg is higher than the selectors,78 // and the genre is undefined79 } else if((movie[index].vote_average >= rating) && (genSelect == 'undefined')) {80 $('#container').append(81 `82 <div class="card m-3 pt-1" style="width: 18rem;">83 <a target="_blank" href="https://www.themoviedb.org/movie/${movie[index].id}">84 <img src="https://image.tmdb.org/t/p/w500${movie[index].poster_path}" class="card-img-top" alt="...">85 </a> 86 <div class="card-body">87 <h5 class="card-title">${movie[index].title}</h5>88 <p class="card-text">${movie[index].overview}</p>89 </div>90 </div>91 `92 )93 } else {94 // else, only return movies with both a vote average higher than the selected one95 // and matching the genre that was selected96 if((movie[index].vote_average >= rating) && genCmp(genres)) {97 $('#container').append(98 `99 <div class="card m-3 pt-1" style="width: 18rem;">100 <a target="_blank" href="https://www.themoviedb.org/movie/${movie[index].id}">101 <img src="https://image.tmdb.org/t/p/w500${movie[index].poster_path}" class="card-img-top" alt="...">102 </a> 103 <div class="card-body">104 <h5 class="card-title">${movie[index].title}</h5>105 <p class="card-text">${movie[index].overview}</p>106 </div>107 </div>108 `109 )110 }111 }112 })113 })114 })...
params_core.js
Source:params_core.js
1$(function () {2 var ParamsHeadersArr = $.parseJSON(ParamsHeaders);3 var ParamsDataArr = $.parseJSON(ParamsData);4 if ($.trim($('#params').html()) == '') $('#params').hide();5 else $('#params').show();67 $('#cat_id').change(function () {8 var val = $('#cat_id :selected').val().split('_');9 var params_show = [];10 podrazdel = val[1];11 $('#params').empty();12 if (ParamsHeadersArr[podrazdel]) {13 $.each(ParamsHeadersArr[podrazdel], function (i, v) {14 var check_ot_do = v.name.substr(v.name.length - 4, 4);15 if (check_ot_do != ': до') {16 if (check_ot_do != ': оÑ') {17 GenSelect = '<div class="param_element"><select id="param_data' + i + '" param="' + i + '" name="paramdata[' + i + ']"><option value="">' + v.name + '</option>';18 if (ParamsDataArr[i]) {19 $.each(ParamsDataArr[i], function (pid, dataO) {20 if (pid != 'child') {21 GenSelect += '<option value="' + dataO.id + '">' + dataO.value + '</option>';22 }23 });24 }25 GenSelect += '</select></div>';26 if (!(v.prior in params_show)) params_show[v.prior] = GenSelect;27 else params_show.push(GenSelect);28 //$('#params').append(GenSelect);29 }30 else {31 var name_param = v.name.substr(0, v.name.length - 4);32 var Input = '<div class="param_element">' +33 '<input type="text" placeholder="'+name_param+'" title="'+name_param+'" name="paramdata[' + i + ']">' +34 '<span>'+v.example+'</span>' +35 '</div>';36 if (!(v.prior in params_show)) params_show[v.prior] = Input;37 else params_show.push(Input);38 //$('#params').append(Input);39 }40 }41 });42 $.each(params_show, function (i, v) {43 $('#params').append(v);44 });45 params_show = [];46 }47 if ($('#params').html() == '') $('#params').hide();48 else $('#params').show();49 });5051 $('#params [name*="paramdata"]').live("change", function () {52 var val = $('#cat_id :selected').val().split('_');53 podrazdel = val[1];54 var value_id = $(this).val();55 var param_id = $(this).attr("param");56 if (ParamsHeadersArr[podrazdel] && ParamsHeadersArr[podrazdel][param_id] && ParamsHeadersArr[podrazdel][param_id]['child']) {57 $.each(ParamsHeadersArr[podrazdel][param_id]['child'], function (i) {58 $('#param_data' + i).remove();59 });60 }61 if (ParamsDataArr[param_id] && ParamsDataArr[param_id]['child'] && ParamsDataArr[param_id]['child'][value_id]) {62 newparam = ParamsDataArr[param_id]['child'][value_id][0]['param_id'];63 GenSelect = '<select id="param_data' + newparam + '" param="' + newparam + '" name="paramdata[' + newparam + ']"><option value="">' + ParamsHeadersArr[podrazdel][param_id]['child'][newparam].name + '</option>';64 $.each(ParamsDataArr[param_id]['child'][value_id], function (pid, dataO) {65 GenSelect += '<option value="' + dataO.id + '">' + dataO.value + '</option>';66 });67 GenSelect += '</select>';68 $('#param_data' + param_id).after(GenSelect);69 }7071 });
...
jquery-dropdate.js
Source:jquery-dropdate.js
1/*2 * Jquery DropDown Date v1.03 * https://github.com/luonghuycuong/jquery-dropdate4 * 5 */6(function ( $, window, document, undefined ) {7 var name = "dropdate",8 defaults = {9 minYear:1818,10 maxYear:new Date().getFullYear(),11 format:'yyyy/mm/dd',12 className:'dropdate-select',13 defaultDate:new Date()14 };15 function genselect(from, to, defaultValue){16 var str = '<select>';17 if(defaultValue){18 str += '<option value="">'+defaultValue+'</option>';19 }20 for(var i = from; i <= to; i++){21 str += '<option value="'+i+'">'+i+'</option>';22 }23 str += '</select>';24 return str;25 }26 27 function dropdate(el, options) {28 29 var s = this;30 s.opts = $.extend( {}, defaults, options );31 s.elem = $(el);32 init();33 function init(){34 var d = s.elem.val();35 d = d ? d : s.opts.defaultDate;36 37 s.opts.day = $(genselect(1, 31, 'Day'));38 s.opts.month = $(genselect(1, 12, 'Month'));39 s.opts.year = $(genselect(s.opts.minYear, s.opts.maxYear, 'Year'));40 41 var date = Date.parse(d);42 if(isNaN(date)){43 date = new Date();44 } else{45 var date = new Date(date);46 s.elem.val(date.format(s.opts.format));47 s.opts.year.val(date.getFullYear());48 s.opts.month.val(date.getMonth()+1);49 s.opts.day.val(date.getDate());50 }51 var required = s.elem.prop('required');52 53 s.opts.day.prop('required', required).addClass(s.opts.className);54 s.opts.month.prop('required', required).addClass(s.opts.className);55 s.opts.year.prop('required', required).addClass(s.opts.className);56 57 s.elem.after(s.opts.day);58 s.elem.after(s.opts.month);59 s.elem.after(s.opts.year);60 s.elem.prop('type', 'hidden');61 var selectchange = function(e){62 try {63 var date = new Date(s.opts.year.val(), s.opts.month.val() ? parseInt(s.opts.month.val())-1 : '', s.opts.day.val());64 s.elem.val(date.format(s.opts.format));65 } catch(err){66 s.elem.val('');67 }68 }69 70 s.opts.year.on('change', selectchange);71 s.opts.month.on('change', selectchange);72 s.opts.day.on('change', selectchange);73 }74 }75 76 $.fn[name] = function ( options ) {77 return this.each(function () {78 if (!$.data(this, name)) {79 $.data(this, name, new dropdate( this, options ));80 }81 });82 };83 ...
genSelect.test.js
Source:genSelect.test.js
...17 brands: { [value]: [value] },18 },19 };20 test('Renders the component', () => {21 const { getByRole, getAllByRole } = render(genSelect(type)(context));22 const component = getByRole(type);23 const options = getAllByRole('option');24 expect(component).toHaveClass(type);25 expect(component).toBeInTheDocument();26 expect(component.value).toEqual(context.state[type]);27 options.map((option) => expect(option).toBeInTheDocument());28 });29 test('When selected the option, action triggers', () => {30 const types = {31 make: { action: 'setMake' },32 model: { action: 'setModel' },33 };34 jest.spyOn(BrandManager, [types[type].action]).mockImplementation();35 const component = render(genSelect(type)(context)).getByRole(type);36 fireEvent.change(component, { target: { value }});37 expect(BrandManager[types[type].action])38 .toHaveBeenCalledWith({ ...context, data: value });39 });...
index.test.js
Source:index.test.js
...6// const value = `${i.toString(36)}${i}`;7// options.push(value);8// }9describe('VirtualSelect', () => {10 function genSelect(args) {11 return (12 <VirtualSelect {...args}>13 {options.map((v) => (14 <div key={v}>{v}</div>15 ))}16 </VirtualSelect>17 );18 }19 it('render success', () => {20 const wrapper = render(genSelect());21 expect(wrapper).toMatchSnapshot();22 });23 it('renders disabled select correctly', () => {24 const wrapper = render(genSelect({ disabled: true }));25 expect(wrapper).toMatchSnapshot();26 });27 it('should hide the dropdown when click outside', () => {28 const wrapper = render(genSelect());29 const inputEls = screen.getAllByPlaceholderText('please select');30 // second input box31 fireEvent(inputEls[1], new FocusEvent('focus'));32 // screen.debug()33 expect(wrapper.queryByText('abc')).toBeInTheDocument();34 fireEvent.click(document);35 expect(wrapper.queryByText('abc')).not.toBeInTheDocument();36 });...
inputControls.js
Source:inputControls.js
...4import PurchaseDate from './purchaseDate';5import AddButton from './addButton';6const InputControl = (context) =>7 <div role="inputControl">8 <span> Make { genSelect('make')(context) }</span>9 <span> Model { genSelect('model')(context) }</span>10 <span> Vehicle Number { VehicleNumber(context) }</span>11 <span> Purchase Date { PurchaseDate(context) }</span>12 <span> { AddButton(context) } </span>13 </div>;...
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 const input = await page.$('input[name="q"]');7 await input.press('a');8 await input.press('b');9 await input.press('c');10 await input.press('Enter');11 await browser.close();12})();
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.click('input[aria-label="Search"]');
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const page = await browser.newPage();5 await page.selectOption('select', { value: 'en' });6 await browser.close();7})();8const { chromium } = require('playwright');9(async () => {10 const browser = await chromium.launch();11 const page = await browser.newPage();12 await page.selectOption('select', { label: 'English' });13 await browser.close();14})();15const { chromium } = require('playwright');16(async () => {17 const browser = await chromium.launch();18 const page = await browser.newPage();19 await page.selectOption('select', { index: 1 });20 await browser.close();21})();22const { chromium } = require('playwright');23(async () => {24 const browser = await chromium.launch();25 const page = await browser.newPage();26 await page.selectOption('select', { value: 'en' });27 await page.selectOption('select', { value: 'fr' });28 await browser.close();29})();30const { chromium } = require('playwright');31(async () => {32 const browser = await chromium.launch();33 const page = await browser.newPage();34 await page.selectOption('select', { value: 'en' });35 await page.selectOption('select', { value: 'fr' });36 await page.selectOption('select', { value:
Using AI Code Generation
1const { genSelect } = require('playwright/lib/server/frames');2const { Page } = require('playwright/lib/server/page');3const { Frame } = require('playwright/lib/server/frame');4const { ElementHandle } = require('playwright/lib/server/dom');5const { JSHandle } = require('playwright/lib/server/javascript');6const { CDPSession } = require('playwright/lib/server/cdpsession');7const { genSelect } = require('playwright/lib/server/frames');8const { Page } = require('playwright/lib/server/page');9const { Frame } = require('playwright/lib/server/frame');10const { ElementHandle } = require('playwright/lib/server/dom');11const { JSHandle } = require('playwright/lib/server/javascript');12const { CDPSession } = require('playwright/lib/server/cdpsession');13const { genSelect } = require('playwright/lib/server/frames');14const { Page } = require('playwright/lib/server/page');15const { Frame } = require('playwright/lib/server/frame');16const { ElementHandle } = require('playwright/lib/server/dom');17const { JSHandle } = require('playwright/lib/server/javascript');18const { CDPSession } = require('playwright/lib/server/cdpsession');19const { genSelect } = require('playwright/lib/server/frames');20const { Page } = require('playwright/lib/server/page');21const { Frame } = require('playwright/lib/server/frame');22const { ElementHandle } = require('playwright/lib/server/dom');23const { JSHandle } = require('playwright/lib/server/javascript');24const { CDPSession } = require('playwright/lib/server/cdpsession');25const { genSelect } = require('playwright/lib/server/frames');26const { Page } = require('playwright/lib/server/page');27const { Frame } = require('playwright/lib/server/frame');28const { ElementHandle } = require('playwright/lib/server/dom');29const { JSHandle } = require('playwright/lib/server/javascript');30const { CDPSession } = require('playwright/lib/server/cdpsession');
Using AI Code Generation
1const { genSelect } = require('playwright-core/lib/server/dom.js');2const { jsdom } = require("jsdom");3const { JSDOM } = jsdom;4const dom = new JSDOM(`<!DOCTYPE html><p>Hello world</p>`);5const document = dom.window.document;6const body = document.querySelector('body');7const div = document.createElement('div');8div.setAttribute('id', 'container');9body.appendChild(div);10const container = document.querySelector('#container');11 </select>`;12const select = document.querySelector('#mySelect');13const option = document.querySelector('option[value="saab"]');14const result = genSelect(select, option);15console.log(result);16{ type: 'select',17 selected: true }
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.selectOption('select', 'javascript');7 await browser.close();8})();9const { chromium } = require('playwright');10(async () => {11 const browser = await chromium.launch();12 const context = await browser.newContext();13 const page = await context.newPage();14 await page.selectOption('select', { value: 'javascript' });15 await browser.close();16})();17const { chromium } = require('playwright');18(async () => {19 const browser = await chromium.launch();20 const context = await browser.newContext();21 const page = await context.newPage();22 await page.selectOption('select', { label: 'JavaScript' });23 await browser.close();24})();25const { chromium } = require('playwright');26(async () => {27 const browser = await chromium.launch();28 const context = await browser.newContext();29 const page = await context.newPage();30 await page.selectOption('select', { index: 1 });31 await browser.close();32})();33const { chromium } = require('playwright');34(async () => {35 const browser = await chromium.launch();36 const context = await browser.newContext();37 const page = await context.newPage();38 await page.selectOption('select', { value: 'javascript', label: 'JavaScript' });39 await browser.close();40})();
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!