Best JavaScript code snippet using devicefarmer-stf
participantsfilter.js
Source:participantsfilter.js
1// This file is part of Moodle - http://moodle.org/2//3// Moodle is free software: you can redistribute it and/or modify4// it under the terms of the GNU General Public License as published by5// the Free Software Foundation, either version 3 of the License, or6// (at your option) any later version.7//8// Moodle is distributed in the hope that it will be useful,9// but WITHOUT ANY WARRANTY; without even the implied warranty of10// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the11// GNU General Public License for more details.12//13// You should have received a copy of the GNU General Public License14// along with Moodle. If not, see <http://www.gnu.org/licenses/>.15/**16 * Participants filter managemnet.17 *18 * @module core_user/participants_filter19 * @copyright 2020 Andrew Nicols <andrew@nicols.co.uk>20 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later21 */22import CourseFilter from './local/participantsfilter/filtertypes/courseid';23import * as DynamicTable from 'core_table/dynamic';24import GenericFilter from './local/participantsfilter/filter';25import {get_strings as getStrings} from 'core/str';26import Notification from 'core/notification';27import Pending from 'core/pending';28import Selectors from './local/participantsfilter/selectors';29import Templates from 'core/templates';30import CustomEvents from 'core/custom_interaction_events';31import jQuery from 'jquery';32/**33 * Initialise the participants filter on the element with the given id.34 *35 * @param {String} participantsRegionId36 */37export const init = participantsRegionId => {38 // Keep a reference to the filterset.39 const filterSet = document.querySelector(`#${participantsRegionId}`);40 // Keep a reference to all of the active filters.41 const activeFilters = {42 courseid: new CourseFilter('courseid', filterSet),43 };44 /**45 * Get the filter list region.46 *47 * @return {HTMLElement}48 */49 const getFilterRegion = () => filterSet.querySelector(Selectors.filterset.regions.filterlist);50 /**51 * Add an unselected filter row.52 *53 * @return {Promise}54 */55 const addFilterRow = () => {56 const pendingPromise = new Pending('core_user/participantsfilter:addFilterRow');57 const rownum = 1 + getFilterRegion().querySelectorAll(Selectors.filter.region).length;58 return Templates.renderForPromise('core_user/local/participantsfilter/filterrow', {"rownumber": rownum})59 .then(({html, js}) => {60 const newContentNodes = Templates.appendNodeContents(getFilterRegion(), html, js);61 return newContentNodes;62 })63 .then(filterRow => {64 // Note: This is a nasty hack.65 // We should try to find a better way of doing this.66 // We do not have the list of types in a readily consumable format, so we take the pre-rendered one and copy67 // it in place.68 const typeList = filterSet.querySelector(Selectors.data.typeList);69 filterRow.forEach(contentNode => {70 const contentTypeList = contentNode.querySelector(Selectors.filter.fields.type);71 if (contentTypeList) {72 contentTypeList.innerHTML = typeList.innerHTML;73 }74 });75 return filterRow;76 })77 .then(filterRow => {78 updateFiltersOptions();79 return filterRow;80 })81 .then(result => {82 pendingPromise.resolve();83 return result;84 })85 .catch(Notification.exception);86 };87 /**88 * Get the filter data source node fro the specified filter type.89 *90 * @param {String} filterType91 * @return {HTMLElement}92 */93 const getFilterDataSource = filterType => {94 const filterDataNode = filterSet.querySelector(Selectors.filterset.regions.datasource);95 return filterDataNode.querySelector(Selectors.data.fields.byName(filterType));96 };97 /**98 * Add a filter to the list of active filters, performing any necessary setup.99 *100 * @param {HTMLElement} filterRow101 * @param {String} filterType102 * @param {Array} initialFilterValues The initially selected values for the filter103 * @returns {Filter}104 */105 const addFilter = async(filterRow, filterType, initialFilterValues) => {106 // Name the filter on the filter row.107 filterRow.dataset.filterType = filterType;108 const filterDataNode = getFilterDataSource(filterType);109 // Instantiate the Filter class.110 let Filter = GenericFilter;111 if (filterDataNode?.dataset.filterTypeClass) {112 Filter = await import(filterDataNode.dataset.filterTypeClass);113 }114 activeFilters[filterType] = new Filter(filterType, filterSet, initialFilterValues);115 // Disable the select.116 const typeField = filterRow.querySelector(Selectors.filter.fields.type);117 typeField.value = filterType;118 typeField.disabled = 'disabled';119 // Update the list of available filter types.120 updateFiltersOptions();121 return activeFilters[filterType];122 };123 /**124 * Get the registered filter class for the named filter.125 *126 * @param {String} name127 * @return {Object} See the Filter class.128 */129 const getFilterObject = name => {130 return activeFilters[name];131 };132 /**133 * Remove or replace the specified filter row and associated class, ensuring that if there is only one filter row,134 * that it is replaced instead of being removed.135 *136 * @param {HTMLElement} filterRow137 * @param {Bool} refreshContent Whether to refresh the table content when removing138 */139 const removeOrReplaceFilterRow = (filterRow, refreshContent) => {140 const filterCount = getFilterRegion().querySelectorAll(Selectors.filter.region).length;141 if (filterCount === 1) {142 replaceFilterRow(filterRow, refreshContent);143 } else {144 removeFilterRow(filterRow, refreshContent);145 }146 };147 /**148 * Remove the specified filter row and associated class.149 *150 * @param {HTMLElement} filterRow151 * @param {Bool} refreshContent Whether to refresh the table content when removing152 */153 const removeFilterRow = async(filterRow, refreshContent = true) => {154 const filterType = filterRow.querySelector(Selectors.filter.fields.type);155 const hasFilterValue = !!filterType.value;156 // Remove the filter object.157 removeFilterObject(filterRow.dataset.filterType);158 // Remove the actual filter HTML.159 filterRow.remove();160 // Update the list of available filter types.161 updateFiltersOptions();162 if (hasFilterValue && refreshContent) {163 // Refresh the table if there was any content in this row.164 updateTableFromFilter();165 }166 // Update filter fieldset legends.167 const filterLegends = await getAvailableFilterLegends();168 getFilterRegion().querySelectorAll(Selectors.filter.region).forEach((filterRow, index) => {169 filterRow.querySelector('legend').innerText = filterLegends[index];170 });171 };172 /**173 * Replace the specified filter row with a new one.174 *175 * @param {HTMLElement} filterRow176 * @param {Bool} refreshContent Whether to refresh the table content when removing177 * @param {Number} rowNum The number used to label the filter fieldset legend (eg Row 1). Defaults to 1 (the first filter).178 * @return {Promise}179 */180 const replaceFilterRow = (filterRow, refreshContent = true, rowNum = 1) => {181 // Remove the filter object.182 removeFilterObject(filterRow.dataset.filterType);183 return Templates.renderForPromise('core_user/local/participantsfilter/filterrow', {"rownumber": rowNum})184 .then(({html, js}) => {185 const newContentNodes = Templates.replaceNode(filterRow, html, js);186 return newContentNodes;187 })188 .then(filterRow => {189 // Note: This is a nasty hack.190 // We should try to find a better way of doing this.191 // We do not have the list of types in a readily consumable format, so we take the pre-rendered one and copy192 // it in place.193 const typeList = filterSet.querySelector(Selectors.data.typeList);194 filterRow.forEach(contentNode => {195 const contentTypeList = contentNode.querySelector(Selectors.filter.fields.type);196 if (contentTypeList) {197 contentTypeList.innerHTML = typeList.innerHTML;198 }199 });200 return filterRow;201 })202 .then(filterRow => {203 updateFiltersOptions();204 return filterRow;205 })206 .then(filterRow => {207 // Refresh the table.208 if (refreshContent) {209 return updateTableFromFilter();210 } else {211 return filterRow;212 }213 })214 .catch(Notification.exception);215 };216 /**217 * Remove the Filter Object from the register.218 *219 * @param {string} filterName The name of the filter to be removed220 */221 const removeFilterObject = filterName => {222 if (filterName) {223 const filter = getFilterObject(filterName);224 if (filter) {225 filter.tearDown();226 // Remove from the list of active filters.227 delete activeFilters[filterName];228 }229 }230 };231 /**232 * Remove all filters.233 *234 * @returns {Promise}235 */236 const removeAllFilters = () => {237 const pendingPromise = new Pending('core_user/participantsfilter:setFilterFromConfig');238 const filters = getFilterRegion().querySelectorAll(Selectors.filter.region);239 filters.forEach(filterRow => removeOrReplaceFilterRow(filterRow, false));240 // Refresh the table.241 return updateTableFromFilter()242 .then(result => {243 pendingPromise.resolve();244 return result;245 });246 };247 /**248 * Remove any empty filters.249 */250 const removeEmptyFilters = () => {251 const filters = getFilterRegion().querySelectorAll(Selectors.filter.region);252 filters.forEach(filterRow => {253 const filterType = filterRow.querySelector(Selectors.filter.fields.type);254 if (!filterType.value) {255 removeOrReplaceFilterRow(filterRow, false);256 }257 });258 };259 /**260 * Update the list of filter types to filter out those already selected.261 */262 const updateFiltersOptions = () => {263 const filters = getFilterRegion().querySelectorAll(Selectors.filter.region);264 filters.forEach(filterRow => {265 const options = filterRow.querySelectorAll(Selectors.filter.fields.type + ' option');266 options.forEach(option => {267 if (option.value === filterRow.dataset.filterType) {268 option.classList.remove('hidden');269 option.disabled = false;270 } else if (activeFilters[option.value]) {271 option.classList.add('hidden');272 option.disabled = true;273 } else {274 option.classList.remove('hidden');275 option.disabled = false;276 }277 });278 });279 // Configure the state of the "Add row" button.280 // This button is disabled when there is a filter row available for each condition.281 const addRowButton = filterSet.querySelector(Selectors.filterset.actions.addRow);282 const filterDataNode = filterSet.querySelectorAll(Selectors.data.fields.all);283 if (filterDataNode.length <= filters.length) {284 addRowButton.setAttribute('disabled', 'disabled');285 } else {286 addRowButton.removeAttribute('disabled');287 }288 if (filters.length === 1) {289 filterSet.querySelector(Selectors.filterset.regions.filtermatch).classList.add('hidden');290 filterSet.querySelector(Selectors.filterset.fields.join).value = 2;291 filterSet.dataset.filterverb = 2;292 } else {293 filterSet.querySelector(Selectors.filterset.regions.filtermatch).classList.remove('hidden');294 }295 };296 /**297 * Set the current filter options based on a provided configuration.298 *299 * @param {Object} config300 * @param {Number} config.jointype301 * @param {Object} config.filters302 * @returns {Promise}303 */304 const setFilterFromConfig = config => {305 const filterConfig = Object.entries(config.filters);306 if (!filterConfig.length) {307 // There are no filters to set from.308 return Promise.resolve();309 }310 // Set the main join type.311 filterSet.querySelector(Selectors.filterset.fields.join).value = config.jointype;312 const filterPromises = filterConfig.map(([filterType, filterData]) => {313 if (filterType === 'courseid') {314 // The courseid is a special case.315 return false;316 }317 const filterValues = filterData.values;318 if (!filterValues.length) {319 // There are no values for this filter.320 // Skip it.321 return false;322 }323 return addFilterRow().then(([filterRow]) => addFilter(filterRow, filterType, filterValues));324 }).filter(promise => promise);325 if (!filterPromises.length) {326 return Promise.resolve();327 }328 return Promise.all(filterPromises).then(() => {329 return removeEmptyFilters();330 })331 .then(updateFiltersOptions)332 .then(updateTableFromFilter);333 };334 /**335 * Update the Dynamic table based upon the current filter.336 *337 * @return {Promise}338 */339 const updateTableFromFilter = () => {340 const pendingPromise = new Pending('core_user/participantsfilter:updateTableFromFilter');341 const filters = {};342 Object.values(activeFilters).forEach(filter => {343 filters[filter.filterValue.name] = filter.filterValue;344 });345 return DynamicTable.setFilters(346 DynamicTable.getTableFromId(filterSet.dataset.tableRegion),347 {348 jointype: parseInt(filterSet.querySelector(Selectors.filterset.fields.join).value, 10),349 filters,350 }351 )352 .then(result => {353 pendingPromise.resolve();354 return result;355 })356 .catch(Notification.exception);357 };358 /**359 * Fetch the strings used to populate the fieldset legends for the maximum number of filters possible.360 *361 * @return {array}362 */363 const getAvailableFilterLegends = async() => {364 const maxFilters = document.querySelector(Selectors.data.typeListSelect).length - 1;365 let requests = [];366 [...Array(maxFilters)].forEach((_, rowIndex) => {367 requests.push({368 "key": "filterrowlegend",369 "component": "core_user",370 // Add 1 since rows begin at 1 (index begins at zero).371 "param": rowIndex + 1372 });373 });374 const legendStrings = await getStrings(requests)375 .then(fetchedStrings => {376 return fetchedStrings;377 })378 .catch(Notification.exception);379 return legendStrings;380 };381 // Add listeners for the main actions.382 filterSet.querySelector(Selectors.filterset.region).addEventListener('click', e => {383 if (e.target.closest(Selectors.filterset.actions.addRow)) {384 e.preventDefault();385 addFilterRow();386 }387 if (e.target.closest(Selectors.filterset.actions.applyFilters)) {388 e.preventDefault();389 updateTableFromFilter();390 }391 if (e.target.closest(Selectors.filterset.actions.resetFilters)) {392 e.preventDefault();393 removeAllFilters();394 }395 });396 // Add the listener to remove a single filter.397 filterSet.querySelector(Selectors.filterset.regions.filterlist).addEventListener('click', e => {398 if (e.target.closest(Selectors.filter.actions.remove)) {399 e.preventDefault();400 removeOrReplaceFilterRow(e.target.closest(Selectors.filter.region), true);401 }402 });403 // Add listeners for the filter type selection.404 let filterRegion = jQuery(getFilterRegion());405 CustomEvents.define(filterRegion, [CustomEvents.events.accessibleChange]);406 filterRegion.on(CustomEvents.events.accessibleChange, e => {407 const typeField = e.target.closest(Selectors.filter.fields.type);408 if (typeField && typeField.value) {409 const filter = e.target.closest(Selectors.filter.region);410 addFilter(filter, typeField.value);411 }412 });413 filterSet.querySelector(Selectors.filterset.fields.join).addEventListener('change', e => {414 filterSet.dataset.filterverb = e.target.value;415 });416 const tableRoot = DynamicTable.getTableFromId(filterSet.dataset.tableRegion);417 const initialFilters = DynamicTable.getFilters(tableRoot);418 if (initialFilters) {419 const initialFilterPromise = new Pending('core_user/participantsfilter:setFilterFromConfig');420 // Apply the initial filter configuration.421 setFilterFromConfig(initialFilters)422 .then(() => initialFilterPromise.resolve())423 .catch();424 }...
Using AI Code Generation
1var stf = require('devicefarmer-stf-provider');2var adb = require('adbkit');3var client = adb.createClient();4client.listDevices()5 .then(function(devices) {6 return Promise.all(devices.map(function(device) {7 return client.shell(device.id, 'getprop ro.build.version.release')8 .then(adb.util.readAll)9 .then(function(output) {10 return {id: device.id, version: parseInt(output.toString().trim())};11 })12 }))13 })14 .then(function(devices) {15 var filter = stf.filterRow(devices, function(row) {16 return row.version >= 4;17 });18 console.log(filter);19 })20 .catch(function(err) {21 console.error('Something went wrong:', err.stack);22 });23[ { id: 'emulator-5554', version: 7 },24 { id: 'emulator-5556', version: 7 },25 { id: 'emulator-5558', version: 7 },26 { id: 'emulator-5560', version: 7 },27 { id: 'emulator-5562', version: 7 },28 { id: 'emulator-5564', version: 7 },29 { id: 'emulator-5566', version: 7 },30 { id: 'emulator-5568', version: 7 },31 { id: 'emulator-5570', version: 7 },32 { id: 'emulator-5572', version: 7 },33 { id: 'emulator-5574', version: 7 },34 { id: 'emulator-5576', version: 7 },35 { id: 'emulator-5578', version: 7 },36 { id: 'emulator-5580', version: 7 },37 { id: 'emulator-5582', version: 7 },38 { id: 'emulator-5584', version: 7 },39 { id: 'emulator-5586', version: 7 },40 { id: 'emulator-5588', version: 7 },41 { id: 'emulator-5590', version: 7 },42 { id: 'emulator-5592', version: 7 },43 { id: 'emulator-5594
Using AI Code Generation
1var stf = require('devicefarmer-stf')2var util = require('util')3client.filterRow({4}).then(function(row) {5 console.log(util.inspect(row, { depth: null }))6})7var stf = require('devicefarmer-stf')8var util = require('util')9client.filterRow({10}).then(function(row) {11 console.log(util.inspect(row, { depth: null }))12})13var stf = require('devicefarmer-stf')14var util = require('util')15client.filterRow({16}).then(function(row) {17 console.log(util.inspect(row, { depth: null }))18})19var stf = require('devicefarmer-stf')20var util = require('util')21client.filterRow({22}).then(function(row) {23 console.log(util.inspect(row, { depth: null }))24})25var stf = require('devicefarmer-stf')26var util = require('util')27client.filterRow({28}).then(function(row) {29 console.log(util.inspect(row, { depth: null }))30})
Using AI Code Generation
1var stf = require('devicefarmer-stf-client');2client.filterRow('test', 'test', function(err, devices) {3 console.log(devices);4});5var stf = require('devicefarmer-stf-client');6client.getRow('test', 'test', function(err, devices) {7 console.log(devices);8});9var stf = require('devicefarmer-stf-client');10client.getRow('test', 'test', function(err, devices) {11 console.log(devices);12});13var stf = require('devicefarmer-stf-client');14client.getRow('test', 'test', function(err, devices) {15 console.log(devices);16});17var stf = require('devicefarmer-stf-client');18client.getRow('test', 'test', function(err, devices) {19 console.log(devices);20});21var stf = require('devicefarmer-stf-client');22client.getRow('test', 'test', function(err, devices) {23 console.log(devices);24});25var stf = require('devicefarmer-stf-client');26client.getRow('test', 'test', function(err, devices) {27 console.log(devices);28});29var stf = require('devicefarmer-stf-client');
Using AI Code Generation
1var adb = require('adbkit');2var client = adb.createClient();3client.listDevices()4 .then(function(devices) {5 return Promise.all(devices.map(function(device) {6 return client.shell(device.id, 'dumpsys window')7 .then(adb.util.readAll)8 .then(function(output) {9 console.log('[%s] %s', device.id, output.toString().trim());10 })11 }))12 })13 .catch(function(err) {14 console.error('Something went wrong:', err.stack)15 })16var adb = require('adbkit');17var client = adb.createClient();18client.listDevices()19 .then(function(devices) {20 return Promise.all(devices.map(function(device) {21 return client.shell(device.id, 'dumpsys window')22 .then(adb.util.readAll)23 .then(function(output) {24 console.log('[%s] %s', device.id, output.toString().trim());25 })26 }))27 })28 .catch(function(err) {29 console.error('Something went wrong:', err.stack)30 })31var adb = require('adbkit');32var client = adb.createClient();33client.listDevices()34 .then(function(devices) {35 return Promise.all(devices.map(function(device) {36 return client.shell(device.id, 'dumpsys window')37 .then(adb.util.readAll)38 .then(function(output) {39 console.log('[%s] %s', device.id, output.toString().trim());40 })41 }))42 })43 .catch(function(err) {44 console.error('Something went wrong:', err.stack)45 })
Using AI Code Generation
1var stf = require('devicefarmer-stf');2var options = {3};4var client = stf.connect(options);5client.getDevices().then(function(devices) {6 var filteredDevices = client.filterRow(devices, {7 });8 console.log(filteredDevices);9});10[ { serial: '0123456789ABCDEF',11 display: { id: 0, width: 1080, height: 1920, xdpi: 420.13, ydpi: 419.83 },12 phone: { network: 'UNKNOWN', signal: 0 },13 battery: { status: 2, health: 2, level: 100, scale: 100, plugged: 0, temp: 303, voltage: 4114 },14 providerMetadata: {},
Using AI Code Generation
1var stf = require('devicefarmer-stf-client');2client.filterRow('serial','HT5CZJT00660').then(function(device){3console.log(device);4});5var stf = require('devicefarmer-stf-client');6client.filterRow('serial','HT5CZJT00660').then(function(device){7console.log(device);8});9var stf = require('devicefarmer-stf-client');10client.filterRow('serial','HT5CZJT00660').then(function(device){11console.log(device);12});13var stf = require('devicefarmer-stf-client');14client.filterRow('serial','HT5CZJT00660').then(function(device){15console.log(device);16});17var stf = require('devicefarmer-stf-client');18client.filterRow('serial','HT5CZJT00660').then(function(device){19console.log(device);20});21var stf = require('devicefarmer-stf-client');22client.filterRow('serial','HT5CZJT00660').then(function(device){23console.log(device);24});25var stf = require('devicefarmer-stf-client');26client.filterRow('serial','HT5CZJT00660').then(function(device){27console.log(device);28});
Using AI Code Generation
1var stf = require('devicefarmer-stf');2var filter = new stf.FilterRow('test');3filter.add('manufacturer', 'samsung');4filter.add('model', 'GT-I9505');5filter.add('version', '4.4.2');6filter.add('serial', '0123456789ABCDEF');7console.log(filter.filterRow());8var stf = require('devicefarmer-stf');9var filter = new stf.FilterRow('test');10filter.add('manufacturer', 'samsung');11filter.add('model', 'GT-I9505');12filter.add('version', '4.4.2');13filter.add('serial', '0123456789ABCDEF');14console.log(filter.filterRow());15var stf = require('devicefarmer-stf');16var filter = new stf.FilterRow('test');17filter.add('manufacturer', 'samsung');18filter.add('model', 'GT-I9505');19filter.add('version', '4.4.2');20filter.add('serial', '0123456789ABCDEF');21console.log(filter.filterRow());22var stf = require('devicefarmer-stf');23var filter = new stf.FilterRow('test');24filter.add('manufacturer', 'samsung');25filter.add('model', 'GT-I9505');26filter.add('version', '4
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!!