Best JavaScript code snippet using appium
borrowNone.events.js
Source:borrowNone.events.js  
1Osp.Core.Mixin.define("borrowNone.Events",2{3	members:4	{5		PAGE:6		{7			PREVIOUS: null,8			CURRENT: null9		},10		CURRENT:11		{12			ITEM: null,13			ID: null14		},15		CHECKBUTTON:16		{17			STATE: null18		},19		BOX:20		{21			STATE: null22		},23		ID:24		{25			DATE: null,26			ENDDATE: null,27			BORROWTYPE:28			{29				FROM: null,30				TO: null31			},32			EXPORTMODE_1: null,33			EXPORTMODE_2: null,34			EXPORTMODE_3: null35		},36		LISTENER:37		{38			HEADER: null,39			FOOOTER: null,40			LIST:41			{42				BORROW: null,43				LOAN: null,44				CONTACT: null45			},46			CHECKBUTTON:47			{48				BORROW: null,49				LOAN: null50			}51		},52		onCheckButtonAction: function(e)53		{54			var actionId = e.getData().actionId;55			switch(actionId)56			{57				// TYPE58				case 1:59					this.CHECKBUTTON.STATE = 'borrow';60					break;61				case 2:62					this.CHECKBUTTON.STATE = 'loan';63					break;64				// ALLOW ALWAYS EXPORT65				case 3: // on66					localStorage.setItem("allowExport", "yes");67					break;68				case 4: // off69					localStorage.removeItem("allowExport");70					break;71				72				// ENABLE SUCCESS NOTIFY73				case 5: // on74					localStorage.setItem("enableNotify", "on");75					break;76				case 6: // off77					localStorage.removeItem("enableNotify");78					break;79				// EXPORT MENU80				case 10:81					this.showExportMenu(this.PAGE.CURRENT, true);82					break;83				case 11:84					this.showExportMenu(this.PAGE.CURRENT, false);85					break;86			}87		},88		onFooterAction: function(e)89		{90			var actionId = e.getData().actionId,91				self = this;92			switch(actionId)93			{94				// ADDPAGE95				case 1:96					var allowExport = localStorage.getItem("allowExport");97					this.headerObj.removeAllItems();98					this.headerObj.removeAllButtons();99					this.headerObj.setHeaderStyle('title');100					this.headerObj.setTitleText(this.getMessage('IDS_TITLE_NEW_ITEM'));101					this.SaveCancelButtons(3);102					if(this.PAGE.CURRENT === "borrowList")103					{104						this.radioGroupObj.setSelectedItem(this.borrowCheckbutton);105						this.PAGE.PREVIOUS = this.PAGE.CURRENT;106					}107					if(this.PAGE.CURRENT === "loanList")108					{109						this.radioGroupObj.setSelectedItem(this.loanCheckbutton);110						this.PAGE.PREVIOUS = this.PAGE.CURRENT;111					}112					this.ID.DATE  = this.startDateField;113					this.ID.ENDDATE  = this.endDateField;114					this.ID.BORROWTYPE.FROM = this.borrowCheckbutton;115					this.ID.BORROWTYPE.TO = this.loanCheckbutton;116					this.ID.EXPORTMODE_0 = this.typeMode1CheckButton;117					this.ID.EXPORTMODE_1 = this.typeMode2CheckButton;118					this.ID.EXPORTMODE_2 = this.typeMode3CheckButton;119					if(allowExport)120					{121						this.exportToggle.setSelected(true);122						this.timeValueField.setVisible(true);123						this.typeMode1CheckButton.setVisible(true);124						this.typeMode2CheckButton.setVisible(true);125						this.typeMode3CheckButton.setVisible(true);126					}127					this.PAGE.CURRENT = "addPage";128					this.footerObj.setItemEnabled(0, false);129					this.hideAllPages();130					this.showPage(this.addPanel);131					break;132				// DELETELIST133				case 2:134					// borrowPanel135					if(this.borrowList.isVisible() && this.borrowList.getItemCount() > 0)136					{137						this.hideAllPages();138						this.borrowList.removeListenerById(this.LISTENER.LIST.BORROW);139						this.updateList(this.borrowList, 'mark');140						this.DeleteCancelButtons();141						this.showPage(this.borrowList);142					}143					// loanPanel144					if(this.loanList.isVisible() && this.loanList.getItemCount() > 0)145					{146						this.hideAllPages();147						this.loanList.removeListenerById(this.LISTENER.LIST.LOAN);148						this.updateList(this.loanList, 'mark');149						this.DeleteCancelButtons();150						this.showPage(this.loanList);151					}152					break;153				// SAVE154				case 3:155					this.setLoading(true);156					var titleField = this.titleField,157						personField = this.personField,158						typeField = this.radioGroupObj,159						startDateField = this.startDateField,160						endDateField = this.endDateField,161						noteArea = this.noteArea,162						picURLField = this.picURL,163						timeValueField = this.timeValueField,164						modusField = this.alarmTypeGroupObj,165						requiredFields = [titleField, personField, startDateField],166						exportToggle = this.exportToggle;167					if(this.CheckFields(requiredFields, startDateField, startDateField))168					{169						// vars170						var title = titleField.getText(),171							person = personField.getText(),172							type = typeField.getSelectedItem() == this.ID.BORROWTYPE.FROM ? 1 : 2,173							start = Date.parse(startDateField.getText()).getTime(),174							end = endDateField.getText() ? Date.parse(endDateField.getText()).getTime() : -1,175							note = noteArea.getText(),176							pic = picURLField.getText(),177							time = 0,178							modus = 1,179							bufferItem = {180								"title": title,181								"type": type,182								"person": person,183								"date": start,184								"endDate": end,185								"pic": pic,186								"note": note,187								"eventId": -1188							};189						if(exportToggle.isSelected())190						{191							time = parseInt(timeValueField.getText(), 10);192							if(modusField.getSelectedItem() == this.ID.EXPORTMODE_0) // if no alarm193							{194								modus = 0;195							}196							if(modusField.getSelectedItem() == this.ID.EXPORTMODE_1) // if alarm + display197							{198								modus = 1;199							}200							if(modusField.getSelectedItem() == this.ID.EXPORTMODE_2) // if alarm + display201							{202								modus = 2;203							}204							if(time && modus)205							{206								bufferItem.exportData = {207									"time": time,208									"modus": modus209								};210							}211							this.export2Calendar(bufferItem);212						}213						else // without calendar export214						{215							this.saveEntry(bufferItem);216						}217					}218					this.setLoading(false);219					break;220					// CANCEL221				case 4:222					if(this.PAGE.CURRENT === 'editPage')223					{224						this.hideAllPages();225						this.showPage(this.detailPanel);226						var index = this.detailIdLabelValue.getText(),227							db = localStorage.getItem("db"),228							data = JSON.parse(db).results,229							itemData = data[index];230						// MODIFY HEADER231						this.BackButtonHeader();232						this.headerObj.setTitleText(itemData.title);233						// MODIFY FOOTER234						this.EditDeleteButtons();235						this.clearForm();236					}237					else if(this.PAGE.CURRENT === 'addPage')238					{239						// MODIFY HEADER240						this.DefaultHeader();241						// MODIFY FOOTER242						this.AddDeleteButtons();243						this.hideAllPages();244						if(this.PAGE.PREVIOUS === 'borrowList' || this.PAGE.PREVIOUS == null)245						{246							this.showPage(this.borrowList);247						}248						if(this.PAGE.PREVIOUS === 'loanList')249						{250							this.showPage(this.loanList);251						}252						this.clearForm();253					}254					else255					{256						var itemsCount = 0,257							item = null,258							self = this;259						if(this.borrowList.isVisible())260						{261							this.updateList(this.borrowList, 'normal');262							this.AddDeleteButtons();263							this.LISTENER.LIST.BORROW = this.borrowList.addListener('listItemStateChange', this.onListAction, this);264						}265						if(this.loanList.isVisible())266						{267							this.updateList(this.loanList, 'mark');268							this.AddDeleteButtons();269							this.LISTENER.LIST.LOAN = this.loanList.addListener('listItemStateChange', this.onListAction, this);270						}271					}272					break;273				// DELETE FROM LIST274				case 5:275					var saveItem = {}; // open buffer object276						itemsCount = 0,277						item = null,278						idx = 0,279						dbResults = JSON.parse(localStorage.getItem('db')).results;280					if(this.borrowList.isVisible())281					{282						dbResults = this.removeFromList(this.borrowList, dbResults);283						saveItem.results = dbResults; // add changed dbResults to buffer object284						localStorage.setItem('db', JSON.stringify(saveItem)); // save buffer object to db285						if(this.isDBEmpty())286						{287							localStorage.removeItem('db');288						}289						this.AddDeleteButtons();290						this.LISTENER.LIST.BORROW = this.borrowList.addListener('listItemStateChange', this.onListAction, this);291						this.updateList(this.borrowList, 'normal');292					}293					if(this.loanList.isVisible())294					{295						dbResults = this.removeFromList(this.loanList, dbResults);296						saveItem.results = dbResults; // add changed dbResults to buffer object297						localStorage.setItem('db', JSON.stringify(saveItem)); // save buffer object to db298						if(this.isDBEmpty())299						{300							localStorage.removeItem('db');301						}302						this.AddDeleteButtons();303						this.LISTENER.LIST.LOAN = this.loanList.addListener('listItemStateChange', this.onListAction, this);304						this.updateList(this.loanList, 'normal');305					}306					break;307				// EDIT308				case 6:309					var allowExport = localStorage.getItem('allowExport'),310						item = this.CURRENT.ITEM,311						id = this.CURRENT.ID;312					// change PAGE.CURRENT to 'editPage'313					this.PAGE.CURRENT = 'editPage';314					// MODIFY HEADER315					this.EditItemHeader();316					// MODIFY FOOTER317					this.SaveCancelButtons(8);318					var title = item.title,319						person = item.person,320						date = item.date,321						endDate = item.endDate,322						type = isNaN(item.type) ? item.type : parseInt(item.type, 10),323						note = item.note,324						pic = item.pic,325						alarmTime = "",326						alarmMode = null,327						box = (type === 'loan' || type ===  2) ? this.editLoanCheckbutton : this.editBorrowCheckbutton;328					if(Osp.Core.Check.isPositiveNumber(date))329					{330						date = new Date(date).toLocaleDateString();331					}332					else333					{334						date = new Date(Date.parse(date)).toLocaleDateString();335					}336					if(endDate)337					{338						if(Osp.Core.Check.isPositiveNumber(endDate))339						{340							endDate = new Date(endDate).toLocaleDateString();341						}342						else343						{344							endDate = new Date(Date.parse(endDate)).toLocaleDateString();345						}346					}347					// fill edit fields348					this.editRadioGroupObj.setSelectedItem(box);349					this.editTitleField.setText(title);350					this.editPersonField.setText(person);351					this.editStartDateField.setText(date);352					this.editEndDateField.setText(endDate);353					this.editNoteArea.setText(note);354					if(item.exportData)355					{356						this.editTimeValueField.setText(item.exportData.time+'');357						if(item.exportData.modus === 0)358						{359							this.typeMode1CheckButton.setSelected(true);360						}361						if(item.exportData.modus === 1)362						{363							this.typeMode2CheckButton.setSelected(true);364						}365						if(item.exportData.modus === 3)366						{367							this.typeMode3CheckButton.setSelected(true);368						}369					}370					this.ID.DATE  = this.editStartDateField;371					this.ID.ENDDATE  = this.editEndDateField;372					this.ID.BORROWTYPE.FROM = this.editBorrowCheckbutton;373					this.ID.BORROWTYPE.TO = this.editLoanCheckbutton;374					this.ID.EXPORTMODE_0 = this.editTypeMode1CheckButton;375					this.ID.EXPORTMODE_1 = this.editTypeMode2CheckButton;376					this.ID.EXPORTMODE_2 = this.editTypeMode3CheckButton;377					if(allowExport)378					{379						this.showExportMenu(this.PAGE.CURRENT, true);380					}381					// hide all pages except editPage382					this.hideAllPages();383					this.showPage(this.editPanel);384					break;385				// DELETE ITEM FROM DETAILPAGE386				case 7:387					var index = this.detailIdLabelValue.getText(), // read index388						db = localStorage.getItem('db'), // open DB389						dbResults = JSON.parse(db).results; // query results390					dbResults.splice(index, 1); // remove item from dbResults391					var saveItem = {}; // create new object392					saveItem.results = dbResults; // fill results key with changed dbResults;393					localStorage.setItem('db', JSON.stringify(saveItem)); // save it on DB394					if(this.isDBEmpty())395					{396						localStorage.removeItem('db');397					}398					this.loadDB(); // reload db399					// modify header400					this.headerObj.setHeaderStyle(Osp.Ui.Controls.HeaderStyle.SEGMENTED);401					this.headerObj.addItem({actionId : 1, text : 'From'});402					this.headerObj.addItem({actionId : 2, text : 'To'});403					// modify footer404					this.AddDeleteButtons();405					this.hideAllPages();406					if(this.PAGE.PREVIOUS === 'borrowList')407					{408						this.showPage(this.borrowList);409					}410					if(this.PAGE.PREVIOUS === 'loanList')411					{412						this.showPage(this.loanList);413						this.headerObj.setItemSelected(1);414					}415					break;416				// SAVE EDIT417				case 8:418					this.setLoading(true);419					this.footerObj.setItemEnabled(0, false);420					var self = this,421						title = this.editTitleField,422						person = this.editPersonField,423						startDate = this.editStartDateField,424						endDate = this.editEndDateField,425						required = [title, person, startDate],426						index = this.detailIdLabelValue.getText();427					if(this.CheckFields(required, startDate, endDate))428					{429						var title = this.editTitleField.getText(),430							person = this.editPersonField.getText(),431							type = this.editRadioGroupObj.getSelectedItem() == this.ID.BORROWTYPE.FROM ? 1 : 2,432							start = Date.parse(this.editStartDateField.getText()).getTime(),433							end = this.editEndDateField.getText() ? Date.parse(this.editStartDateField.getText()).getTime() : -1,434							note = this.editNoteArea.getText(),435							pic = this.editPicURL.getText(),436							time = parseInt(this.editTimeValueField.getText(), 10),437							modus = null,438							eventId = this.detailEventIdLabelValue.getText() ? parseInt(this.detailEventIdLabelValue.getText(), 10) : -1,439							bufferItem = {440								"title": title,441								"type": type,442								"person": person,443								"date": start,444								"endDate": end,445								"pic": pic,446								"note": note,447								"eventId": eventId448							};449						if(exportToggle.isSelected())450						{451							time = parseInt(timeValueField.getText(), 10);452							if(modusField.getSelectedItem() == this.ID.EXPORTMODE_0) // if no alarm453							{454								modus = 0;455							}456							if(modusField.getSelectedItem() == this.ID.EXPORTMODE_1) // display only457							{458								modus = 1;459							}460							if(modusField.getSelectedItem() == this.ID.EXPORTMODE_2) // if alarm + display461							{462								modus = 2;463							}464							bufferItem.exportData = {465								"time": time,466								"modus": modus467							};468							if(!eventId || eventId === -1)469							{470								this.export2Calendar(bufferItem, index);471							}472							else473							{474								this.updateEvent(bufferItem, index);475							}476						}477						else // without calendar export478						{479							this.saveEntry(bufferItem, index);480						}481					}482					break;483			}484		},485		onHeaderAction: function(e)486		{487			var actionId = e.getData().actionId;488			switch(actionId)489			{490				// BORROW491				case 1:492					this.hideAllPages();493					if(!this.borrowList.isVisible())494					{495						this.showPage(this.borrowList);496					}497					this.PAGE.CURRENT = 'borrowList';498					break;499				// LOAN500				case 2:501					this.hideAllPages();502					if(!this.loanList.isVisible())503					{504						this.showPage(this.loanList);505					}506					this.PAGE.CURRENT = 'loanList';507					break;508				// EXIT509				case 3:510					var userConfirm = confirm('Application will close now. Continue?');511					if(userConfirm)512					{513						Osp.App.Application.terminate();514					}515					break;516				// BACK517				case 4:518					if(this.contactList.isVisible())519					{520						this.showFooter(true);521						this.headerObj.removeAllItems(); // clean header522						this.headerObj.removeAllButtons(); // clean header523						this.headerObj.setHeaderStyle('title'); // set header style to "title"524						this.contactList.removeAllItems(); // clean contactList525						this.hideAllPages();526						if(this.PAGE.CURRENT === 'addPage')527						{528							this.headerObj.setTitleText(this.getMessage('IDS_TITLE_NEW_ITEM')); // update header text529							this.SaveCancelButtons(3); // add save (id:3) and cancel button.530							this.showPage(this.addPanel);531						}532						else533						{534							this.headerObj.setTitleText(this.getMessage('IDS_TITLE_EDIT_ITEM')); // update header text535							this.SaveCancelButtons(8); // add save (id:3) and cancel button.536							this.showPage(this.editPanel);537						}538					}539					else540					{541						this.showFooter(true);542						// MODIFY HEADER543						this.DefaultHeader();544						// MODIFY FOOTER545						this.AddDeleteButtons();546						this.hideAllPages();547						if(this.PAGE.PREVIOUS === 'borrowList')548						{549							this.showPage(this.borrowList);550							if(this.borrowList.getItemCount() === 0)551							{552								this.borrowList.removeAllItems();553							}554							this.borrowList.updateList();555						}556						if(this.PAGE.PREVIOUS === 'loanList')557						{558							this.showPage(this.loanList);559							this.headerObj.setItemSelected(1);560							if(this.loanList.getItemCount() == 0)561							{562								this.loanList.removeAllItems();563							}564							this.loanList.updateList();565						}566					}567					break;568				// SETTINGS569				case 5:570					var allowExport = localStorage.getItem("allowExport"),571						enableNotify = localStorage.getItem("enableNotify"),572						db = localStorage.getItem('db'),573						file = 'export.db',574						location = 'documents/borrowNone/data',575						fileSystemAPI = deviceapis.filesystem,576						importButton = this.importButton;577					function onSuccess(dir)578					{579						importButton.setEnabled(true);580					}581					function resolveCB(dir)582					{583						dir.listFiles(onSuccess, onError, {name: file});584					}585					function onError(e)586					{587						console.log("e.message := "+e.message);588						importButton.setEnabled(false);589					}590					fileSystemAPI.resolve(resolveCB, onError, location, 'r');591					if(this.borrowList.isVisible())592					{593						this.PAGE.PREVIOUS = 'borrowList';594					}595					if(this.loanList.isVisible())596					{597						this.PAGE.PREVIOUS = 'loanList';598					}599					// MODIFY HEADER600					this.BackButtonHeader();601					this.headerObj.setTitleText(this.getMessage('IDS_TITLE_SETTINGS'));602					// MODIFY FOOTER603					this.showFooter(false);604					if(allowExport)605					{606						this.allowExportCB.setSelected(true);607					}608					if(enableNotify)609					{610						this.allowNotifyCB.setSelected(true);611					}612					if(this.isDBEmpty())613					{614						this.exportButton.setEnabled(false);615					}616					else617					{618						this.exportButton.setEnabled(true);	619					}620					this.hideAllPages();621					this.showPage(this.settingsPanel);622					break;623			}624		},625		onButtonAction: function(e)626		{627			var self = this,628				actionId = e.getData().actionId;629			switch(actionId)630			{631				// CAMERA632				case 1:633					this.takeAPicture('camera');634					break;635				// LIBRARY636				case 2:637					this.takeAPicture('library');638					break;639				// CONTACTS640				case 3:641					this.getContacts();642					break;643				// EXPORT644				case 4:645					this.exportDB();646					break;647				// IMPORT648				case 5:649					this.importDB();650					break;651			}652		},653		onListAction: function(e)654		{655			var list = e.getData().source; // get list656				item = list.getItemAt(e.getData().index); // get listIndex657			// FROMLIST/TOLIST658			if(this.loanList.isVisible() || this.borrowList.isVisible())659			{660				this.PAGE.PREVIOUS = this.borrowList.isVisible() ? 'borrowList' : 'loanList';661				var index = parseInt(item.setting.descriptionText, 10), // get arrayIndex662					data  = JSON.parse(localStorage.getItem('db')).results, // query results663					itemData = data[index], // query one specific item664					eventId = (itemData.eventId && itemData.eventId !== -1) ? itemData.eventId : "",665					date = itemData.date,666					endDate = (itemData.endDate && itemData.endDate !== -1) ? itemData.endDate : "",667					type = "";668				if(itemData.type === 2 || itemData.type === 'loan')669				{670					type = "./images/00_icon_arrow-r.png";671				}672				if(itemData.type === 1 || itemData.type === 'borrow')673				{674					type = "./images/00_icon_arrow-l.png";675				}676				if(Osp.Core.Check.isPositiveNumber(date))677				{678					console.log(new Date(date).toLocaleDateString());679					console.log(new Date(date).toDateString());680					date = new Date(date).toLocaleDateString();681				}682				else683				{684					date = new Date(Date.parse(date)).toLocaleDateString();685				}686				if(endDate)687				{688					if(Osp.Core.Check.isPositiveNumber(endDate))689					{690						endDate = new Date(endDate).toLocaleDateString();691					}692					else693					{694						endDate = new Date(Date.parse(endDate)).toLocaleDateString();695					}696				}697				// set data698				this.detailPicLabelValue.setBackgroundImage(itemData.pic);699				this.detailTypeLabelValue.setBackgroundImage(type);700				this.detailPersonLabelValue.setText(itemData.person);701				this.detailStartDateLabelValue.setText(date);702				this.detailEndDateLabelValue.setText(endDate);703				this.detailNoteLabelValue.setText(itemData.note);704				this.detailIdLabelValue.setText(index+'');705				this.detailEventIdLabelValue.setText(eventId+'');706				this.detailTitleLabelValue.setText(itemData.title);707				this.detailStatusLabelValue.setText(itemData.type+'');708				// modify header709				this.BackButtonHeader();710				this.headerObj.setTitleText(itemData.title);711				// modify footer712				this.EditDeleteButtons();713				// show detail page and hide all other pages714				this.hideAllPages();715				this.showPage(this.detailPanel);716				this.CURRENT.ITEM = itemData;717				this.CURRENT.ID = index;718			}719			// CONTACTLIST720			if(this.contactList.isVisible())721			{722				var contactItem = item.setting.elements;723				this.headerObj.removeAllItems();724				this.headerObj.removeAllButtons();725				this.headerObj.setHeaderStyle('title');726				this.showFooter(true);727				this.contactList.removeAllItems();728				this.hideAllPages();729				if(this.PAGE.CURRENT === 'addPage')730				{731					this.headerObj.setTitleText(this.getMessage('IDS_TITLE_NEW_ITEM'));732					this.SaveCancelButtons(3);733					this.personField.setText(contactItem[0].text);734					if(this.checkEmptyFields([this.titleField, this.personField, this.startDateField]))735					{736						this.footerObj.setItemEnabled(0, true);737					}738					else739					{740						this.footerObj.setItemEnabled(0, false);741					}742					this.showPage(this.addPanel);743				}744				else745				{746					this.headerObj.setTitleText(this.getMessage('IDS_TITLE_EDIT_ITEM'));747					this.SaveCancelButtons(8);748					this.editPersonField.setText(contactItem[0].text);749					if(this.checkEmptyFields([this.editTitleField, this.editPersonField, this.editStartDateField]))750					{751						this.footerObj.setItemEnabled(0, true);752					}753					else754					{755						this.footerObj.setItemEnabled(0, false);756					}757					this.showPage(this.editPanel);758				}759			}760		},761		onFastScrollIndexAction: function(e)762		{763			var index = e.getData().index,764				source = e.getData().source;765			console.log(index);766			console.log(source);767		},768		onContextChange: function(e)769		{770			var text = e.getData().text,771				source = e.getData().source, 772				chk1 = false,773				chk2 = false;774			if(this.PAGE.CURRENT === 'addPage')775			{776				chk1 = this.checkEmptyFields([this.titleField, this.personField, this.startDateField]);777			}778			if(this.PAGE.CURRENT === 'editPage')779			{780				chk1 = this.checkEmptyFields([this.editTitleField, this.editPersonField, this.editStartDateField]);781			}782			if(source == this.ID.DATE || source == this.ID.ENDDATE)783			{784				if(!Date.parse(text))785				{786					this.showPopup(source.getTitleText(), this.getMessage('IDS_ERROR_NO_DATE'), "ok");787					chk2 = false;788				}789				else790				{791					chk2 = true;792				}793			}794			if(chk1 && chk2)795			{796				this.footerObj.setItemEnabled(0, true);797			}798		}799	}...DateTimeTime.js
Source:DateTimeTime.js  
1/*******************************************************************************2 * Copyright (c) 2008, 2014 Innoopract Informationssysteme GmbH and others.3 * All rights reserved. This program and the accompanying materials4 * are made available under the terms of the Eclipse Public License v1.05 * which accompanies this distribution, and is available at6 * http://www.eclipse.org/legal/epl-v10.html7 *8 * Contributors:9 *    Innoopract Informationssysteme GmbH - initial API and implementation10 *    EclipseSource - ongoing development11 ******************************************************************************/12rwt.qx.Class.define( "rwt.widgets.DateTimeTime", {13  extend : rwt.widgets.base.Parent,14  construct : function( style ) {15    this.base( arguments );16    this.setOverflow( "hidden" );17    this._short = rwt.util.Strings.contains( style, "short" );18    this._medium = rwt.util.Strings.contains( style, "medium" );19    this._long = rwt.util.Strings.contains( style, "long" );20    this.addEventListener( "keypress", this._onKeyPress, this );21    this.addEventListener( "keyup", this._onKeyUp, this );22    this.addEventListener( "mousewheel", this._onMouseWheel, this );23    this.addEventListener( "focus", this._onFocusIn, this );24    this.addEventListener( "blur", this._onFocusOut, this );25    // Hours26    this._hoursTextField = new rwt.widgets.base.Label( "00" );27    this._hoursTextField.setAppearance( "datetime-field" );28    this._hoursTextField.setUserData( "maxLength", 2 );29    this._hoursTextField.addEventListener( "mousedown",  this._onTextFieldMouseDown, this );30    this.add(this._hoursTextField);31    // Separator32    this._separator3 = new rwt.widgets.base.Label( ":" );33    this._separator3.setAppearance( "datetime-separator" );34    this.add(this._separator3);35    // Minutes36    this._minutesTextField = new rwt.widgets.base.Label( "00" );37    this._minutesTextField.setAppearance( "datetime-field" );38    this._minutesTextField.setUserData( "maxLength", 2 );39    this._minutesTextField.addEventListener( "mousedown",  this._onTextFieldMouseDown, this );40    this.add(this._minutesTextField);41    // Separator42    this._separator4 = new rwt.widgets.base.Label( ":" );43    this._separator4.setAppearance( "datetime-separator" );44    if( this._medium || this._long ) {45      this.add(this._separator4);46    }47    // Seconds48    this._secondsTextField = new rwt.widgets.base.Label( "00" );49    this._secondsTextField.setAppearance( "datetime-field" );50    this._secondsTextField.setUserData( "maxLength", 2 );51    this._secondsTextField.addEventListener( "mousedown",  this._onTextFieldMouseDown, this );52    if( this._medium || this._long ) {53      this.add(this._secondsTextField);54    }55    // Spinner56    this._spinner = this._createSpinner();57    this.add( this._spinner );58    // Set the default focused text field59    this._focusedTextField = this._hoursTextField;60    // Set the appearance after subwidgets are created61    this.setAppearance( "datetime-time" );62  },63  destruct : function() {64    this._disposeObjects( "_hoursTextField",65                          "_minutesTextField",66                          "_secondsTextField",67                          "_focusedTextField",68                          "_spinner",69                          "_separator3",70                          "_separator4" );71  },72  members : {73    _getSubWidgets : function() {74      return [ this._hoursTextField,75               this._minutesTextField,76               this._secondsTextField,77               this._spinner,78               this._separator3,79               this._separator4 ];80    },81    _createSpinner : function() {82      var spinner = new rwt.widgets.base.Spinner();83      spinner.set( {84        wrap: true,85        border: null,86        backgroundColor: null,87        selectTextOnInteract : false88      } );89      spinner.setMin( 0 );90      spinner.setMax( 23 );91      spinner.setValue( 0 );92      spinner.addEventListener( "change",  this._onSpinnerChange, this );93      spinner._textfield.setTabIndex( null );94      // Hack to prevent the spinner text field to request the focus95      spinner._textfield.setFocused = rwt.util.Functions.returnTrue;96      // Solution for Bug 28402197      spinner._textfield.setDisplay( false );98      spinner._upbutton.setAppearance( "datetime-button-up" );99      spinner._downbutton.setAppearance( "datetime-button-down" );100      spinner.removeEventListener( "keypress", spinner._onkeypress, spinner );101      spinner.removeEventListener( "keydown", spinner._onkeydown, spinner );102      spinner.removeEventListener( "keyup", spinner._onkeyup, spinner );103      spinner.removeEventListener( "mousewheel", spinner._onmousewheel, spinner );104      return spinner;105    },106    _applyFont : function( value, old ) {107      this.base( arguments, value, old );108      this._hoursTextField.setFont( value );109      this._minutesTextField.setFont( value );110      this._secondsTextField.setFont( value );111      this._separator3.setFont( value );112      this._separator4.setFont( value );113    },114    _onFocusIn : function() {115      this._focusedTextField.addState( "selected" );116      this._initialEditing = true;117    },118    _onFocusOut : function() {119      this._focusedTextField.removeState( "selected" );120    },121    _onTextFieldMouseDown : function( event ) {122      this._setFocusedTextField( event.getTarget() );123    },124    _setFocusedTextField :  function( textField ) {125      if( this._focusedTextField !== textField ) {126        var tmpValue;127        this._focusedTextField.removeState( "selected" );128        this._focusedTextField = null;129        if( textField === this._hoursTextField ) {130          this._spinner.setMin( 0 );131          this._spinner.setMax( 23 );132          tmpValue = this._removeLeadingZero( this._hoursTextField.getText() );133          this._spinner.setValue( parseInt( tmpValue, 10 ) );134        } else if( textField === this._minutesTextField ) {135          this._spinner.setMin( 0 );136          this._spinner.setMax( 59 );137          tmpValue = this._removeLeadingZero( this._minutesTextField.getText() );138          this._spinner.setValue( parseInt( tmpValue, 10 ) );139        } else if( textField === this._secondsTextField ) {140          this._spinner.setMin( 0 );141          this._spinner.setMax( 59 );142          tmpValue = this._removeLeadingZero( this._secondsTextField.getText() );143          this._spinner.setValue( parseInt( tmpValue, 10 ) );144        }145        this._focusedTextField = textField;146        this._focusedTextField.addState( "selected" );147        this._initialEditing = true;148      }149    },150    _onSpinnerChange : function() {151      if( this._focusedTextField != null ) {152        var oldValue = this._focusedTextField.getText();153        var newValue = this._addLeadingZero( this._spinner.getValue() );154        this._focusedTextField.setText( newValue );155        if( oldValue != newValue ) {156          this._sendChanges();157        }158      }159    },160    _onKeyPress : function( event ) {161      if( event.getModifiers() === 0 ) {162        switch( event.getKeyIdentifier() ) {163          case "Enter":164            this._handleKeyEnter( event );165            break;166          case "Left":167            this._handleKeyLeft( event );168            break;169          case "Right":170            this._handleKeyRight( event );171            break;172          case "Up":173            this._handleKeyUp( event );174            break;175          case "Down":176            this._handleKeyDown( event );177            break;178          case "PageUp":179          case "PageDown":180          case "Home":181          case "End":182            this._stopEvent( event );183            break;184        }185      }186    },187    _onKeyUp : function( event ) {188      if( event.getModifiers() === 0 ) {189        switch( event.getKeyIdentifier() ) {190          case "0": case "1": case "2": case "3": case "4":191          case "5": case "6": case "7": case "8": case "9":192            this._handleKeyNumber( event );193            break;194          case "Home":195            this._handleKeyHome( event );196            break;197          case "End":198            this._handleKeyEnd( event );199            break;200        }201      }202    },203    _handleKeyEnter : function() {204      rwt.remote.EventUtil.notifyDefaultSelected( this );205    },206    _handleKeyLeft : function( event ) {207      if( this._focusedTextField === this._hoursTextField ) {208        if( this._short ) {209          this._setFocusedTextField( this._minutesTextField );210        } else {211          this._setFocusedTextField( this._secondsTextField );212        }213      } else if( this._focusedTextField === this._minutesTextField ) {214        this._setFocusedTextField( this._hoursTextField );215      } else if( this._focusedTextField === this._secondsTextField ) {216        this._setFocusedTextField( this._minutesTextField );217      }218      this._stopEvent( event );219    },220    _handleKeyRight : function( event ) {221      if( this._focusedTextField === this._hoursTextField ) {222        this._setFocusedTextField( this._minutesTextField );223      } else if( this._focusedTextField === this._minutesTextField ) {224        if( this._short ) {225          this._setFocusedTextField( this._hoursTextField );226        } else {227          this._setFocusedTextField( this._secondsTextField );228        }229      } else if( this._focusedTextField === this._secondsTextField ) {230        this._setFocusedTextField( this._hoursTextField );231      }232      this._stopEvent( event );233    },234    _handleKeyDown : function( event ) {235      var value = this._spinner.getValue();236      if( value == this._spinner.getMin() ) {237        this._spinner.setValue( this._spinner.getMax() );238      } else {239        this._spinner.setValue( value - 1 );240      }241      this._stopEvent( event );242    },243    _handleKeyUp : function( event ) {244      var value = this._spinner.getValue();245      if( value == this._spinner.getMax() ) {246        this._spinner.setValue( this._spinner.getMin() );247      } else {248        this._spinner.setValue( value + 1 );249      }250      this._stopEvent( event );251    },252    _handleKeyNumber : function( event ) {253      var key = event.getKeyIdentifier();254      var value = this._removeLeadingZero( this._focusedTextField.getText() );255      var maxChars = this._focusedTextField.getUserData( "maxLength" );256      var newValue = value.length < maxChars && !this._initialEditing ? value + key : key;257      var intValue = parseInt( newValue, 10 );258      if( intValue >= this._spinner.getMin() && intValue <= this._spinner.getMax() ) {259        this._spinner.setValue( intValue );260      } else {261        intValue = parseInt( key, 10 );262        if( intValue >= this._spinner.getMin() && intValue <= this._spinner.getMax() ) {263          this._spinner.setValue( intValue );264        }265      }266      this._initialEditing = false;267      this._stopEvent( event );268    },269    _handleKeyHome : function( event ) {270      this._spinner.setValue( this._spinner.getMin() );271      this._initialEditing = true;272      this._stopEvent( event );273    },274    _handleKeyEnd : function( event ) {275      this._spinner.setValue( this._spinner.getMax() );276      this._initialEditing = true;277      this._stopEvent( event );278    },279    _onMouseWheel : function( event ) {280      if( this.getFocused() ) {281        this._stopEvent( event );282        this._spinner._onmousewheel( event );283      }284    },285    _stopEvent : function( event ) {286      event.preventDefault();287      event.stopPropagation();288    },289    _addLeadingZero : function( value ) {290      return value < 10 ? "0" + value : "" + value;291    },292    _removeLeadingZero : function( value ) {293      var result = value;294      if( value.length == 2 ) {295        var firstChar = value.substring( 0, 1 );296        if( firstChar == "0" ) {297          result = value.substring( 1 );298        }299      }300      return result;301    },302    _sendChanges : function() {303      if( !rwt.remote.EventUtil.getSuspended() ) {304        var connection = rwt.remote.Connection.getInstance();305        var remoteObject = connection.getRemoteObject( this );306        var hours = parseInt( this._removeLeadingZero( this._hoursTextField.getText() ), 10 );307        remoteObject.set( "hours", hours );308        var minutes = parseInt( this._removeLeadingZero( this._minutesTextField.getText() ), 10 );309        remoteObject.set( "minutes", minutes );310        var seconds = parseInt( this._removeLeadingZero( this._secondsTextField.getText() ), 10 );311        remoteObject.set( "seconds", seconds );312        if( remoteObject.isListening( "Selection" ) ) {313          connection.onNextSend( this._onSend, this );314          connection.sendDelayed( 200 );315        }316      }317    },318    _onSend : function() {319      rwt.remote.EventUtil.notifySelected( this );320    },321    setHours : function( value ) {322      this._hoursTextField.setText( this._addLeadingZero( value ) );323      if( this._focusedTextField === this._hoursTextField ) {324        this._spinner.setValue( value );325      }326    },327    setMinutes : function( value ) {328      this._minutesTextField.setText( this._addLeadingZero( value ) );329      if( this._focusedTextField === this._minutesTextField ) {330        this._spinner.setValue( value );331      }332    },333    setSeconds : function( value ) {334      this._secondsTextField.setText( this._addLeadingZero( value ) );335      if( this._focusedTextField === this._secondsTextField ) {336        this._spinner.setValue( value );337      }338    },339    setBounds : function( index, x, y, width, height ) {340      var widget;341      switch( index ) {342        case 7:343          widget = this._spinner;344        break;345        case 8:346          widget = this._hoursTextField;347        break;348        case 9:349          widget = this._minutesTextField;350        break;351        case 10:352          widget = this._secondsTextField;353        break;354        case 11:355          widget = this._separator3;356        break;357        case 12:358          widget = this._separator4;359        break;360      }361      widget.set( {362        left: x,363        top: y,364        width: width,365        height: height366      } );367    }368  }...DateTimeTimeTest.js
Source:DateTimeTimeTest.js  
1/*******************************************************************************2 * Copyright (c) 2011, 2014 EclipseSource and others.3 * All rights reserved. This program and the accompanying materials4 * are made available under the terms of the Eclipse Public License v1.05 * which accompanies this distribution, and is available at6 * http://www.eclipse.org/legal/epl-v10.html7 *8 * Contributors:9 *    EclipseSource - initial API and implementation10 ******************************************************************************/11(function() {12var TestUtil = org.eclipse.rwt.test.fixture.TestUtil;13var ObjectRegistry = rwt.remote.ObjectRegistry;14var Processor = rwt.remote.MessageProcessor;15var shell;16rwt.qx.Class.define( "org.eclipse.rwt.test.tests.DateTimeTimeTest", {17  extend : rwt.qx.Object,18  members : {19    setUp : function() {20      shell = TestUtil.createShellByProtocol( "w2" );21      TestUtil.flush();22    },23    tearDown : function() {24      shell.destroy();25    },26    testDateTimeHandlerEventsList : function() {27      var handler = rwt.remote.HandlerRegistry.getHandler( "rwt.widgets.DateTime" );28      assertEquals( [ "Selection", "DefaultSelection" ], handler.events );29    },30    testCreateDateTimeTimeByProtocol : function() {31      Processor.processOperation( {32        "target" : "w3",33        "action" : "create",34        "type" : "rwt.widgets.DateTime",35        "properties" : {36          "style" : [ "TIME", "MEDIUM" ],37          "parent" : "w2"38        }39      } );40      var widget = ObjectRegistry.getObject( "w3" );41      assertTrue( widget instanceof rwt.widgets.DateTimeTime );42      assertIdentical( shell, widget.getParent() );43      assertTrue( widget.getUserData( "isControl" ) );44      assertEquals( "datetime-time", widget.getAppearance() );45      assertTrue( widget._medium );46      assertFalse( widget._short );47      assertFalse( widget._long );48      widget.destroy();49    },50    testSetHoursByProtocol : function() {51      Processor.processOperation( {52        "target" : "w3",53        "action" : "create",54        "type" : "rwt.widgets.DateTime",55        "properties" : {56          "style" : [ "TIME", "MEDIUM" ],57          "parent" : "w2",58          "hours" : 359        }60      } );61      var widget = ObjectRegistry.getObject( "w3" );62      assertEquals( "03", widget._hoursTextField.getText() );63      widget.destroy();64    },65    testSetMinutesByProtocol : function() {66      Processor.processOperation( {67        "target" : "w3",68        "action" : "create",69        "type" : "rwt.widgets.DateTime",70        "properties" : {71          "style" : [ "TIME", "MEDIUM" ],72          "parent" : "w2",73          "minutes" : 3374        }75      } );76      var widget = ObjectRegistry.getObject( "w3" );77      assertEquals( "33", widget._minutesTextField.getText() );78      widget.destroy();79    },80    testSetSecondsByProtocol : function() {81      Processor.processOperation( {82        "target" : "w3",83        "action" : "create",84        "type" : "rwt.widgets.DateTime",85        "properties" : {86          "style" : [ "TIME", "MEDIUM" ],87          "parent" : "w2",88          "seconds" : 2289        }90      } );91      var widget = ObjectRegistry.getObject( "w3" );92      assertEquals( "22", widget._secondsTextField.getText() );93      widget.destroy();94    },95    testSetSubWidgetsBoundsByProtocol : function() {96      Processor.processOperation( {97        "target" : "w3",98        "action" : "create",99        "type" : "rwt.widgets.DateTime",100        "properties" : {101          "style" : [ "TIME", "MEDIUM" ],102          "parent" : "w2",103          "subWidgetsBounds" : [ [ 8, 3, 5, 24, 18 ], [ 11, 27, 5, 6, 18 ] ]104        }105      } );106      var widget = ObjectRegistry.getObject( "w3" );107      assertEquals( 3, widget._hoursTextField.getLeft() );108      assertEquals( 5, widget._hoursTextField.getTop() );109      assertEquals( 24, widget._hoursTextField.getWidth() );110      assertEquals( 18, widget._hoursTextField.getHeight() );111      assertEquals( 27, widget._separator3.getLeft() );112      assertEquals( 5, widget._separator3.getTop() );113      assertEquals( 6, widget._separator3.getWidth() );114      assertEquals( 18, widget._separator3.getHeight() );115      widget.destroy();116    },117    testCreateDateTimeTime : function() {118      var dateTime = this._createDefaultDateTimeTime();119      assertTrue( dateTime instanceof rwt.widgets.DateTimeTime );120      assertEquals( "datetime-time", dateTime.getAppearance() );121      assertFalse( dateTime._spinner.getSelectTextOnInteract() );122      dateTime.destroy();123    },124    testSendAllFieldsTogether : function() {125      var dateTime = this._createDefaultDateTimeTime();126      dateTime.setHours( 4 );127      dateTime.setMinutes( 34 );128      dateTime.setSeconds( 55 );129      TestUtil.clearRequestLog();130      TestUtil.press( dateTime, "Up" );131      rwt.remote.Connection.getInstance().send();132      assertEquals( 1, TestUtil.getRequestsSend() );133      var message = TestUtil.getMessageObject();134      assertEquals( 5, message.findSetProperty( "w3", "hours" ) );135      assertEquals( 34, message.findSetProperty( "w3", "minutes" ) );136      assertEquals( 55, message.findSetProperty( "w3", "seconds" ) );137      dateTime.destroy();138    },139    testSendSelectionEvent : function() {140      var dateTime = this._createDefaultDateTimeTime();141      TestUtil.fakeListener( dateTime, "Selection", true );142      TestUtil.clearRequestLog();143      TestUtil.press( dateTime, "Up" );144      TestUtil.forceInterval( rwt.remote.Connection.getInstance()._delayTimer );145      assertEquals( 1, TestUtil.getRequestsSend() );146      var message = TestUtil.getMessageObject();147      assertNotNull( message.findNotifyOperation( "w3", "Selection" ) );148      dateTime.destroy();149    },150    testSendDefaultSelectionEvent : function() {151      var dateTime = this._createDefaultDateTimeTime();152      TestUtil.fakeListener( dateTime, "DefaultSelection", true );153      TestUtil.clearRequestLog();154      TestUtil.press( dateTime, "Enter" );155      assertEquals( 1, TestUtil.getRequestsSend() );156      var message = TestUtil.getMessageObject();157      assertNotNull( message.findNotifyOperation( "w3", "DefaultSelection" ) );158      dateTime.destroy();159    },160    // see bug 358531161    testEditingWithKeyboard_InitialEditing : function() {162      var dateTime = this._createDefaultDateTimeTime();163      dateTime.setHours( 2 );164      dateTime.setMinutes( 2 );165      dateTime.setSeconds( 2 );166      TestUtil.click( dateTime._minutesTextField );167      TestUtil.flush();168      TestUtil.press( dateTime, "1" );169      TestUtil.press( dateTime, "3" );170      assertEquals( "13", dateTime._minutesTextField.getText() );171      dateTime.destroy();172    },173    testEditingWithKeyboard_ContinualEditing : function() {174      var dateTime = this._createDefaultDateTimeTime();175      dateTime.setHours( 2 );176      dateTime.setMinutes( 2 );177      dateTime.setSeconds( 2 );178      TestUtil.click( dateTime._minutesTextField );179      TestUtil.flush();180      TestUtil.press( dateTime, "2" );181      TestUtil.press( dateTime, "1" );182      TestUtil.press( dateTime, "3" );183      assertEquals( "03", dateTime._minutesTextField.getText() );184      dateTime.destroy();185    },186    testSetCustomVariant : function() {187      var dateTime = this._createDefaultDateTimeTime();188      dateTime.setCustomVariant( "foo" );189      assertEquals( "foo", dateTime._hoursTextField._customVariant );190      assertEquals( "foo", dateTime._minutesTextField._customVariant );191      assertEquals( "foo", dateTime._secondsTextField._customVariant );192      assertEquals( "foo", dateTime._spinner._customVariant );193      assertEquals( "foo", dateTime._separator3._customVariant );194      assertEquals( "foo", dateTime._separator4._customVariant );195      dateTime.destroy();196    },197    testRollLeft : function() {198      var dateTime = this._createDefaultDateTimeTime();199      TestUtil.press( dateTime, "Left" );200      assertTrue( dateTime._secondsTextField.hasState( "selected" ) );201      TestUtil.press( dateTime, "Left" );202      assertTrue( dateTime._minutesTextField.hasState( "selected" ) );203      TestUtil.press( dateTime, "Left" );204      assertTrue( dateTime._hoursTextField.hasState( "selected" ) );205      TestUtil.press( dateTime, "Left" );206      assertTrue( dateTime._secondsTextField.hasState( "selected" ) );207      dateTime.destroy();208    },209    testRollRight : function() {210      var dateTime = this._createDefaultDateTimeTime();211      TestUtil.press( dateTime, "Right" );212      assertTrue( dateTime._minutesTextField.hasState( "selected" ) );213      TestUtil.press( dateTime, "Right" );214      assertTrue( dateTime._secondsTextField.hasState( "selected" ) );215      TestUtil.press( dateTime, "Right" );216      assertTrue( dateTime._hoursTextField.hasState( "selected" ) );217      TestUtil.press( dateTime, "Right" );218      assertTrue( dateTime._minutesTextField.hasState( "selected" ) );219      dateTime.destroy();220    },221    testPressHome : function() {222      var dateTime = this._createDefaultDateTimeTime();223      dateTime.setHours( 4 );224      TestUtil.press( dateTime, "Home" );225      assertEquals( "00", dateTime._hoursTextField.getText() );226      dateTime.destroy();227    },228    testPressEnd : function() {229      var dateTime = this._createDefaultDateTimeTime();230      dateTime.setHours( 4 );231      TestUtil.press( dateTime, "End" );232      assertEquals( "23", dateTime._hoursTextField.getText() );233      dateTime.destroy();234    },235    testRollWithMouseWheel : function() {236      var dateTime = this._createDefaultDateTimeTime();237      dateTime.setFocused( true );238      dateTime.setHours( 4 );239      TestUtil.fakeWheel( dateTime, -1 );240      assertEquals( "03", dateTime._hoursTextField.getText() );241      dateTime.destroy();242    },243    //////////244    // Helpers245    _createDefaultDateTimeTime : function() {246      var dateTime = new rwt.widgets.DateTimeTime( "medium" );247      var handler = rwt.remote.HandlerRegistry.getHandler( "rwt.widgets.DateTime" );248      ObjectRegistry.add( "w3", dateTime, handler );249      dateTime.setSpace( 3, 115, 3, 20 );250      dateTime.addToDocument();251      TestUtil.flush();252      return dateTime;253    }254  }255} );...event_filters_spec.js
Source:event_filters_spec.js  
...19            page.filterBy('Status', 'Ingesting');20            page.filterBy('Source', 'Twitter');21        });22        it('displays the selected filters', function () {23            expect(page.filter.field.getText()).toContain('Status: Ingesting');24            expect(page.filter.field.getText()).toContain('Source: Twitter');25        });26        it('clears the filter when asked to', function () {27            page.filter.clearButton.click();28            expect(page.filter.field.getText()).not.toContain('Status: Ingesting');29            expect(page.filter.field.getText()).not.toContain('Sources: Twitter');30        });31        it('restores filters when reloading the page', function () {32            page.get();33            expect(page.filter.field.getText()).toContain('Status: Ingesting');34            expect(page.filter.field.getText()).toContain('Source: Twitter');35            expect(page.filter.textFilter.getAttribute('value')).toContain('Something');36        });37    });38    describe('filter profiles', function () {39        beforeEach(function () {40            page.filterBy('Status', 'Ingesting');41            page.filterBy('Source', 'Twitter');42            page.profile.menuButton.click();43        });44        it('allows saving the current filters', function () {45            expect(page.profile.profiles.getText()).not.toContain('My Filter');46            expect(page.profile.nameField.isDisplayed()).toBe(false);47            page.profile.formButton.click();48            expect(page.profile.nameField.isDisplayed()).toBe(true);49            page.profile.nameField.sendKeys('My Filter');50            page.profile.saveButton.click();51            page.profile.menuButton.click();52            expect(page.profile.profiles.getText()).toContain('My Filter');53            expect(page.profile.activeProfile.getText()).toEqual('My Filter');54        });55        describe('with a previous filter', function () {56            beforeEach(function () {57                page.profile.formButton.click();58                page.profile.nameField.sendKeys('Twitter');59                page.profile.saveButton.click();60                page.filterBy('Status', 'Recording');61                page.filterBy('Source', 'Facebook');62            });63            it('saves a new profile', function () {64                page.profile.menuButton.click();65                page.profile.formButton.click();66                page.profile.nameField.sendKeys('Facebook');67                page.profile.saveButton.click();68                page.profile.menuButton.click();69                expect(page.profile.profiles.getText()).toContain('Twitter');70                expect(page.profile.profiles.getText()).toContain('Facebook');71                expect(page.profile.activeProfile.getText()).toEqual('Facebook');72            });73        });74        describe('loading a profile', function () {75            beforeEach(function () {76                page.profile.formButton.click();77                page.profile.nameField.sendKeys('Twitter');78                page.profile.saveButton.click();79                page.filterBy('Status', 'Recording');80                page.filterBy('Source', 'Facebook');81                page.profile.menuButton.click();82                page.profile.formButton.click();83                page.profile.nameField.sendKeys('Facebook');84                page.profile.saveButton.click();85                page.profile.menuButton.click();86            });87            it('restores saved filters', function () {88                expect(page.filter.field.getText()).toContain('Status: Recording');89                expect(page.filter.field.getText()).toContain('Source: Facebook');90                element(by.linkText('Twitter')).click();91                expect(page.filter.field.getText()).toContain('Status: Ingesting');92                expect(page.filter.field.getText()).toContain('Source: Twitter');93            });94            it('persists across page reload', function () {95                element(by.linkText('Twitter')).click();96                expect(page.filter.field.getText()).toContain('Status: Ingesting');97                expect(page.filter.field.getText()).toContain('Source: Twitter');98                page.get();99                expect(page.filter.field.getText()).toContain('Status: Ingesting');100                expect(page.filter.field.getText()).toContain('Source: Twitter');101                page.profile.menuButton.click();102                expect(page.profile.profiles.getText()).toContain('Twitter');103                expect(page.profile.profiles.getText()).toContain('Facebook');104            });105        });106        describe('editing a profile', function () {107            beforeEach(function () {108                page.profile.formButton.click();109                page.profile.nameField.sendKeys('Twitter');110                page.profile.saveButton.click();111                page.filterBy('Status', 'Recording');112                page.filterBy('Source', 'Facebook');113                page.profile.menuButton.click();114                page.profile.formButton.click();...field.component.js
Source:field.component.js  
...34           [ngModel]="field.getValue()" (ngModelChange)="setNumberValue($event)"35           [attr.aria-label]="disabled ? 'Disabled number field' : 'Press Enter to edit number: ' + field.getValue()"36           tabindex="-1">37    <div *ngIf="isDropdown()">38      <label [id]="mainFieldId" [attr.aria-label]="('CURRENT_ARGUMENT_VALUE'|translate) + ' ' + field.getText() + ' Move right to view submenu'">39        {{'CURRENT_ARGUMENT_VALUE'|translate}} {{field.getText()}}40      </label>41      <ol role="group">42        <li [id]="idMap[optionValue]" role="treeitem" *ngFor="#optionValue of getOptions()"43            [attr.aria-labelledBy]="generateAriaLabelledByAttr(idMap[optionValue + 'Button'], 'blockly-button')"44            [attr.aria-level]="level" [attr.aria-selected]="field.getValue() == optionValue">45          <button [id]="idMap[optionValue + 'Button']" (click)="handleDropdownChange(field, optionValue)"46                  [disabled]="disabled" tabindex="-1"47                  [attr.aria-label]="optionText[optionValue] + ' Press Enter to select this value'">48            {{optionText[optionValue]}}49          </button>50        </li>51      </ol>52    </div>53    <div *ngIf="isCheckbox()">54      // Checkboxes are not currently supported.55    </div>56    <label [id]="mainFieldId" *ngIf="isTextField() && hasVisibleText()">57      {{field.getText()}}58    </label>59    `,60    inputs: ['field', 'index', 'parentId', 'disabled', 'mainFieldId', 'level'],61    pipes: [blocklyApp.TranslatePipe]62  })63  .Class({64    constructor: [blocklyApp.UtilsService, function(_utilsService) {65      this.optionText = {66        keys: []67      };68      this.utilsService = _utilsService;69    }],70    ngOnInit: function() {71      var elementsNeedingIds = this.generateElementNames(this.field);72      // Warning: this assumes that the elements returned by73      // this.generateElementNames() are unique.74      this.idMap = this.utilsService.generateIds(elementsNeedingIds);75    },76    setNumberValue: function(newValue) {77      // Do not permit a residual value of NaN after a backspace event.78      this.field.setValue(newValue || 0);79    },80    generateAriaLabelledByAttr: function(mainLabel, secondLabel) {81      return mainLabel + ' ' + secondLabel;82    },83    generateElementNames: function() {84      var elementNames = [];85      if (this.isDropdown()) {86        var keys = this.getOptions();87        for (var i = 0; i < keys.length; i++){88          elementNames.push(keys[i], keys[i] + 'Button');89        }90      }91      return elementNames;92    },93    isNumberInput: function() {94      return this.field instanceof Blockly.FieldNumber;95    },96    isTextInput: function() {97      return this.field instanceof Blockly.FieldTextInput &&98          !(this.field instanceof Blockly.FieldNumber);99    },100    isDropdown: function() {101      return this.field instanceof Blockly.FieldDropdown;102    },103    isCheckbox: function() {104      return this.field instanceof Blockly.FieldCheckbox;105    },106    isTextField: function() {107      return !(this.field instanceof Blockly.FieldTextInput) &&108          !(this.field instanceof Blockly.FieldDropdown) &&109          !(this.field instanceof Blockly.FieldCheckbox);110    },111    hasVisibleText: function() {112      var text = this.field.getText().trim();113      return !!text;114    },115    getOptions: function() {116      if (this.optionText.keys.length) {117        return this.optionText.keys;118      }119      var options = this.field.getOptions_();120      for (var i = 0; i < options.length; i++) {121        var tuple = options[i];122        this.optionText[tuple[1]] = tuple[0];123        this.optionText.keys.push(tuple[1]);124      }125      return this.optionText.keys;126    },...auth.js
Source:auth.js  
1describe('Registration', function() {2  var fnameField, lnameField, emailField, passwordField;3  beforeEach(function() {4    fnameField = element(by.id('name'));5    lnameField = element(by.id('lname'));6    emailField = element(by.id('email'));7    passwordField = element(by.id('password'));8  });9  it('page fields should be empty', function() {10    browser.get('/#/register');11    expect(fnameField.getText()).toEqual('');12    expect(lnameField.getText()).toEqual('');13    expect(passwordField.getText()).toEqual('');14    expect(emailField.getText()).toEqual('');15  });16  it('should require all fields to be filled', function(){17    fnameField.sendKeys('Doe');18    element(by.name('button')).click();19    expect(browser.getCurrentUrl()).toMatch(/\/#\/register/);20    fnameField.clear();21  });22  it('should create a new user', function(){23    fnameField.sendKeys("Johnny");24    lnameField.sendKeys("Does");25    emailField.sendKeys("johnnydoes@doedoes.com");26    passwordField.sendKeys("doespassword");27    element(by.name('button')).click();28    expect(browser.getCurrentUrl()).toMatch(/\/#\/login/);29  });30});31describe('Login', function(){32  var emailField, passwordField;33  beforeEach(function() {34    emailField = element(by.id('email'));35    passwordField = element(by.id('password'));36  });37  it('page fields should be empty', function() {38    browser.get('/#/login');39    expect(passwordField.getText()).toEqual('');40    expect(emailField.getText()).toEqual('');41  });42  it('should require all fields to be filled', function(){43    element(by.name('button')).click();44    var errorMsg = element(by.css('.text-danger'));45    expect(errorMsg.getText()).toBe('Wrong email/password.');46  });47  it('should succeed with valid credentials', function(){48    emailField.sendKeys("johnnydoes@doedoes.com");49    passwordField.sendKeys("doespassword");50    element(by.name('button')).click();51    expect(browser.getCurrentUrl()).toMatch(/\/#\//);52    expect(element(by.css('.page')).getText()).toBe("Dashboard");53  })...click.js
Source:click.js  
1var tests = {2    "Should not break ng-click": function (file) {3        return function () {4            browser.get("http://localhost:9000/test/fixtures/click" + file + ".html");5            element(by.css("button#test1")).click();6            expect(element(by.css("#field")).getText()).toBe("Success");7        };8    },9    "Should not break ng-click for translated strings": function (file) {10        return function () {11            browser.get("http://localhost:9000/test/fixtures/click" + file + ".html");12            element(by.css("button#test2")).click();13            expect(element(by.css("#field")).getText()).toBe("Success");14        };15    },16    "Should compile ng-click": function (file) {17        return function () {18            browser.get("http://localhost:9000/test/fixtures/click" + file + ".html");19            element(by.css("#test3 button")).click();20            expect(element(by.css("#field")).getText()).toBe("Success");21        };22    }23};24describe("Click", function () {25    for (var key in tests) {26        it(key, tests[key](""));27    }28});29describe("Click (no jQuery)", function () {30    for (var key in tests) {31        it(key, tests[key]("-nojquery"));32    }...tableview.js
Source:tableview.js  
1var $webfx = {title: "TableView Example"};2/**3function addPerson(event) {4        ObservableList<Person> data = tableView.getItems();5        data.add(new Person(firstNameField.getText(),6            lastNameField.getText(),7            emailField.getText()8        ));9        10        firstNameField.setText("");11        lastNameField.setText("");12        emailField.setText("");   13    }...Using AI Code Generation
1package com.appium.tests;2import java.net.MalformedURLException;3import java.net.URL;4import java.util.concurrent.TimeUnit;5import org.openqa.selenium.By;6import org.openqa.selenium.WebElement;7import org.openqa.selenium.remote.DesiredCapabilities;8import io.appium.java_client.AppiumDriver;9import io.appium.java_client.MobileElement;10import io.appium.java_client.android.AndroidDriver;11public class Test {12public static void main(String[] args) throws MalformedURLException, InterruptedException {13    DesiredCapabilities cap = new DesiredCapabilities();14    cap.setCapability("deviceName", "Android");15    cap.setCapability("platformName", "Android");16    cap.setCapability("platformVersion", "7.0");17    cap.setCapability("appPackage", "com.android.calculator2");18    cap.setCapability("appActivity", "com.android.calculator2.Calculator");Using AI Code Generation
1var webdriver = require('selenium-webdriver');2var driver = new webdriver.Builder()3    .forBrowser('firefox')4    .build();5driver.findElement(webdriver.By.name('q')).sendKeys('webdriver');6driver.findElement(webdriver.By.name('btnG')).click();7driver.wait(function() {8  return driver.getTitle().then(function(title) {9    return title === 'webdriver - Google Search';10  });11}, 1000);12driver.getTitle().then(function(title) {13    console.log("Title is: " + title);14});15Error: TypeError: driver.getTitle(...).then is not a function16    at Object.<anonymous> (C:\Users\user\Desktop\New folder\test.js:13:16)17    at Module._compile (module.js:556:32)18    at Object.Module._extensions..js (module.js:565:10)19    at Module.load (module.js:473:32)20    at tryModuleLoad (module.js:432:12)21    at Function.Module._load (module.js:424:3)22    at Function.Module.runMain (module.js:590:10)23    at startup (bootstrap_node.js:194:16)24driver.getTitle().then(function(title) {25    console.log("Title is: " + title);26});27Error: TypeError: driver.getTitle(...).then is not a function28    at Object.<anonymous> (C:\Users\user\Desktop\New folder\test.js:13:16)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!!
