Best JavaScript code snippet using playwright-internal
u-db.service.js
Source:u-db.service.js  
1import React  from 'react'2import ReactDOM from 'react-dom';3import * as moment from 'moment';4import * as $ from 'jquery';5import { translate } from '../services/u-language-codes.service';6import ufwX from '../services/ufw-interface';7import ugsX from '../services/u-generics.service';8export class UDbService {9	view_key_value = "";10	recordPosition = 0;11	view_tab = 0;12	primary_dataset = null;13	on_binding = false;14	auto_update = false;15	datasets = "";16	context = null;17	ufw = null;18	ugs = null;19	constructor() {20		this.ufw = ufwX;21		this.ugs = ugsX;22	}23	//=================================================================================24	selectTab(class_name, tab) { 	//tabindex start at 0 25		$(class_name + ' li').removeClass('active');26		$('.tab-content .tab-pane').removeClass('active');27		$('a[href="#tab' + tab + '"]').closest('li').addClass('active');28		$('#tab' + tab).addClass('active');29	}30	//=================================================================================31	prepareDatasets(businessObject) {32		this.datasets = businessObject.datasets;33		if (!this.datasets) return;34		for (var i = 0; i < this.datasets.length; i++) {35			this.datasets[i].dataset_format = JSON.parse(this.datasets[i].dataset_format);36			this.datasets[i].dataset_content = JSON.parse(this.datasets[i].dataset_content);37		}38		this.primary_dataset = this.datasets[0];39		if (this.primary_dataset.dataset_content.length === 0) {40			this.createNewPrimaryRow();41		}42		if (this.recordPosition > this.primary_dataset.dataset_content.length - 1)43			this.recordPosition = this.primary_dataset.dataset_content.length - 1;44	}45	//=================================================================================46	createNewPrimaryRow() {47		var newRow = {};48		for (var key in this.primary_dataset.dataset_format[0]) {49			newRow[key] = '';50		}51		newRow['__State'] = '1';52		this.primary_dataset.dataset_content.push(newRow);53	}54	//=================================================================================55	genericActionsExit() {56		this.genericActions('Exit');57	}58	//=================================================================================59	genericActions(action) {60		if (action) {61			if (action.includes("New")) {62				this.onNewRecordEvent();63				return false;64			}65			if (action.includes("Delete")) {66				this.onDeleteRecordEvent();67				return false;68			}69			if (action.includes("Exit")) {70				this.onBackToCallerEvent();71				return false;72			}73		}74		return true;75	}76	//=================================================================================77	bindData(caller) {78		if (caller) this.context = caller;79		var element_navpos = document.getElementById('eid_nav_position');80		if (element_navpos) {81			var navpos = (this.recordPosition + 1).toString() + " / " + this.primary_dataset.dataset_content.length.toString();82			element_navpos.value = navpos;83		}84		this.on_binding = true;85		if (this.context && (typeof this.context.beforeBinding !== 'undefined' && typeof this.context.beforeBinding === 'function')) {86			this.context.beforeBinding();87		}88		this.bindInputs();89		this.bindPhones();90		this.bindAddresses();91		this.bindTables();92		this.bindSelects();93		this.bindReactSelects();94		if (this.context && (typeof this.context.afterBinding !== 'undefined' && typeof this.context.afterBinding === 'function')) {95			this.context.afterBinding();96		}97		this.on_binding = false;98		this.setNavigationButtonsBehavior();99	}100	//=================================================================================101	bindReactSelects() {102		var slct = null;103		for (let i = 1; i <= 10;++i) {104			slct = document.getElementById('ReactSelect' + i.toString());105			if (slct) {106				this.context.setSelectionList(slct, 1);107			}108			else {109				return;110            }111		}112	}113	//=================================================================================114	bindSelects() {115		var value = '';116		Array.from(document.getElementsByTagName('Select')).forEach((select) => {117			var dataset_name = select.getAttribute('data-dataset');118			if (dataset_name) {119				this.context.setSelectionList(select, dataset_name);120			}121			var bind = select.getAttribute('data-bind');122			if (bind) {123				value = this.primary_dataset.dataset_content[this.recordPosition][bind];124				if (!value) value = '';125				this.context.setSelectedValue(select.id, value);126			}127		})128	}129  //=================================================================================130	bindTables() {131		Array.from(document.getElementsByTagName('table')).forEach((table) => {132			var tableRows = "";133			var dataset_name = table.getAttribute('data-bind');134			if (dataset_name) {135				var dataset = this.getDataset(dataset_name);136				if (dataset) {137					while (table.tBodies.length > 0) {138						if (table.id === 'eid_main_table') return;139						table.removeChild(table.tBodies[0])140					}141					var tblBody = document.createElement("tbody");142					table.appendChild(tblBody);143					if ((table.id !== 'eid_main_table') && (dataset.foreign_key_field)) {144						var parentKeyField = this.primary_dataset.dataset_content[this.recordPosition][dataset.parent_key_field];145						tableRows = dataset.dataset_content.filter(item => {146							return item[dataset.foreign_key_field] === parentKeyField147						});148					}149					else {150						tableRows = dataset.dataset_content;151					}152					tableRows.forEach((tableRow) => {153						var row = this.createTableRow(table, tableRow);154						tblBody.appendChild(row);155					});156				}157			}158		})159	}160	//=================================================================================161	createTableRow(table, json_table_row) {162		var _row = document.createElement('tr');163		Array.from(table.getElementsByTagName('th')).forEach((header) => {164			var _cell = document.createElement('td');165			_cell.style.cssText = 'margin: 0 !important; padding-right: 3px; padding-left: 3px; border: solid 1px gray; vertical-align: middle; background-color: white; color: black';166			var _label = document.createElement("Label");167			var bind = header.getAttribute('data-bind');168			if (bind && json_table_row[bind]) {169				_label.innerHTML = json_table_row[bind];170			}171			_cell.appendChild(_label);172			_row.appendChild(_cell);173		});174		return _row;175	}176	//=================================================================================177	getDataset(dataset_name) {178		if (this.datasets) {179			for (var gdi = 0; gdi < this.datasets.length; gdi++) {180				if (dataset_name === this.datasets[gdi].dataset_name) {181					return this.datasets[gdi];182				}183			}184		}185		return null;186	}187	//=================================================================================188	bindInputs() {189		Array.from(document.getElementsByTagName('input')).forEach((input) => {190			var bind = input.getAttribute('data-bind');191			if (bind) {192				var value = this.primary_dataset.dataset_content[this.recordPosition][bind];193				if (!value) value = '';194				if (input.type === 'checkbox') {195					input.value = value === "1" ? 'on' : 'off';196					input.checked = value === "1" ? true : false;197				}198				else {199					input.value = value;200				}201			}202		});203	}204	//=================================================================================205	bindPhones() {206		Array.from(document.querySelectorAll("[href*=tel]")).forEach((phone) => {207			var bind = phone.getAttribute('data-bind');208			if (bind) {209				phone.style.textAlign = localStorage.getItem('direction') === "ltr" ? "left" : "right";210				var value = this.primary_dataset.dataset_content[this.recordPosition][bind];211				if (value) {212					//phone.text = value;213					phone.innerHTML = value;214					phone.href = "tel:" + value;215				}216			}217		});218	}219	//=================================================================================220	bindAddresses() {221		Array.from(document.querySelectorAll("[href*=waze]")).forEach((address) => {222			var bind = address.getAttribute('data-bind');223			if (bind) {224				//address.style.textAlign = localStorage.getItem('direction') === "ltr" ? "left" : "right";225				var value = this.primary_dataset.dataset_content[this.recordPosition][bind];226				if (value) { // .css("text-align", "center");227					//address.text = value;228					address.innerHTML = value;229					address.href = "waze://?q=" + value;230				}231			}232		});233	}234	//=================================================================================235	setNavigationButtonsBehavior() {236		var prevButton = document.getElementById("eid_nav_prev");237		if (prevButton) (prevButton).disabled = (this.recordPosition === 0);238		//if (prevButton) (prevButton as HTMLInputElement).disabled = (this.recordPosition === 0);239		var nextButton = document.getElementById("eid_nav_next");240		if (nextButton) (nextButton).disabled = (this.recordPosition >= this.primary_dataset.dataset_content.length - 1);241		//if (nextButton) (nextButton as HTMLInputElement).disabled = (this.recordPosition >= this.primary_dataset.dataset_content.length - 1);242	}243	//=================================================================================244	navigatePrev() {245		if (this.recordPosition === 0) return;246		if (!this.onAboutToNavigate()) return;247		this.recordPosition--;248		this.bindData();249		if (this.context &&250			typeof this.context.setMainTableCursor !== 'undefined' &&251			typeof this.context.setMainTableCursor === 'function') {252  			this.context.setMainTableCursor();253		}254	}255	//=================================================================================256	navigateNext() {257		if (this.recordPosition >= this.primary_dataset.dataset_content.length - 1) return;258		if (!this.onAboutToNavigate()) return;259		this.recordPosition++;260		this.bindData();261		if (this.context &&262			typeof this.context.setMainTableCursor !== 'undefined' &&263			typeof this.context.setMainTableCursor === 'function') {264	  		this.context.setMainTableCursor();265		}266	}267	//=================================================================================268	confirmExit() {269		this.onAboutToNavigate()270	}271	//=================================================================================272	onNewRecordEvent() {273		if (!this.onAboutToNavigate()) return;274		this.createNewPrimaryRow();275		this.recordPosition = this.primary_dataset.dataset_content.length - 1;276		this.bindData();277	}278	//=================================================================================279	onDeleteRecordEvent() {280		if (this.primary_dataset.dataset_content[this.recordPosition].__State !== '1') {// Indicate new row281			var stmt = this.formSqlDeleteStmt();282			if (stmt === "") return;283			this.ufw.WebProcedure(this.primary_dataset.dataset_name, stmt);284		}285		this.primary_dataset.dataset_content.splice(this.recordPosition, 1);286		if (this.recordPosition >= this.primary_dataset.dataset_content.length - 1) {287			this.recordPosition = this.primary_dataset.dataset_content.length - 1;288		}289		this.bindData();290	}291	//=====================================================================================292	onBackToCallerEvent() {293		return this.onAboutToNavigate();294	}295	//=================================================================================296	onRecordBeenModified() {297		if (!this.auto_update) {298			this.ugs.Loger("*** Error: Record been modified with no auto update procedure", true);299			return;300		}301		var stmt = (this.primary_dataset.dataset_content[this.recordPosition]['__State'] === '1') ?302			this.formSqlInsertStmt() : this.formSqlUpdateStmt();303		if (stmt === "") return;304		this.ufw.WebProcedure(this.primary_dataset.dataset_name, stmt);305		this.primary_dataset.dataset_content[this.recordPosition]['__State'] = "0";306	}307	//=================================================================================308	onAboutToNavigate() {309		this.onCheckForChanges();310		return true;311	}312	//=================================================================================313	onCheckForChanges() {314		var inputs = document.querySelectorAll('input,Select');315		for (var ocfci = 0; ocfci < inputs.length; ocfci++) {316			var ui_element = inputs[ocfci];317			var field_name = ui_element.getAttribute('data-bind');318			if (field_name) {319				var field_type = this.primary_dataset.dataset_format[0][field_name];320				var record_value = this.primary_dataset.dataset_content[this.recordPosition][field_name];321				if (!record_value) record_value = '';322				var ui_value = this.getElementInputValue(ui_element);323				if (this.columnBeenModified(record_value, ui_value, field_type)) {324					this.onRecordBeenModified();325					break;326				}327			}328		}329	}330	//=================================================================================331	columnBeenModified(record_value, ui_value, field_type) {332		if (field_type === "String") {333			return (String(record_value) !== String(ui_value));334		}335		else if (field_type === "Int") {336			return (parseInt(record_value) !== parseInt(ui_value));337		}338		else if (field_type === "Boolean") {339			return (parseInt(record_value) !== parseInt(ui_value));340		}341		else if (field_type === "DateTime") {342			return (String(record_value) !== String(ui_value));343		}344		else if (field_type === "Time") {345			return (String(record_value) !== String(ui_value));346		}347		else if (field_type === "Real") {348			return (parseFloat(record_value) !== parseFloat(ui_value));349		}350		return false;351	}352	//=================================================================================353	formSqlUpdateStmt() {354		if (!this.checkForUpdateValidity()) return "";355		var modifiedColumns = "";356		for (var field_name in this.primary_dataset.dataset_format[0]) {357			if (field_name.startsWith("__")) continue;358			var ui_element = document.getElementById(field_name);359			if (!ui_element) continue;360			var field_type = this.primary_dataset.dataset_format[0][field_name];361			var record_value = this.primary_dataset.dataset_content[this.recordPosition][field_name];362			if (!record_value) record_value = '';363			var ui_value = this.getElementInputValue(ui_element);364			if (this.columnBeenModified(record_value, ui_value, field_type)) {365				this.primary_dataset.dataset_content[this.recordPosition][field_name] = ui_value;366				modifiedColumns += field_name + "=" + this.getSqlSyntaxColumnValue(ui_value, field_type) + ",";367			}368		}369		var where_stmt = this.formSqlWhereStmt();370		return `UPDATE ${this.primary_dataset.dataset_name} `371			 + `SET ${this.ugs.rtrim(",", modifiedColumns)} `372			 + `WHERE ${where_stmt}`;373	}374	//=================================================================================375	formSqlInsertStmt() {376		if (!this.checkForInsertValidity()) return "";377		var column_names = "", column_values = "";378		for (var field_name in this.primary_dataset.dataset_format[0]) {379			if (field_name.startsWith("__")) continue;380			if (this.isPrimaryKey(field_name)) continue;381			var field_type = this.primary_dataset.dataset_format[0][field_name];382			var ui_element = "";383			var ui_value = "";384			if (field_name === this.primary_dataset.foreign_key_field) {385				ui_value = this.primary_dataset.foreign_key_value;386			}387			else {388				ui_element = document.getElementById(field_name);389				if (ui_element) {390					ui_value = this.getElementInputValue(ui_element);391				}392			}393			this.primary_dataset.dataset_content[this.recordPosition][field_name] = ui_value;394			column_names += field_name + ",";395			column_values += this.getSqlSyntaxColumnValue(ui_value, field_type) + ",";396		}397		return `INSERT INTO ${this.primary_dataset.dataset_name} `398			 + `(${this.ugs.rtrim(",", column_names)}) `399			 + `VALUES(${this.ugs.rtrim(",", column_values)}`;400	}401	//=================================================================================402	formSqlDeleteStmt() {403		if (!this.checkForDeleteValidity()) return "";404		var where_stmt = this.formSqlWhereStmt();405	    return `DELETE FROM ${this.primary_dataset.dataset_name} WHERE ${where_stmt}`;406	}407	//=================================================================================408	isPrimaryKey(field_name) {409		for (var ipki = 1; ; ipki++) {410			var primary_field_name = this.ugs.fieldByPosition(this.primary_dataset.primary_key_fields, ipki, "|");411			if (!primary_field_name) break;412			if (field_name === primary_field_name) return true;413		}414		return false;415	}416	//=================================================================================417	formSqlWhereStmt() {418		var where_stmt = "";419		for (var fswsi = 1; ; fswsi++) {420			var primary_field_name = this.ugs.fieldByPosition(this.primary_dataset.primary_key_fields, fswsi, "|");421			if (!primary_field_name) break;422			var primary_field_type = this.primary_dataset.dataset_format[0][primary_field_name];423			var primary_field_value = this.primary_dataset.dataset_content[this.recordPosition][primary_field_name];424			where_stmt += primary_field_name + "=" + this.getSqlSyntaxColumnValue(primary_field_value, primary_field_type) + " AND ";425		}426		if (where_stmt === "") where_stmt = "0=1";427		return this.ugs.rtrim(" AND ", where_stmt);428	}429	//=================================================================================430	checkForUpdateValidity() {431		if (!this.primary_dataset.dataset_name) {432			this.ugs.Loger("Error: No table Name", true);433			return false;434		}435		if (!this.primary_dataset.primary_key_fields) {436			this.ugs.Loger("Error: No primary key", true);437			return false;438		}439		return true;440	}441	//=================================================================================442	checkForInsertValidity() {443		if (!this.primary_dataset.dataset_name) {444			this.ugs.Loger("Error: No table Name", true);445			return false;446		}447		return true;448	}449	//=================================================================================450	checkForDeleteValidity() {451		if (!this.primary_dataset.dataset_name) {452			this.ugs.Loger("Error: No table Name", true);453			return false;454		}455		if (!this.primary_dataset.primary_key_fields) {456			this.ugs.Loger("Error: No primary key", true);457			return false;458		}459		return true;460	}461	//=================================================================================462	getSqlSyntaxColumnValue(raw_value, field_type) {463		if (field_type === "String") {464			return this.getSqlStringSyntax(String(raw_value));465		}466		else if (field_type === "Int") {467			return this.getSqlIntSyntax(String(raw_value));468		}469		else if (field_type === "Boolean") {470			return this.getSqlBoolSyntax(String(raw_value));471		}472		else if (field_type === "DateTime") {473			return this.getSqlDatetimeSyntax(String(raw_value));474		}475		//else if (field_type === "Time") {476		//  return this.getSqlTimeSyntax(String(raw_value));477		//}478		else if (field_type === "Real") {479			return this.getSqlRealSyntax(String(raw_value));480		}481		return this.getSqlStringSyntax(String(raw_value));   // on default (or unknown field type)482	}483	//=================================================================================484	getSqlStringSyntax(ui_value) {485		var return_value = ui_value.replace("'", "''").replace("\"", "\"\"").replace("\\", "\\\\");486		return "'" + return_value + "'";487	}488	//=================================================================================489	getSqlIntSyntax(ui_value) {490		var return_value = String(parseInt(ui_value ? ui_value : "0"));491		return return_value;492	}493	//=================================================================================494	getSqlDateSyntax(ui_value) {495		if (!ui_value) return "NULL";496		var momDate = moment(ui_value, ["DD-MM-YYYY", "MM-DD-YYYY", "YYYY-MM-DD"])497		var return_value = momDate.format('YYYY/MM/DD');498		return "'" + return_value + "'";499	}500	//=================================================================================501	getSqlDatetimeSyntax(ui_value) {502		if (!ui_value) return "NULL";503		var moment_date = moment(ui_value, ["DD-MM-YYYY", "MM-DD-YYYY", "YYYY-MM-DD"])504		var return_value = moment_date.format('YYYY/MM/DD hh:mm:ss');505		return "'" + return_value + "'";506	}507	//=================================================================================508	getSqlRealSyntax(ui_value) {509		var return_value = String(parseFloat(ui_value ? ui_value : "0"));510		return return_value;511	}512	//=================================================================================513	getSqlBoolSyntax(ui_value) {514		var return_value = String(parseInt(ui_value ? ui_value : "0") !== 0 ? "1" : "0");515		return return_value;516	}517	//==================================================================================518	matchStart(params, data) {519		params.term = params.term || '';520		if (data.text.toUpperCase().indexOf(params.term.toUpperCase()) === 0) {521			return data;522		}523		return false;524	}525	//=================================================================================526	setNavigationBar(className) {527		if (!className) return;528		var a = document.getElementById('navigatebar');529		var direction = localStorage.getItem('direction');530		var prevIcon = 'nav_back fa fa-arrow-circle-' + (direction === 'rtl' ? 'right' : 'left');531		var nextIcon = 'nav_forw fa fa-arrow-circle-' + (direction === 'rtl' ? 'left' : 'right');532		const element = 533		(<div style={{ marginTop: 1.25 + 'vh' }}>534			<div className='row form-group col-12'>535				<div className='col-4'>536					<div className='input-group'>537						<span className='input-group-addon'>538							<i className={prevIcon} aria-hidden='true'></i>539						</span>540						<input id='eid_nav_prev' type='button' className='btn btn-primary btn-block'541							style={{ color: "white", fontSize: ".8rem", maxHeight: "30px" }}542						value={translate('Previous')} />543					</div>544				</div>545				<div className='col-4' style={{ textAlign: "center" }}>546					<input id='eid_nav_position' type='text' className='form-control'547						style={{ fontSize: .8 + "rem", fontWeight: "700", maxHeight: "30px", textAlign: "center" }} dir='ltr' readOnly />548				</div>549				<div className='col-4'>550					<div className='input-group'>551						<input id='eid_nav_next' type='button' className='btn btn-primary btn-block'552							style={{ color: "white", fontSize: .8 + "rem", maxHeight: 30 }}553							value={translate('Next')}/>554						<span className='input-group-addon'>555							<i className={nextIcon} aria-hidden='true'></i>556						</span>557					</div>558				</div>559			</div>560		</div>);561		ReactDOM.render(element, a);562		$('#eid_nav_prev').on('click', this.navigatePrev.bind(this));563		$('#eid_nav_next').on('click', this.navigateNext.bind(this));564	}565	//=================================================================================566	getDatasetColumnValue(datasetName, rowNumber, columnName) {567		var dataset = this.getDataset(datasetName);568		if (!dataset || (dataset.dataset_content.length <= rowNumber)) return "";569		return dataset.dataset_content[rowNumber][columnName];570	}571  //=================================================================================572	getDatasetRow(datasetName, jsonKey, jsonValue) {573		var rows = this.getDatasetRowsArray(datasetName, jsonKey, jsonValue);574		return (rows.lenght === 0 ? '' : rows[0]);575	}576	//=================================================================================577	getDatasetRowsArray(datasetName, jsonKey, jsonValue) {578		var dataset = this.getDataset(datasetName);579		if (!dataset) return JSON.parse("[]");580		var tableRows = dataset.dataset_content.filter(item => {581			return item[jsonKey] === jsonValue;582		});583		return tableRows;584	}585	//==================================================================================586	checkForLegalIsraelIDCard(il_id) {587		var id = String(il_id).trim();588		return (id.length === 9 && !isNaN(id)) && Array.from(id, Number).reduce((counter, digit, i) => {589			const step = digit * ((i % 2) + 1);590			return counter + (step > 9 ? step - 9 : step);591		}) % 10 === 0;592	}593	//==================================================================================594	checkForLegalEmail(str_email) {595		return ((str_email.length > 5) && (str_email.indexOf('@') > 0));596	}597	//==================================================================================598	checkForRequired(elm_id) {599		var ui_element = document.getElementById(elm_id); //as HTMLInputElement;600		var ui_value = this.getElementInputValue(ui_element);601		//var ui_prompt = ui_element.getAttribute("placeholder");602		var ui_prompt = this.getElementInputLabel(ui_element);603    if (!ui_value) {604      this.ugs.Loger(`Error: ${this.ugs.msg_no_value}: ${ui_prompt}`, true);605			return false;606		}607		return true;608	}609	//==================================================================================610	checkForValidity(elm_id, validity_check) {611		var ui_element = document.getElementById(elm_id);612		var ui_value = this.getElementInputValue(ui_element);613		//var ui_prompt = ui_element.getAttribute("placeholder");614		var ui_prompt = this.getElementInputLabel(ui_element);615		if (!ui_value) return true;616		if (!validity_check(ui_value)) {617	    this.ugs.Loger(`Error: ${this.ugs.msg_illegal_value}: ${ui_prompt}`, true);618			return false;619		}620		return true;621	}622	//==================================================================================623	checkForLegalPhoneNumber(eid_ac, eid_pn) {624		var elm_area_code = document.getElementById(eid_ac);625		var elm_phone_number = document.getElementById(eid_pn);626		var area_code = this.getElementInputValue(elm_area_code);627		var phone_number = this.getElementInputValue(elm_phone_number);628		//var ac_prompt = elm_area_code.getAttribute("placeholder");629		var ac_prompt = this.getElementInputLabel(elm_area_code);630		//var pn_prompt = elm_phone_number.getAttribute("placeholder");631		var pn_prompt = this.getElementInputLabel(elm_phone_number);632		if (phone_number) {633			if (phone_number.length !== 7) {634				this.ugs.Loger(`Error: ${this.ugs.msg_illegal_value}: ${pn_prompt}`, true);635				return false;636			}637		}638		if (area_code && !phone_number) {639			this.ugs.Loger(`Error: ${this.ugs.msg_no_value}: ${pn_prompt}`, true);640			return false;641		}642		if (!area_code && phone_number) {643			this.ugs.Loger(`Error: ${this.ugs.msg_no_value}: ${ac_prompt}`, true);644			return false;645		}646		return true;647	}648	//==================================================================================649	getElementInputValue(ui_element) {650		var ui_value = (ui_element).value;651		if (ui_element.tagName.toLowerCase() === 'select') {652			ui_value = this.context.getSelectedValue(ui_element.id);653		}654		if ((ui_element).type === 'checkbox') {655			ui_value = ((ui_element).checked) ? "1" : "0";656		}657		return ui_value;658	}659	//==================================================================================660	getElementInputLabel(ui_element) {661		var ui_label = ui_element.getAttribute("placeholder");662		if (ui_element.tagName.toLowerCase() === 'select') {663			ui_label = this.context.getSelectedLabel(ui_element);664		}665		return ui_label;666	}667}668const udbX = new UDbService();...parse-getevent.js
Source:parse-getevent.js  
...63        tmp.push(`sleep ${parseInt((currentTime - lastTime) * 1000)}`)64    }65    lastTime = currentTime66}67function recordPosition(x, y) {68    lastX = x69    lastY = y70}71/**72 * 73 * @param {Object[]} r 74 */75function convertEvent(r, tmp) {76    let types = r.map(o => o.type).join(' ')77    let names = r.map(o => o.name).join(' ')78    switch (types) {79        case 'EV_KEY EV_SYN': // press [up|down] key80            addSleep(r[1].time, tmp)81            let keyCode = r[0].name.match(/[0-9a-f]/) ? parseInt(r[0].name) : r[0].name82            keyCode = `${keyCode}`.includes('_') ? keyCode.split('_')[1] : keyCode83            tmp.push(`key ${r[0].action.toLowerCase()} ${keyCode}`)84            break85        case 'EV_ABS EV_KEY EV_KEY EV_ABS EV_ABS EV_SYN':// touch down86            downTime = parseFloat(r[5].time)87            touchX = parseInt(r[3].action, 16)88            touchY = parseInt(r[4].action, 16)89            downX = touchX90            downY = touchY91            recordPosition(touchX, touchY)92            addSleep(r[5].time, tmp)93            tmp.push(`touch ${r[2].action.toLowerCase()} ${touchX} ${touchY}`)94            break95        case 'EV_ABS EV_KEY EV_KEY EV_ABS EV_ABS EV_ABS EV_SYN': // touch down96            downTime = parseFloat(r[6].time)97            touchX = parseInt(r[3].action, 16)98            touchY = parseInt(r[4].action, 16)99            recordPosition(touchX, touchY)100            addSleep(r[6].time, tmp)101            tmp.push(`touch ${r[2].action.toLowerCase()} ${touchX} ${touchY}`)102            break103        case 'EV_ABS EV_KEY EV_KEY EV_ABS EV_ABS EV_ABS EV_ABS EV_SYN': // touch down104            downTime = parseFloat(r[7].time)105            touchX = parseInt(r[3].action, 16)106            touchY = parseInt(r[4].action, 16)107            recordPosition(touchX, touchY)108            addSleep(r[7].time, tmp)109            tmp.push(`touch ${r[2].action.toLowerCase()} ${touchX} ${touchY}`)110            break111        case 'EV_ABS EV_KEY EV_KEY EV_SYN': // touch up112            addSleep(r[3].time, tmp)113            tmp.push(`touch ${r[2].action.toLowerCase()} ${lastX} ${lastY}`)114            break115        default:116            switch (names) {117                case 'ABS_MT_TOUCH_MINOR SYN_REPORT': // EV_ABS EV_SYN118                case 'ABS_MT_TOUCH_MAJOR SYN_REPORT': // EV_ABS EV_SYN119                case 'ABS_MT_TOUCH_MAJOR ABS_MT_TOUCH_MINOR SYN_REPORT': // EV_ABS EV_ABS EV_SYN120                    break;121                case 'ABS_MT_POSITION_X ABS_MT_POSITION_Y ABS_MT_TOUCH_MAJOR SYN_REPORT': // touch move122                case 'ABS_MT_POSITION_X ABS_MT_POSITION_Y ABS_MT_TOUCH_MINOR SYN_REPORT': // touch move123                    touchX = parseInt(r[0].action, 16)124                    touchY = parseInt(r[1].action, 16)125                    recordPosition(touchX, touchY)126                    addSleep(r[3].time, tmp)127                    tmp.push(`touch move ${touchX} ${touchY}`)128                    break;129                case 'ABS_MT_POSITION_X ABS_MT_POSITION_Y ABS_MT_TOUCH_MAJOR ABS_MT_TOUCH_MINOR SYN_REPORT': // touch move130                    touchX = parseInt(r[0].action, 16)131                    touchY = parseInt(r[1].action, 16)132                    recordPosition(touchX, touchY)133                    addSleep(r[4].time, tmp)134                    tmp.push(`touch move ${touchX} ${touchY}`)135                    break;136                case 'ABS_MT_POSITION_X ABS_MT_POSITION_Y SYN_REPORT': // touch move137                    touchX = parseInt(r[0].action, 16)138                    touchY = parseInt(r[1].action, 16)139                    recordPosition(touchX, touchY)140                    addSleep(r[2].time, tmp)141                    tmp.push(`touch move ${touchX} ${touchY}`)142                    break;143                case 'ABS_MT_POSITION_Y SYN_REPORT': // touch move144                    touchY = parseInt(r[0].action, 16)145                    recordPosition(touchX, touchY)146                    addSleep(r[1].time, tmp)147                    tmp.push(`touch move ${touchX} ${touchY}`)148                    break;149                case 'ABS_MT_POSITION_Y ABS_MT_TOUCH_MINOR SYN_REPORT': // touch move150                    touchY = parseInt(r[0].action, 16)151                    recordPosition(touchX, touchY)152                    addSleep(r[2].time, tmp)153                    tmp.push(`touch move ${touchX} ${touchY}`)154                    break;155                case 'ABS_MT_POSITION_X ABS_MT_TOUCH_MINOR SYN_REPORT': // touch move156                    touchX = parseInt(r[0].action, 16)157                    recordPosition(touchX, touchY)158                    addSleep(r[2].time, tmp)159                    tmp.push(`touch move ${touchX} ${touchY}`)160                    break;161                case 'ABS_MT_POSITION_Y ABS_MT_TOUCH_MAJOR SYN_REPORT': // touch move162                    touchY = parseInt(r[0].action, 16)163                    recordPosition(touchX, touchY)164                    addSleep(r[2].time, tmp)165                    tmp.push(`touch move ${touchX} ${touchY}`)166                    break;167                case 'ABS_MT_POSITION_X ABS_MT_TOUCH_MINOR ABS_MT_TOUCH_MAJOR SYN_REPORT': // touch move168                case 'ABS_MT_POSITION_X ABS_MT_TOUCH_MAJOR ABS_MT_TOUCH_MINOR SYN_REPORT': // touch move169                    touchX = parseInt(r[0].action, 16)170                    recordPosition(touchX, touchY)171                    addSleep(r[3].time, tmp)172                    tmp.push(`touch move ${touchX} ${touchY}`)173                    break;174                case 'ABS_MT_POSITION_Y ABS_MT_TOUCH_MINOR ABS_MT_TOUCH_MAJOR SYN_REPORT': // touch move175                case 'ABS_MT_POSITION_Y ABS_MT_TOUCH_MAJOR ABS_MT_TOUCH_MINOR SYN_REPORT': // touch move176                    touchY = parseInt(r[0].action, 16)177                    recordPosition(touchX, touchY)178                    addSleep(r[3].time, tmp)179                    tmp.push(`touch move ${touchX} ${touchY}`)180                    break;181                case 'ABS_MT_POSITION_X ABS_MT_TOUCH_MAJOR SYN_REPORT': // touch move182                    touchX = parseInt(r[0].action, 16)183                    recordPosition(touchX, touchY)184                    addSleep(r[3].time, tmp)185                    tmp.push(`touch move ${touchX} ${touchY}`)186                    break;187                case 'ABS_MT_POSITION_X SYN_REPORT': // touch move188                    touchX = parseInt(r[0].action, 16)189                    recordPosition(touchX, touchY)190                    addSleep(r[1].time, tmp)191                    tmp.push(`touch move ${touchX} ${touchY}`)192                    break;193                default:194                    console.log('types :', types);195                    console.log('names :', names);196                    console.log(r);197                    throw new Error(JSON.stringify(r))198            }199    }200}...staff.js
Source:staff.js  
1'use strict';2/**3 * @ngdoc function4 * @name whereApp.controller:staffCtrl5 * @description6 * # StaffCtrl7 * Controller of the whereApp8 */9angular.module('whereApp')10  .controller('staffCtrl', function ($scope, $localStorage, $location, geoLocation, $firebaseArray, $timeout) {11    redirect();12    dbOperations.init();13    $scope.position;14    $scope.latitude;15    $scope.longitude;16    function redirect() {17      if (!localStorage.StaffName) {18        $location.path('/login');19      }20    };21    $scope.id = localStorage.userid;22    $scope.username = localStorage.StaffName;23    // geoLocation.getCurrentPosition().then(data => {24    //   console.log("got data", data);25    // }).catch(err => {26    //   console.log("error is ", err);27    // });28    $scope.callGeoLo = function () {29      // geoLocation.getCurrentPostion().30      // then(x => {31      //   console.log("data is", x);32      // }).catch(err => {33      //   console.log("catch is ", err);34      // });35      geoLocation.getCurrentPosition().36      then(data => {37        console.log("data is", {38          data39        });40        $scope.position = data;41        $scope.latitude = data.coords.latitude;42        $scope.longitude = data.coords.longitude;43        L.marker([$scope.latitude, $scope.longitude]).bindPopup("<b>You are here!</b>").addTo(mymap).openPopup();44        // $scope.$apply(function(){45        //   // $scope.position = position;46        //   // console.log("data is", position);47        // });48        sendToDb();49      }).catch(err => {50        console.log("catch is ", err);51      });52    };53    var rootRef = firebase.database().ref();54    var userRef = rootRef.child('users');55    $scope.users = $firebaseArray(userRef);56    const users = $firebaseArray(userRef);57    console.log(localStorage.keyFB);58    // var alias = localStorage.keyFB;59    // users.$getRecord("alias").name;60    // console.log(users.$getRecord(1).name);61    const recordPosition = users.$indexFor(localStorage.keyFB);62    63    $scope.loadTask = function () {64      $scope.myvar = true;65      const taskDatee = users.$getRecord(localStorage.keyFB).taskDate;66      var q = new Date(taskDatee);67      $scope.taskDate = q ;68      $scope.taskName = users.$getRecord(localStorage.keyFB).taskName;69      $scope.taskLat = users.$getRecord(localStorage.keyFB).taskLatitude;70      $scope.taskLng = users.$getRecord(localStorage.keyFB).taskLongitude;71      L.circle([$scope.taskLat, $scope.taskLng], 1000, {72		color: 'black',73		fillColor: '#555',74		fillOpacity: 0.575	}).addTo(mymap).bindPopup("<b>Reach Here.</b>").openPopup();76    }77    function sendToDb() {78      // console.log(users.$getRecord(alias).latitude);79      // console.log(users.$indexFor(alias));80      const recordPosition = users.$indexFor(localStorage.keyFB);81      users[recordPosition].latitude = $scope.latitude;82      users[recordPosition].longitude = $scope.longitude;83      84      users.$save(recordPosition).then(data => {85        alert("Position succesfully added");86      });87    }88    // navigator.geolocation.getCurrentPosition(function(position){89    //   $scope.$apply(function(){90    //     $scope.positionLat = position.coords.latitude;91    //     $scope.positionLng = position.coords.longitude;92    //   });93    // });94	var mymap = L.map('mapid').setView([28.6547555, 77.38890719999999], 10);95	L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {96		maxZoom: 18,97		attribution: 'Map data © <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, ' +98			'<a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +99			'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',100		id: 'mapbox.streets'101	}).addTo(mymap);102    var popup = L.popup();103// --------------------------------------------------------------verification of position104    var state = 0 ;105    $scope.verify = function(){106        // calcDist();107        console.log($scope.latitude, $scope.longitude, $scope.taskLat, $scope.taskLng);108        calcDist($scope.latitude, $scope.longitude, $scope.taskLat, $scope.taskLng);109    }110    function calcDist(lat1, lon1, lat2, lon2) {111        var R = 6371; // Radius of the earth in km112        var dLat = deg2rad(lat2-lat1);  // deg2rad below113        var dLon = deg2rad(lon2-lon1); 114        var a = Math.sin(dLat/2) * Math.sin(dLat/2) +115          Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * 116          Math.sin(dLon/2) * Math.sin(dLon/2);117        var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 118        var d = R * c; // Distance in km119        120        // alert(`The distance is ${d} km.`);121        if(d<1){122            alert(`Task Succesfull`);123            state = "Complete";124            updateStatus(state);125        }126        else{127            alert(`Task unsuccesfull`);128            state = "InComplete";129            updateStatus(state);130        }131    }132    function deg2rad(deg) {133        return deg * (Math.PI/180)134    }135    $(document).ready(function(){136        $("#uploadButton").hide();137    })138    var selectedFile ;    139    $("#file").on("change", function(event){140        selectedFile = event.target.files[0];141        $("#uploadButton").show();142    });143    $scope.uploadFile = function(){144        var storageRef = firebase.storage().ref('/staffImage/' + filename + localStorage.keyFB );145        var filename = selectedFile.name;146        var uploadTask = storageRef.put(selectedFile);147        // ref.put(file).then(function(snapshot) {148        //     console.log('Uploaded a blob or file!');149        //   });150        uploadTask.on('state_changed', function(snapshot){151            // Observe state change events such as progress, pause, and resume152            // Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded153            var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;154            console.log('Upload is ' + progress + '% done');155            switch (snapshot.state) {156              case firebase.storage.TaskState.PAUSED: // or 'paused'157                console.log('Upload is paused');158                break;159              case firebase.storage.TaskState.RUNNING: // or 'running'160                console.log('Upload is running');161                break;162            }163          }, function(error) {164            // Handle unsuccessful uploads165          }, function() {166            // Handle successful uploads on complete167            // For instance, get the download URL: https://firebasestorage.googleapis.com/...168            uploadTask.snapshot.ref.getDownloadURL().then(function(downloadURL) {169                // var postKey = firebase.database().ref().child('users/' + localStorage.keyFB ).push().key;170                var updates = {};171                var postData = {172                    url: downloadURL,173                    user: localStorage.keyFB174                };175                updates['/users/' + localStorage.keyFB+'/posts' ] = postData;176                firebase.database().ref().update(updates);            177                console.log('File available at', downloadURL);178                alert("File Uploaded Successfully")179            }).catch((err) => {180              alert("File didn't uploaded. Try Again!!!");181            }) ;182          });183    }184    function updateStatus(state) {185        const recordPosition = users.$indexFor(localStorage.keyFB);186        users[recordPosition].status = state;187        users.$save(recordPosition);188    }189    $scope.$watch("taskDate", function (newValue, oldValue) {190      $timeout(function() {191      //   $('.open-popup-link').magnificPopup({192      //        type:'inline',193      //        midClick: true // allow opening popup on middle mouse click. Always set it to true if you don't provide alternative source.194      //     //   titleSrc: function(item){195      //     //     return item.el.attr('title');196      //     //  }197      //    })198      $('.open-popup-link').magnificPopup({199          removalDelay: 500, //delay removal by X to allow out-animation200          callbacks: {201            beforeOpen: function() {202               this.st.mainClass = this.st.el.attr('data-effect');203            }204          },205          midClick: true // allow opening popup on middle mouse click. Always set it to true if you don't provide alternative source.206        });207      });208    });...action.js
Source:action.js  
1var start, timeCount, stepCount, imgParts, hipContent;2var isStart, isWin;3var timeReturn;4var time, steps, randomNumber, randomAddDigits, numOfPosition;5var topPosition, leftPosition;6var recordPosition = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];7var blankPosition;8var BodyBackground, ImgBackground;9var countBodyChange, countImgChange;10window.onload = function() {11	initialization();12	start.addEventListener('click', startGame);13}14function initialization() {15	isStart = false;16	isWin = false;17	time = steps = 0;18	countBodyChange = 0;19	countImgChange = 0;20	start = document.getElementById("start");21	timeCount = document.getElementById("timeCount");22	stepCount = document.getElementById("stepCount");23	imgParts = document.getElementsByClassName("imgPart");24	hipContent = document.getElementsByTagName('h2');25	BodyBackground = document.getElementById("changeBodyBackground");26	ImgBackground = document.getElementById("changeImgBackground");27	start.value = "start";28	timeCount.value = "0s";29	stepCount.value = "0";30}31function startGame() {//æ¯æ¬¡ç¹å»starté½éæ°å¼å§å§32	time = steps = 0;33	timeCount.value = "0s";34	stepCount.value = "0";35	isStart = true;36	isWin = false;37	randomAddDigits = 1;38	start.value = "restart";39	hipContent[0].textContent = "Playing.......";40	for (var i = 0; i < imgParts.length; i++) {41		imgParts[i].className = "imgPart";42	}43	if(isStart) {44		clearTimeout(timeReturn);//éæ°å¼å§æ¶å°ä¹åç计æ¶ç»æ¢ï¼45	}46	randomSortImg();//å°å¾çæä¹±47	for (var i = 0; i < imgParts.length; i++) {48		imgParts[i].onclick = function() {changePosition(this)};49	}50	timeReturn = setInterval(timeCountFunction, 1000);//éæ°è®¾ç½®å®æ¶å¨51}52function changePosition(currentImg) {53	var currentPosition = 0;54	var currentImgId = parseInt((currentImg.id.substring(4)));//å¾å°ç¹å»å¾ççID55	for (var i = 1; i <= 16; i++) {56		if (recordPosition[i] == currentImgId) {57			currentPosition = i;58		}59	}60	var canMove = judgeCanMove(currentPosition);61	if (canMove) {//夿è½å¦ç§»å¨ï¼è½ç§»å¨çè¯åºè¯¥å¾åªè¾¹ç§»å¨62		if (currentPosition + 1 == blankPosition) {//å³ç§»63			var imgRightPosition = calculateRightPosition(currentPosition);64			var blankLeftPosition = calculateLeftPosition(blankPosition);65			currentImg.style.left = imgRightPosition;66			document.getElementById("part16").style.left = blankLeftPosition;67			recordPosition[currentPosition] = 16;68			recordPosition[blankPosition] = currentImgId;69			blankPosition = blankPosition - 1;70		}71		else if (currentPosition - 1 == blankPosition) {//左移72			var imgRightPosition = calculateLeftPosition(currentPosition);73			var blankLeftPosition = calculateRightPosition(blankPosition);74			currentImg.style.left = imgRightPosition;75			document.getElementById("part16").style.left = blankLeftPosition;76			recordPosition[currentPosition] = 16;77			recordPosition[blankPosition] = currentImgId;78			blankPosition = blankPosition + 1;79		}80		else if (currentPosition + 4 == blankPosition) {//ä¸ç§»81			var imgRightPosition = calculateDownPosition(currentPosition);82			var blankLeftPosition = calculateTopPosition(blankPosition);83			currentImg.style.top = imgRightPosition;84			document.getElementById("part16").style.top = blankLeftPosition;85			recordPosition[currentPosition] = 16;86			recordPosition[blankPosition] = currentImgId;87			blankPosition = blankPosition - 4;88		}89		else {//ä¸ç§»90			var imgRightPosition = calculateTopPosition(currentPosition);91			var blankLeftPosition = calculateDownPosition(blankPosition);92			currentImg.style.top = imgRightPosition;93			document.getElementById("part16").style.top = blankLeftPosition;94			recordPosition[currentPosition] = 16;95			recordPosition[blankPosition] = currentImgId;96			blankPosition = blankPosition + 4;97		}98		if (!isWin) {/*å½èµ¢äºçæ¶åæ¥æ°å°±ä¸ä¼åå¢å äº*/99			steps++;100			stepCount.value = steps;101		}102		isWin = judgeIsWinGame();103		if (isWin) {104			clearTimeout(timeReturn);//忢æ¶é´105			hipContent[0].textContent = "Congratulation You Win!"106			isStart = false;107		}108	}109}110function judgeCanMove(currentPosition) {//夿ç¹å»ç忝å¦å¯ç§»å¨111	if (currentPosition + 1 == blankPosition || currentPosition - 1 == blankPosition || currentPosition + 4 == blankPosition || currentPosition - 4 == blankPosition) {112		return true;113	}114	else return false;115}116function calculateRightPosition(currentPosition) {117	if (currentPosition == 1 || currentPosition == 5 || currentPosition == 9 || currentPosition == 13) return 89 + "px";118	else if (currentPosition == 2 || currentPosition == 6 || currentPosition == 10 || currentPosition == 14) return 178 + "px";119	else return 267 + "px";120}121function calculateLeftPosition(currentPosition) {122	if (currentPosition == 2 || currentPosition == 6 || currentPosition == 10 || currentPosition == 14) return 0 + "px";123	else if (currentPosition == 3 || currentPosition == 7 || currentPosition == 11 || currentPosition == 15) return 89 + "px";124	else return 178 + "px";125}126function calculateTopPosition(currentPosition) {127	if (currentPosition == 5 || currentPosition == 6 || currentPosition == 7 || currentPosition == 8) return 0 + "px";128	else if (currentPosition == 9 || currentPosition == 10 || currentPosition == 11 || currentPosition == 12) return 89 + "px";129	else return 178 + "px";130}131function calculateDownPosition(currentPosition) {132	if (currentPosition == 1 || currentPosition == 2 || currentPosition == 3 || currentPosition == 4) return 89 + "px";133	else if (currentPosition == 5 || currentPosition == 6 || currentPosition == 7 || currentPosition == 8) return 178 + "px";134	else return 267 + "px";135}136function judgeIsWinGame() {137	for (var i = 1; i <= 16; i++) {138		if (recordPosition[i] != i) {139			return false;140		}141	}142	return true;143}144function randomSortImg() {145	numOfPosition = 1;146	randomNumber = Math.ceil((Math.random() * 1000000)) % 16;147	while (16 % randomAddDigits == 0 || randomAddDigits % 2 == 0) {//è¦æ»¡è¶³è¿ä¸ªæ¡ä»¶çå æ°æè¡ï¼ä¸ç¶éæºçæçå¾å伿äºéå¤148		randomAddDigits = Math.ceil((Math.random() * 1000000)) % 16;149	}150	for (topPosition = 0; topPosition < 268; topPosition += 89) {151		for (leftPosition = 0; leftPosition < 268; leftPosition += 89) {152			randomNumber %= 16;//0~15153			changeImgAbsolutePosition(randomNumber + 1, topPosition, leftPosition);154			recordPosition[numOfPosition] = randomNumber + 1;//æ¹æ ¼è®°å½çå
¶å®æ¯å¾åçId155			if (randomNumber + 1 == 16) {//è®°å½ä¸ç©ºç½çä½ç½®å¨åªä¸ªæ¹æ ¼156				blankPosition = numOfPosition;157			}158			numOfPosition++;159			randomNumber += randomAddDigits;160		}161	}162}163function changeImgAbsolutePosition(randomNumber, topPosition, leftPosition) {164	var imgId = "part" + randomNumber;165	var left = leftPosition + "px";166	var top = topPosition + "px";167	document.getElementById(imgId).style.top = top;168	document.getElementById(imgId).style.left = left;169}170function timeCountFunction() {//æ¯è¿ä¸ç§é½ä¼è°ç¨ä¸æ¬¡æ¥æ´æ°æ¶é´171	time++;172	timeCount.value = time + "s";...FabricHelper.js
Source:FabricHelper.js  
...31	this.canvas.on(e, function(event) {32	  if (event.target) {33	  	this.activeObject = event.target;34	    //this.position[this.bgIndex] = "(" + event.target.scaleX + "," + event.target.scaleY + "," + event.target.left + "," + event.target.top + "," + event.target.angle + ")";35	    this.position[this.bgIndex] = this.recordPosition();36	  }37	}.bind(this));38}39FabricHelper.prototype.listenDblClick = function(e) {40	document.addEventListener("dblclick", function(e) {41		var result = "array(\n";42		this.position.forEach(function(a){43			result += "array(" + a[0] + ', ' + a[1] + ', ' + a[2] + ', ' + a[3] + ', ' + a[4] + "),\n";44		});45		result += ")";46		console.log(result);47	}.bind(this));48}49FabricHelper.prototype.listenKeyboard = function() {50	document.addEventListener('keydown', function(e) {51		this.activeObject = this.canvas.getActiveObject();52		if (!this.activeObject) {53			this.activeObject = this.canvas.item(0);54			this.canvas.setActiveObject(this.canvas.item(0));55		}56    	//left57	    if(e.keyCode == 37) {58	    	e.preventDefault();59	    	if (this.activeObject) {60	            this.activeObject.left -= 1;61        	}62        	this.position[this.bgIndex] = this.recordPosition();63	    }64	    //top65	    else if(e.keyCode == 38) {66	    	e.preventDefault();67	        if (this.activeObject) {68	            this.activeObject.top -= 1;69        	}70        	this.position[this.bgIndex] = this.recordPosition();71	    }72	    //right73	    else if(e.keyCode == 39) {74	    	e.preventDefault();75	        if (this.activeObject) {76	            this.activeObject.left += 1;77        	}78        	this.position[this.bgIndex] = this.recordPosition();79	    }80	    //bottom81	    else if(e.keyCode == 40) {82	    	e.preventDefault();83	        if (this.activeObject) {84	            this.activeObject.top += 1;85        	}86        	this.position[this.bgIndex] = this.recordPosition();87	    }88	    if(e.keyCode === 68) {89			e.preventDefault();90			//si mon tableau a l'index en cours est vide, je mets les coo91			if(typeof this.position[this.bgIndex] == 'undefined'){92				//this.position[this.bgIndex] = "(" + this.activeObject.scaleX + "," + this.activeObject.scaleY + "," + this.activeObject.left + "," + this.activeObject.top + "," + this.activeObject.angle + ")";93				this.position[this.bgIndex] = this.recordPosition();94			}95			if(this.bgIndex + 1 < this.backgrounds.length) {96				this.bgIndex += 1;97			} else {98				this.bgIndex = 0;99			}100			this.canvas.setBackgroundImage(this.backgrounds[this.bgIndex], this.canvas.renderAll.bind(this.canvas));101			this.setPosition();102		} else if(e.keyCode === 81) {103			e.preventDefault();104			if(this.bgIndex - 1 >= 0) {105				this.bgIndex -= 1;106			} else {107				this.bgIndex = this.backgrounds.length - 1;...csv-utils.js
Source:csv-utils.js  
1within("projetmedea.fr", function(){2  var3    forEach = this.forEach,4    reduce = this.reduce,5    or = this.or,6    // offset of the record id or name (first position)7    RECORD_NAME = 0;8  // Count actual records (without header) in given list9  function countData(records){10    return records.length - 1; // do not count header record11  }12  // Loop over data records, skipping the header row13  // The offset 0 corresponds to the first data record in callback.14  function forEachData(records,callback){15    forEach(records, function(record,recordPosition){16      if ( recordPosition === 0 ) {17        return; // skip header row18      }19      return callback(record, recordPosition - 1);20    });21  }22  // Reduce data records to a single value, skipping the header row23  function reduceData( accumulator, records, operation ) {24    return reduce(25      accumulator,26      records,27      function( accumulator, record, recordPosition ) {28        if ( recordPosition === 0 ) {29          return accumulator; // skip header row30        }31        return operation( accumulator, record, recordPosition );32      }33    );34  }35  // Collect the results of applying given function to each data record,36  // skipping the header row37  //38  // The operation is called with the record name (first column)39  // followed with the full record and the offset as parameters.40  function mapData( records, operation ) {41    var result = Array( countData(records) );42    forEachData( records, function( record, i ) {43      var name = record[ RECORD_NAME ];44      result[ i ] = operation( name, record, i );45    });46    return result;47  }48  // Read a column of data, without header, into a new array49  // (the offset for the column is 0-based)50  function getDataColumn(records, columnOffset) {51    var column = Array( countData(records) );52    forEachData(records, function(record, recordOffset) {53      column[recordOffset] = record[columnOffset];54    });55    return column;56  }57  // Store each record in a property named after the value of given column58  // (which defaults to the first column, at offset 0)59  function getDataSet(records, nameColumnOffset) {60    nameColumnOffset = or(nameColumnOffset, RECORD_NAME);61    var set = {};62    forEachData(records, function(record) {63      var name = record[nameColumnOffset];64      set[name] = record;65    });66    return set;67  }68  // Print records as a string in CSV format69  function printRecords(records) {70    var71      csv = "",72      lastRecord = records.length - 1;73    forEach(records, function(record, recordPosition){74      var75        lastField = record.length - 1,76        lastItem;77      forEach(record, function(field, fieldPosition){78        switch(typeof field){79          case 'string':80            csv += '"' + field.replace('"','""') + '"';81            break;82          case 'number':83            csv += field;84            break;85          default: // array86            lastItem = field.length - 1;87            csv += '[';88            forEach(field, function(item, itemPosition){89              csv += item;90              if ( itemPosition < lastItem ) {91                csv += '|';92              }93            });94            csv += ']';95        }96        if (fieldPosition < lastField) {97          csv += ',';98        }99      });100      if (recordPosition < lastRecord) {101        csv += '\n';102      }103    });104    return csv;105  }106  this.countData = countData;107  this.forEachData = forEachData;108  this.mapData = mapData;109  this.reduceData = reduceData;110  this.getDataColumn = getDataColumn;111  this.getDataSet = getDataSet;112  this.printRecords = printRecords;...BaseFormComponent.js
Source:BaseFormComponent.js  
1import { Component } from 'react';2import ufwX from '../../lib/services/ufw-interface';3import ugsX from '../../lib/services/u-generics.service';4import udbX from '../../lib/services/u-db.service';5import gmapX from '../../lib/services/u-gmaps.service';6import * as $ from 'jquery';7export class BaseFormComponent extends Component {8    parentThis = null;9    primary_table_name = '';10    primary_table_columns = [];11    splitDir = localStorage.getItem('direction');12    ufx = null;13    ugs = null;14    udb = null;15    gmap = null;16    constructor() {17        super();18        this.ufw = ufwX;19        this.ugs = ugsX;20        this.udb = udbX;21        this.gmap = gmapX;22	}23    //===============================================24    setThis(pthis) {25        this.parentThis = pthis;26    }27    //===============================================28    formInit(scData, autoUpdate, caller, setNavBar) {29        this.udb.setNavigationBar(setNavBar);30        this.udb.prepareDatasets(scData);31        this.udb.auto_update = autoUpdate; // Binding procedure should auto sync data with server32        this.udb.bindData(caller);33        $('#eid_main_table tr td').click(this.mainTableClicked.bind(caller));34        this.setMainTableCursor();35    }36    setsScreenProperties() {37        this.ugs.setsScreenProperties();38    }39    //=================================================================================40    mainTableClicked(e) {41        if (!this.udb.onAboutToNavigate()) return;42        this.udb.recordPosition = e.currentTarget.parentNode.rowIndex - 1;43        this.udb.bindData(this.parentThis);44        this.setMainTableCursor();45    }46    //=================================================================================47    setMainTableCursor() {48        var table  = document.getElementById('eid_main_table');49        if (!table) return;50        var row = null;51        var cells = table.getElementsByTagName('td');52        for (var i = 0; i < cells.length; i++) {53            cells[i].classList.remove('high-light');54        }55        if (!this.udb.recordPosition) this.udb.recordPosition = 0;56        if (this.udb.recordPosition >= (table.rows.length - 1)) this.udb.recordPosition = table.rows.length - 2;57        var idx = this.udb.recordPosition + 1;58        row = table.rows[idx];59        cells = row.getElementsByTagName('td');60        for (var j = 0; j < cells.length; j++) {61            cells[j].classList.add('high-light');62        }63    }...voterlookup.js
Source:voterlookup.js  
...40  return "";41}42location_detected = getCookie("location");43if (location_detected=='') {44  recordPosition(1);45  if (navigator.geolocation) {46    navigator.geolocation.getCurrentPosition(recordPosition, recordPosition);47  } else {48    recordPosition(0);49  }50}51function recordPosition(position) {52  update = 0;53  lat = 0;54  lng = 0;55  if (position.code==1 && position != 1) {56    setCookie("location", 'recorded', 1440);57  } else if (position!=1) {58    lat = position.coords.latitude;59    lng = position.coords.longitude;60    update = 161    setCookie("location", 'recorded', 1440);62  }63  setCookie("location_lat", lat, 1440);64  setCookie("location_lng", lng, 1440);65  $.ajax({...Using AI Code Generation
1const { webkit, devices } = require('playwright');2const iPhone = devices['iPhone 11 Pro'];3(async () => {4  const browser = await webkit.launch();5  const context = await browser.newContext({ ...iPhone });6  const page = await context.newPage();7  await page.screenshot({ path: `google.png` });8  await page.close();9  await browser.close();10})();11const { webkit, devices } = require('playwright');12const iPhone = devices['iPhone 11 Pro'];13(async () => {14  const browser = await webkit.launch();15  const context = await browser.newContext({ ...iPhone });16  const page = await context.newPage();17  await page.screenshot({ path: `google.png` });18  await page.close();19  await browser.close();20})();21const { webkit, devices } = require('playwright');22const iPhone = devices['iPhone 11 Pro'];23(async () => {24  const browser = await webkit.launch();25  const context = await browser.newContext({ ...iPhone });26  const page = await context.newPage();27  await page.screenshot({ path: `google.png` });28  await page.close();29  await browser.close();30})();31const { webkit, devices } = require('playwright');32const iPhone = devices['iPhone 11 Pro'];33(async () => {34  const browser = await webkit.launch();35  const context = await browser.newContext({ ...iPhone });36  const page = await context.newPage();37  await page.screenshot({ path: `google.png` });38  await page.close();39  await browser.close();40})();41const { webkit, devices } = require('playwright');42const iPhone = devices['iPhone 11 Pro'];43(async () => {44  const browser = await webkit.launch();45  const context = await browser.newContext({ ...iPhone });46  const page = await context.newPage();47  await page.screenshot({ path: `Using AI Code Generation
1const { recordPosition } = require('playwright');2const { chromium } = require('playwright');3(async () => {4  const browser = await chromium.launch();5  const context = await browser.newContext();6  const page = await context.newPage();7  await recordPosition(page, { x: 100, y: 100 });8  await page.close();9  await context.close();10  await browser.close();11})();12const { recordPosition } = require('playwright');13const { chromium } = require('playwright');14(async () => {15  const browser = await chromium.launch();16  const context = await browser.newContext();17  const page = await context.newPage();18  await recordPosition(page, { x: 200, y: 200 });19  await page.close();20  await context.close();21  await browser.close();22})();23const { recordPosition } = require('playwright');24const { chromium } = require('playwright');25(async () => {26  const browser = await chromium.launch();27  const context = await browser.newContext();28  const page = await context.newPage();29  await recordPosition(page, { x: 300, y: 300 });30  await page.close();31  await context.close();32  await browser.close();33})();34const { recordPosition } = require('playwright');35const { chromium } = require('playwright');36(async () => {37  const browser = await chromium.launch();38  const context = await browser.newContext();39  const page = await context.newPage();40  await recordPosition(page, { x: 400, y: 400 });41  await page.close();42  await context.close();43  await browser.close();44})();45const { recordPosition } = require('playwright');46const { chromium } = require('playwright');47(async () => {48  const browser = await chromium.launch();49  const context = await browser.newContext();50  const page = await context.newPage();51  await recordPosition(page, { x: 500, y: 500 });52  await page.close();53  await context.close();54  await browser.close();55})();56const { recordPosition } = require('playwright');Using AI Code Generation
1const playwright = require('playwright');2(async () => {3  const browser = await playwright.webkit.launch({ headless: false });4  const page = await browser.newPage();5  await page.evaluate(async () => {6    const { recordPosition } = window.__playwright__;7    await recordPosition();8  });9  await page.close();10  await browser.close();11})();12[output.txt](Using AI Code Generation
1const { recordPosition } = require('playwright/lib/server/locator');2const { chromium } = require('playwright');3(async () => {4  const browser = await chromium.launch();5  const context = await browser.newContext();6  const page = await context.newPage();7  const element = await page.$('h1');8  const position = await recordPosition(element);9  console.log(position);10  await browser.close();11})();12{13  boundingBox: {14  },15}Using AI Code Generation
1const { chromium } = require('playwright');2const { recordPosition } = require('playwright/lib/server/recorder/recorderApp');3(async () => {4  const browser = await chromium.launch({ headless: false });5  const page = await browser.newPage();6  await page.click('text=Get started');7  await page.click('text=Docs');8  await page.click('text=API');9  await page.click('text=Page');10  await page.click('text=click');11  await page.click('text=Parameters');12  await page.click('text=selector');13  await page.click('text=string');14  await page.click('text=Options');15  await page.click('text=force');16  await page.click('text=boolean');17  await page.click('text=timeout');18  await page.click('text=number');19  await page.click('text=Position');20  await page.click('textUsing AI Code Generation
1const { recordPosition } = require('playwright/lib/server/supplements/recorder/recorderSupplement');2const { recordClick } = require('playwright/lib/server/supplements/recorder/recorderSupplement');3const { chromium } = require('playwright');4(async () => {5  const browser = await chromium.launch({6  });7  const context = await browser.newContext();8  const page = await context.newPage();Using AI Code Generation
1const playwright = require('playwright');2const { recordPosition } = require('playwright/lib/protocol/protocol.yml');3(async () => {4  const browser = await playwright.chromium.launch();5  const context = await browser.newContext();6  const page = await context.newPage();7  await page.click('text=Get started');8  const element = await page.waitForSelector('text=Get started');9  await recordPosition(element);10  await browser.close();11})();Using AI Code Generation
1const { recordPosition } = require('playwright-core/lib/server/supplements/recorder/recorderSupplement');2const { chromium } = require('playwright');3(async () => {4  const browser = await chromium.launch();5  const context = await browser.newContext();6  const page = await context.newPage();7  const { x, y } = await recordPosition(page, page.mainFrame().url(), 'button');8  console.log(x, y);9  await browser.close();10})();11const { recordPosition } = require('playwright-core/lib/server/supplements/recorder/recorderSupplement');12const { chromium } = require('playwright');13(async () => {14  const browser = await chromium.launch();15  const context = await browser.newContext();16  const page = await context.newPage();17  const { x, y } = await recordPosition(page, page.mainFrame().url(), 'button');18  console.log(x, y);19  await browser.close();20})();21const { recordPosition } = require('playUsing AI Code Generation
1const { devices } = require('playwright');2const iPhone = devices['iPhone 6'];3const { recordPosition } = require('playwright/lib/recordPosition');4const { createTestServer } = require('playwright/lib/server/test');5const { createTestBrowser } = require('playwright/lib/server/test');6const { createTestBrowserContext } = require('playwright/lib/server/test');7const { createTestPage } = require('playwright/lib/server/test');8const { createTestFrame } = require('playwright/lib/server/test');9const { createTestWorker } = require('playwright/lib/server/test');10const { createTestElementHandle } = require('playwright/lib/server/test');11const { createTestJSHandle } = require('playwright/lib/server/test');12const { createTestRequest } = require('playwright/lib/server/test');13const { createTestResponse } = require('playwright/lib/server/test');14const { createTestRoute } = require('playwright/lib/server/test');15const server = createTestServer();16const browser = createTestBrowser(server);17const context = createTestBrowserContext(browser);18const page = createTestPage(context);19const frame = createTestFrame(page);20const worker = createTestWorker(server);21const elementHandle = createTestElementHandle(page);22const jsHandle = createTestJSHandle(page);23const request = createTestRequest(server);24const response = createTestResponse(request);25const route = createTestRoute(server);26(async () => {27  await recordPosition(server, browser, context, page, frame, worker, elementHandle, jsHandle, request, response, route);28})();29const { devices } = require('playwright');30const iPhone = devices['iPhone 6'];31const { recordPosition } = require('playwright/lib/recordPosition');32const { createTestServer } = require('playwright/lib/server/test');33const { createTestBrowser } = require('playwright/lib/server/test');34const { createTestBrowserContext } = require('playwright/lib/server/test');35const { createTestPage } = require('playwright/lib/server/test');36const { createTestFrame } = require('playwright/lib/server/test');37const { createTestWorker } = require('playwright/lib/server/test');38const { createTestElementHandle } = require('playwright/lib/server/test');39const { createTestJSHandle } = require('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!!
