How to use isNativeContext method in Appium Xcuitest Driver

Best JavaScript code snippet using appium-xcuitest-driver

bizagi.rendering.tablet.upload.js

Source:bizagi.rendering.tablet.upload.js Github

copy

Full Screen

1/*2 * Name: BizAgi Tablet Render upload Extension3 * Author: Bizagi Mobile Team4 * Comments:5 * - This script will redefine the label render class to adjust to smartphones devices6 */7// Extends itself8bizagi.rendering.upload.extend("bizagi.rendering.upload", {9 BA_ACTION_PARAMETER_PREFIX: bizagi.render.services.service.BA_ACTION_PARAMETER_PREFIX,10 BA_CONTEXT_PARAMETER_PREFIX: bizagi.render.services.service.BA_CONTEXT_PARAMETER_PREFIX,11 QUALITY_PICTURE: 80,12 LIMIT: 1, // limit: The maximum number of audio clips,video clips, etc.13 // in the device user can record in a single capture operation.14 EXTENSIONSIMG: ["image/jpeg", "jpeg", "image", "png", "jpg"],15 EXTENSIONSFILE: ["doc", "docx", "xls", "xlsx", "ppt", "pptx", "pdf", "zip", "rar", "txt"],16 EXTENSIONSVIDEO: ["video/quicktime", "quicktime", "qt", "mov"],17 EXTENSIONSAUDIO: ["audio/wav", "audio", "wav"]18}, {19 postRender: function() {20 var self = this;21 var properties = self.properties;22 // Call base 23 self._super();24 if ((!bizagi.util.isCordovaSupported( ) && !bizagi.util.media.fileAPISupported()) || !properties.editable) {25 self.addEventToOpenSlide();26 } else if ( !bizagi.util.isCordovaSupported( ) ) {27 self.activeUploadWebControl();28 } else {29 self.activateUploadNative();30 }31 //Handler to download the file32 $("ul.files", self.getControl()).on("click", ".ui-bizagi-render-link.button", function (e) {33 if (bizagi.util.isNativePluginSupported()) {34 // ios native behaviour, should open files through a webview35 bizagiapp.openFileWebView({ "itemUrl": $(this).attr("data-url") });36 } else {37 // Android38 bizagi.util.media.downloadFile($(this).attr("data-url"), this.title);39 }40 });41 },42 /**43 * Render readonly44 * @returns {}45 */46 postRenderReadOnly: function() {47 var self = this;48 // Call base 49 self._super();50 if (bizagi.util.isNativePluginSupported()) {51 var filesLinkElements = self.getControl().find(".ui-bizagi-render-link");52 filesLinkElements.on("click", function() {53 bizagiapp.openFileWebView({ "itemUrl": $(this).attr("data-url") });54 });55 } else if (!bizagi.util.isCordovaSupported()) {56 if (self.files !== "undefined" && self.files.length > 0) {57 self.addEventToOpenSlide();58 }59 }60 },61 /**62 * Attach open slide63 * @returns {}64 */65 addEventToOpenSlide: function() {66 var self = this;67 var mode = self.getMode();68 var control = self.getControl();69 var container = self.getControl();70 var formParams = self.getFormParams();71 self.itemAddfile = $(".bz-rn-upload-show-menu", container);72 self.itemAddfile.hide();73 if( !bizagi.util.isCordovaSupported( ) && !bizagi.util.media.fileAPISupported() ) {74 self.element.addClass("bz-rn-read-only");75 }76 $("li", control).click(function(event) {77 var url = $(this).data("url");78 if (mode === "execution") {79 // Avoid redirect & download80 event.preventDefault();81 event.stopPropagation();82 var slideView = new bizagi.rendering.tablet.slide.view.upload(self.dataService, self.renderFactory, {83 title: self.properties.displayName || "",84 container: self.getFormContainer().container,85 formParams: formParams,86 navigation: formParams.navigation,87 url: url88 });89 slideView.render({ url: url });90 }91 });92 },93 /**94 * Active upload by native mode95 * @returns {}96 */97 activateUploadNative: function() {98 var self = this;99 var properties = self.properties;100 var container = self.getControl();101 self.renderControl();102 self.itemAddfile = $(".bz-rn-upload-show-menu", container);103 if (!bizagi.util.isCordovaSupported() || !properties.editable) {104 self.itemAddfile.hide();105 }106 // Check files number107 self.checkMaxFiles();108 // Attach delete option109 self.attachDeleteHandler();110 // Check files extensions111 self.checkExtensions();112 // Not has valid extensions113 if (self.validOptions && (!self.validOptions.image && !self.validOptions.video && !self.validOptions.audio)) {114 self.itemAddfile.hide();115 return;116 }117 var uploadTemplate = self.renderFactory.getTemplate("uploadModalView");118 var kendoTemplate = kendo.template(uploadTemplate, { useWithBlock: false });119 // Creating modal view 120 var $modalView = $.trim(kendoTemplate({121 editable: self.properties.editable,122 noFiles: self.properties.noFiles,123 displayName: self.properties.displayName || "",124 validExtensions: self.validOptions125 }));126 self.itemAddfile.bind("click", function(e) {127 var modalView = new kendo.mobile.ui.ModalView($modalView, {128 close: function() {129 this.destroy();130 this.element.remove();131 },132 modal: false133 });134 self.configureModalViewHandlers(modalView.element);135 modalView.open();136 });137 },138 /**139 * Configure the modalView Handlers for the new combo control.140 * @param {} inputContainer141 * @returns {}142 */143 configureModalViewHandlers: function(inputContainer) {144 var self = this;145 // Getting combo list elements146 self.listOptions = inputContainer.find(".bz-rn-upload-options li");147 // Setting the initial selected display value148 self.listOptions.bind("click", function() {149 self.applyPlugin($(this).data("role"), this.getBoundingClientRect());150 });151 inputContainer.find(".bz-wp-modalview-close").bind("click", function() {152 if (inputContainer.data("kendoMobileModalView")) {153 inputContainer.data("kendoMobileModalView").close();154 }155 });156 },157 /**158 * Attach delete option159 * @returns {}160 */161 attachDeleteHandler: function() {162 var self = this;163 var control = self.getControl();164 $(".bz-rn-upload-delete-icon", control).bind("click", function() {165 var item = $(this).parent(".ui-bizagi-render-upload-item");166 var file = item.data();167 $.when(self.deleteUploadItem(item, file.id))168 .done(function() {169 // Remove item170 item.hide();171 item.remove();172 // Update value173 self.setValue(self.files, false);174 // Check maxFiles175 self.checkMaxFiles();176 // Trigger change177 self.triggerRenderChange();178 });179 });180 },181 /**182 * Apply plugin183 * @param {} option184 * @param {} coordinates185 * @returns {}186 */187 applyPlugin: function(option, coordinates) {188 var self = this;189 var resolutionUpload;190 // If android version is less than 4.4 avoid to show upload sizes due to compatibility with blob files191 var version = bizagi.util.getAndroidVersion();192 var hideUploadSizes = version && version <= 4.4;193 // Resolution upload menu194 if (hideUploadSizes) {195 resolutionUpload = [196 { "guid": 4, "displayName": bizagi.localization.getResource("workportal-size-original") }197 ];198 } else {199 resolutionUpload = [200 { "guid": 1, "displayName": bizagi.localization.getResource("workportal-size-small") },201 { "guid": 2, "displayName": bizagi.localization.getResource("workportal-size-medium") },202 { "guid": 3, "displayName": bizagi.localization.getResource("workportal-size-large") },203 { "guid": 4, "displayName": bizagi.localization.getResource("workportal-size-original") }204 ];205 }206 // Attach document207 $(".bz-resolution-container", self.getControl()).actionSheet({208 actions: resolutionUpload,209 actionClicked: function(action) {210 $.when(self.resolutionButtonHandler(action.guid)).done(function() {211 self.closeModalView();212 });213 }214 });215 switch (option) {216 case "image":217 // Check is offline form 218 var isOfflineForm = bizagi.util.isOfflineForm({ context: self });219 // Select image220 var popover = new CameraPopoverOptions(coordinates.left, coordinates.top - 20, 200, 100, 4);221 var options = {222 quality: self.Class.QUALITY_PICTURE,223 sourceType: Camera.PictureSourceType.PHOTOLIBRARY,224 popoverOptions: popover225 };226 navigator.camera.getPicture(function(dataImage) {227 self.dataImage = dataImage;228 var extensions = self.Class.EXTENSIONSIMG.concat(self.Class.EXTENSIONSAUDIO, self.Class229 .EXTENSIONSVIDEO);230 $.when(bizagi.util.media.checkMaxSize(dataImage, self.properties))231 .done(function() {232 $.when(bizagi.util.media.getFileDataInfo(self.dataImage))233 .then(function(file) {234 self.fileProperties = file;235 if (bizagi.util.media.checkFileTypes(file, self.properties, extensions)) {236 // "new Blob" constructor is not supported in android version 4.2.2237 var version = bizagi.util.getAndroidVersion();238 if ((version && version <= 4.2) || isOfflineForm) {239 self.saveImage(self, self.dataImage);240 self.closeModalView();241 } else {242 // Force click to show actionsheet menu243 $(".bz-resolution-container", self.getControl()).click();244 }245 }246 });247 });248 }, self.onFail.bind(self), options);249 break;250 case "file":251 bizagi.showMessageBox("In development", "Error");252 break;253 case "cimage":254 navigator.camera.getPicture(function(dataImage) {255 $.when(bizagi.util.media.checkMaxSize(dataImage, self.properties)).done(function() {256 $.when(bizagi.util.media.getFileDataInfo(dataImage)).then(function(file) {257 self.fileProperties = file;258 self.saveImage(self, dataImage);259 });260 }).always(function() {261 self.closeModalView();262 });263 }, self.onFail.bind(self), {264 quality: self.Class.QUALITY_PICTURE,265 targetWidth: 1280,266 targetHeight: 960267 });268 break;269 case "caudio":270 navigator.device.capture.captureAudio(function(dataImage) {271 self.saveAudio(self, dataImage);272 }, self.onFail.bind(self), { limit: self.Class.LIMIT });273 break;274 case "cvideo":275 navigator.device.capture.captureVideo(function(dataImage) {276 bizagi.util.tablet.startLoading();277 $.when(bizagi.util.media.checkMaxSizeVideo(dataImage, self.properties)).done(function() {278 self.saveVideo(self, dataImage);279 }).always(function() {280 self.closeModalView();281 bizagi.util.tablet.stopLoading();282 });283 }, self.onFail.bind(self), { limit: self.Class.LIMIT });284 break;285 default:286 break;287 }288 },289 closeModalView: function() {290 var self = this;291 var modalView = self.listOptions.closest("#modalview-upload-options");292 if (self.listOptions && modalView) {293 if (modalView.data("kendoMobileModalView")) {294 modalView.data("kendoMobileModalView").close();295 }296 }297 },298 resolutionButtonHandler: function(ordinal) {299 var self = this;300 var defer = new $.Deferred();301 var actionSelected = ordinal || 0;302 bizagi.util.tablet.startLoading();303 // If original, save image normally, if not, reduce quality and size304 if (actionSelected === 4) {305 self.saveImage(self, self.dataImage);306 defer.resolve();307 } else {308 var resolution = bizagi.util.media.getImageResolution(actionSelected);309 $.when(self.transformImageSize(self.dataImage, resolution.width, resolution.height))310 .done(function() {311 self.saveImage(self, self.dataImage);312 }).fail(function() {313 bizagi.util.tablet.stopLoading();314 }).always(function() {315 defer.resolve();316 });317 }318 $(".ui-bizagi-resolution-container").css("display", "none");319 $(".ui-bizagi-mask").remove();320 return defer.promise();321 },322 renderUploadItem: function(file) {323 var self = this;324 var properties = self.properties;325 var mode = self.getMode();326 var template = self.renderFactory.getTemplate("uploadItem");327 // Don't render urls when not running in execution mode328 var url = mode !== "execution" ? "javascript:void(0);" : self.buildItemUrl(file);329 var html = $.fasttmpl(template, {330 url: url,331 image: false,332 allowDelete: properties.allowDelete,333 editable: properties.editable,334 filename: file.fileName,335 id: file.id,336 mode: mode,337 isNativeContext: bizagi.util.isNativePluginSupported(),338 isCordovaSupported: bizagi.util.isCordovaSupported()339 });340 return html;341 },342 getTemplateName: function() {343 return "upload";344 },345 getTemplateItemName: function() {346 return "uploadItem";347 },348 getTemplateEditionName: function() {349 return "edition.upload";350 },351 getTemplateEditionMenu: function() {352 return "edition.upload.menu";353 },354 saveImage: function(context, dataImage) {355 var self = context;356 var params = {357 dataFile: dataImage,358 data: self.buildAddParams(),359 options: new FileUploadOptions(),360 properties: self.properties,361 extensions: self.Class.EXTENSIONSIMG.concat(self.Class.EXTENSIONSFILE, self.Class.EXTENSIONSAUDIO, self362 .Class.EXTENSIONSVIDEO)363 };364 params.data.queueID = "q_" + bizagi.util.encodeXpath(self.getUploadXpath());365 params.options.fileKey = "file";366 params.options.fileName = self.fileProperties.name;367 params.options.mimeType = "image/jpeg";368 params.options.params = params.data;369 if (self.editedImageURL) {370 params.dataFile = self.editedImageURL;371 self.editedImageURL = null;372 } else {373 params.dataFile = self.fileProperties.url;374 }375 // Fix android 4.4 getting images from recent folder 376 params.dataFile = bizagi.util.media.getImagePath(params.dataFile);377 $.when(bizagi.util.media.uploadFile(params)).done(function(r) {378 var response = JSON.parse(decodeURIComponent(r.response));379 if (response.type === "error") {380 bizagi.showMessageBox(response.message, response.errorType);381 bizagiLoader().stop();382 } else {383 self.onUploadFileCompleted(context, response);384 }385 }).fail(function(error) {386 var response = JSON.parse(decodeURIComponent(error.responseText));387 bizagi.showMessageBox(response.message, response.type);388 }).always(function() {389 self.closeModalView();390 bizagiLoader().stop();391 });392 },393 saveAudio: function(context, dataAudio) {394 var self = context;395 var params = {396 data: self.buildAddParams(),397 options: new FileUploadOptions(),398 properties: self.properties399 };400 params.data.queueID = "q_" + bizagi.util.encodeXpath(self.getUploadXpath());401 params.options.fileName = dataAudio[0].name;402 params.options.params = params.data;403 params.dataFile = dataAudio[0].fullPath;404 $.when(bizagi.util.media.uploadFile(params)).done(function(r) {405 var response = JSON.parse(decodeURIComponent(r.response));406 if (response.type === "error") {407 bizagi.showMessageBox(response.message, response.errorType);408 } else {409 self.onUploadFileCompleted(context, response);410 }411 }).fail(function(error) {412 }).always(function() {413 self.closeModalView();414 bizagiLoader().stop();415 });416 },417 saveVideo: function(context, dataVideo) {418 var self = context;419 var params = {420 data: self.buildAddParams(),421 options: new FileUploadOptions(),422 properties: self.properties423 };424 params.data.queueID = "q_" + bizagi.util.encodeXpath(self.getUploadXpath());425 params.options.fileName = dataVideo[0].name;426 params.options.mimeType = "video/quicktime";427 params.options.params = params.data;428 params.dataFile = dataVideo[0].fullPath;429 $.when(bizagi.util.media.uploadFile(params)).done(function(r) {430 var response = JSON.parse(decodeURIComponent(r.response));431 if (response.type === "error") {432 bizagi.showMessageBox(response.message, response.errorType);433 } else {434 self.onUploadFileCompleted(context, response);435 }436 }).fail(function(error) {437 }).always(function() {438 self.closeModalView();439 bizagiLoader().stop();440 });441 },442 onFail: function(error) {443 bizagi.log("Error: " + error.code);444 var messageError = bizagi.util.processFailMessage(error);445 var message;446 if (messageError.indexOf("No Activity found to handle Intent") !== -1) {447 message = bizagi.util.isValidResource("render-upload-error-media-app") ? bizagi.localization448 .getResource("render-upload-error-media-app")449 : "Your device does not have an app to execute this action.";450 bizagi.showMessageBox(message);451 }452 },453 onUploadFileCompleted: function(context, response) {454 var self = context;455 var control = self.getControl();456 var uploadWrapper = $("ul.files", control);457 var result = response;458 var properties = self.properties;459 if (result.id && result.fileName) {460 // Locate it before the upload wrapper461 var newItem = self.renderUploadItem(result);462 $(uploadWrapper).append(newItem);463 // Increment counter464 self.filesCount = self.filesCount + 1;465 // Copy the files value but not its reference466 var files = self.files.slice();467 //Add the new item to this temporal array468 files.push([result.id, result.fileName]);469 // Update value470 self.setValue(files, false);471 // Check maxFiles472 self.checkMaxFiles();473 // Trigger change474 self.triggerRenderChange();475 control.find(".ui-bizagi-render-upload-item-no-upload").hide();476 if (self.properties.type === "columnUpload") {477 // Refresh to have synchronized the file between sever and client478 bizagiLoader().stop();479 self.getFormContainer().saveForm();480 self.getFormContainer().refreshForm();481 } else {482 if (properties.allowDelete && properties.editable) {483 self.attachDeleteHandler();484 }485 }486 self.editedImageURL = null;487 bizagiLoader().stop();488 } else {489 bizagi.log("Error:" + result.message);490 bizagi.showMessageBox(result.message, "Error");491 }492 },493 saveBlobToFile: function(blob, defer) {494 // root file system entry495 var self = this;496 var newId = "bizagiImgTmp";497 var fileExtension = ".jpg";498 // root file system entry499 window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,500 function(fileSystem) {501 var root = fileSystem.root;502 // writes a file503 var writeFile = function(writer) {504 writer.onwriteend = function(e) {505 self.editedImageURL = writer.localURL;506 defer.resolve();507 };508 writer.onerror = function(e) {509 //bizagi.log("Write failed: " + e.toString());510 };511 // write to file512 writer.write(blob);513 };514 // creates a FileWriter object515 var createWriter = function(fileEntry) {516 fileEntry.createWriter(writeFile, null);517 };518 // create a file and write to it519 root.getFile(newId + fileExtension, { create: true }, createWriter, null);520 },521 function() {522 });523 },524 /**525 * Change image size526 * @param {} objectUri527 * @param {} objWidth528 * @param {} objHeight529 * @returns {}530 */531 transformImageSize: function(objectUri, objWidth, objHeight) {532 var self = this;533 var defer = new $.Deferred();534 window.resolveLocalFileSystemURL(objectUri, function(fileEntry) {535 fileEntry.file(function(fileObj) {536 var reader = new FileReader();537 // Create a function to process the file once it's read538 reader.onloadend = function(evt) {539 // Create an image element that we will load the data into540 var image = new Image();541 image.onload = function(evt) {542 var width = image.width;543 var height = image.height;544 if (objWidth !== 0) {545 if (width > height) {546 if (width > objWidth) {547 height *= objWidth / width;548 width = objWidth;549 }550 } else {551 if (height > objHeight) {552 width *= objHeight / height;553 height = objHeight;554 }555 }556 }557 var canvas = document.createElement("canvas");558 canvas.width = width;559 canvas.height = height;560 canvas.getContext("2d").drawImage(this, 0, 0, width, height);561 self.properties.url = canvas.toDataURL("image/jpeg", 0.5);562 var imageToSaveLocal = self.properties.url.replace("data:image/jpeg;base64,", "");563 var imageBlob = bizagi.util.b64toBlob(imageToSaveLocal);564 self.saveBlobToFile(imageBlob, defer);565 image = null;566 };567 // Load the read data into the image source. It's base64 data568 image.src = bizagi.util.media.getImagePath(objectUri);569 };570 // Read from disk the data as base64571 reader.readAsDataURL(fileObj);572 });573 });574 return defer.promise();575 },576 /**577 * Checks if the total files uploaded reachs the maximun supported578 * @returns {}579 */580 checkMaxFiles: function() {581 var self = this;582 var properties = self.properties;583 var maxFiles = properties.maxfiles;584 var actualFiles = properties.value ? properties.value.length : 0;585 if (maxFiles !== 0 && ((self.filesCount >= maxFiles && actualFiles >= maxFiles))) {586 self.itemAddfile.hide();587 } else {588 self.itemAddfile.show();589 }590 },591 /**592 * Checks the file Extension in each filetype that the device supports593 * @returns {}594 */595 checkExtensions: function() {596 var self = this;597 var properties = self.properties;598 var validExtensions = properties.validExtensions;599 validExtensions = validExtensions.split(";");600 self.validOptions = {601 audio: false,602 video: false,603 image: false,604 file: false605 };606 if (typeof (validExtensions) === "undefined" || validExtensions[0] == "") {607 self.validOptions = {608 audio: true,609 video: true,610 image: true,611 file: false612 };613 return;614 }615 if (validExtensions.length === 1 && validExtensions[0].indexOf("*.*") !== -1) {616 return;617 }618 var i = validExtensions.length;619 while(i-- > 0) {620 validExtensions[i] = validExtensions[i].replace("*.", "");621 if (self.Class.EXTENSIONSIMG.toString().indexOf(validExtensions[i]) > 0 && !self.validOptions.image) {622 self.validOptions.image = true;623 } else if (self.Class.EXTENSIONSAUDIO.toString().indexOf(validExtensions[i]) > 0 && !self.validOptions.audio) {624 self.validOptions.audio = true;625 } else if (self.Class.EXTENSIONSVIDEO.toString().indexOf(validExtensions[i]) > 0 && !self.validOptions.video) {626 self.validOptions.video = true;627 }628 }629 },630 /**631 * Active upload web control632 * @returns {}633 */634 activeUploadWebControl: function() {635 var self = this;636 var container = self.getControl();637 var uploadfile = $(".bz-rn-upload-web", container);638 var file = $(".bz-rn-upload-show-menu span.bz-cm-icon", container);639 self.itemAddfile = $(".bz-rn-upload-show-menu", container);640 // Check maximum files number641 if (self.itIsMaxNumberFilesReached()) {642 self.itemAddfile.hide();643 }644 self.itemAddfile.click(function(){645 uploadfile.click();646 });647 // attach events to file-icon648 file.addClass("bz-rn-upload-native");649 file.on("click", function() {650 uploadfile.click();651 });652 // Attach event to upload-control653 uploadfile.on("change", function() {654 var that = this;655 var dataFile = that.files[0];656 var extensions = self.Class.EXTENSIONSIMG.concat(self.Class.EXTENSIONSFILE, self.Class.EXTENSIONSAUDIO, self657 .Class.EXTENSIONSVIDEO);658 bizagiLoader().start();659 dataFile.fullPath = that.value;660 if (bizagi.util.media.checkMaxSizeFile(dataFile, self.properties)661 && bizagi.util.media.checkFileTypes(dataFile, self.properties, extensions)) {662 $.when(self.processUploadFile(dataFile)).done(function(result) {663 self.onUploadFileCompleted(self, JSON.parse(decodeURIComponent(result)));664 bizagiLoader().stop();665 }).fail(function(error) {666 bizagiLoader().stop();667 if (error.statusText !== "Unauthorized") {668 bizagi.showMessageBox(self.getResource("workportal-widget-admin-language-error"));669 }670 });671 } else {672 bizagiLoader().stop();673 }674 // Clearing input Values675 $(that).val("");676 });677 // Check files number678 self.checkMaxFiles();679 // Attach delete option680 self.attachDeleteHandler();681 },682 /**683 * Check the maximun file than can be uploaded684 * @returns {}685 */686 itIsMaxNumberFilesReached: function() {687 var self = this;688 var properties = self.properties;689 var maxFiles = properties.maxfiles;690 var actualFiles = properties.value ? properties.value.length : 0;691 return maxFiles !== 0 && (actualFiles >= maxFiles);692 },693 /**694 * Build add params to send to the server695 * @param {} dataFile696 * @returns {}697 */698 buildAddFileParams: function(dataFile) {699 var self = this;700 var properties = self.properties;701 // Get form data for POSTing702 var formData = new FormData();703 var form = self.getFormContainer();704 // Build add params to send to the server705 formData.append(self.Class.BA_CONTEXT_PARAMETER_PREFIX + "xpath", self.getUploadXpath());706 formData.append(self.Class.BA_CONTEXT_PARAMETER_PREFIX + "idRender", properties.id);707 formData.append(self.Class.BA_CONTEXT_PARAMETER_PREFIX + "xpathContext", properties.xpathContext);708 formData.append(self.Class.BA_CONTEXT_PARAMETER_PREFIX + self.Class.BA_PAGE_CACHE, properties.idPageCache);709 formData.append(self.Class.BA_ACTION_PARAMETER_PREFIX + "sessionId", form.properties.sessionId);710 formData.append(properties.xpath, dataFile);711 if (properties.contexttype) {712 formData.append(self.Class.BA_CONTEXT_PARAMETER_PREFIX + "contexttype", properties.contexttype);713 }714 try {715 if (typeof (BIZAGI_SESSION_NAME) !== "undefined") {716 formData.append(BIZAGI_SESSION_NAME, form.properties.sessionId);717 } else {718 formData.append("JSESSIONID", form.properties.sessionId);719 }720 } catch (e) {721 formData.append("JSESSIONID", form.properties.sessionId);722 }723 return formData;724 },725 /**726 * Process an upload file into the server727 * @param {} context728 * @param {} dataFile729 * @returns {}730 */731 processUploadFile: function(dataFile) {732 var self = this;733 return self.dataService.processUploadFile({734 url: self.properties.addUrl,735 formData: self.buildAddFileParams(dataFile)736 });737 },738 clearDisplayValue: function(){739 var self = this;740 var items = $(".ui-bizagi-render-upload-item", self.getControl());741 items.each(function(index, item){742 item = $(item);743 var file = item.data();744 $.when(self.deleteUploadItem(item, file.id)).done(function () {745 // Remove item746 item.hide();747 item.remove();748 // Update value749 self.setValue(self.files, false);750 // Check maxFiles751 self.checkMaxFiles();752 // Trigger change753 self.triggerRenderChange();754 });755 })756 }...

Full Screen

Full Screen

context.js

Source:context.js Github

copy

Full Screen

...100 // already in the named context, no need to do anything101 log.debug(`Already in '${name || NATIVE_WIN}' context. Doing nothing.`);102 return;103 }104 if (isNativeContext(name)) {105 // switching into the native context106 this.curContext = null;107 return;108 }109 // switching into a webview context110 // if contexts have not already been retrieved, get them111 if (_.isUndefined(this.contexts)) {112 await this.getContexts();113 }114 let contextId = _.replace(name, WEBVIEW_BASE, '');115 if (contextId === '') {116 // allow user to pass in "WEBVIEW" without an index117 // the second context will be the first webview as118 // the first is always NATIVE_APP...

Full Screen

Full Screen

bizagi.rendering.tablet.upload.offline.js

Source:bizagi.rendering.tablet.upload.offline.js Github

copy

Full Screen

1/*2* Name: BizAgi Tablet Render upload Extension3* Author: Bizagi Mobile Team4* Comments:5* - This script will redefine the label render class to adjust to smartphones devices6*/7// Extends itself8bizagi.rendering.upload.extend("bizagi.rendering.upload.offline", {9 BA_ACTION_PARAMETER_PREFIX: bizagi.render.services.service.BA_ACTION_PARAMETER_PREFIX,10 BA_CONTEXT_PARAMETER_PREFIX: bizagi.render.services.service.BA_CONTEXT_PARAMETER_PREFIX,11 QUALITY_PICTURE: 80,12 LIMIT: 1, //limit: The maximum number of audio clips,video clips, etc. 13 // in the device user can record in a single capture operation.14 EXTENSIONSIMG: ["image/jpeg", "jpeg", "image", "png", "jpg"],15 EXTENSIONSVIDEO: ["video/quicktime", "quicktime", "qt", "mov"],16 EXTENSIONSAUDIO: ["audio/wav", "audio", "wav"]17}, {18 postRender: function() {19 var self = this;20 var properties = self.properties;21 if (!bizagi.util.isCordovaSupported() || !properties.editable) {22 self.addEventToOpenSlide();23 } else {24 self.activateUploadNative();25 }26 // Attach Events27 self.configureHelpText();28 },29 /**30 * Attach open slide31 * @returns {} 32 */33 addEventToOpenSlide: function() {34 var self = this;35 var container = self.getControl();36 self.itemAddfile = $(".bz-rn-upload-show-menu", container);37 self.itemAddfile.hide();38 },39 /** 40 * Template method to implement in each children to customize each control41 * @returns {} 42 */43 renderControl: function() {44 var self = this;45 var properties = self.properties;46 var template = self.renderFactory.getTemplate("upload");47 // Render template48 var html = $.fasttmpl(template, {49 xpath: bizagi.util.encodeXpath(self.getUploadXpath()),50 editable: properties.editable,51 noFiles: (self.filesCount === 0),52 allowSendInMail: properties.allowSendInMail53 });54 // Render current children55 var items = "";56 for (var i = 0; i < self.filesCount; i++) {57 var item = self.renderUploadItem(self.files[i]);58 items += item;59 }60 html = self.replaceFilesHtml(html, items);61 return html;62 },63 /**64 * Render readonly65 * @returns {} 66 */67 postRenderReadOnly: function() {68 var self = this;69 self._super();70 },71 /**72 * Active upload by native mode73 * @returns {} 74 */75 activateUploadNative: function() {76 var self = this;77 self._super();78 },79 getTemplateName: function() {80 return "upload";81 },82 getTemplateItemName: function() {83 return "uploadItem";84 },85 getTemplateEditionName: function() {86 return "edition.upload";87 },88 getTemplateEditionMenu: function() {89 return "edition.upload.menu";90 },91 saveImage: function(context, dataImage) {92 var self = context;93 // Fix android 4.4 getting images from recent folder 94 dataImage = bizagi.util.media.getImagePath(dataImage);95 // Load image96 self.getDataUri(dataImage, function(dataUrl) {97 if (bizagi.util.isEmpty(self.fileExtension)) {98 self.fileExtension = bizagi.util.media.getFileExtension(dataImage);99 }100 var fileName = bizagi.util.uniqueID() + self.fileExtension;101 self.fileExtension = null;102 self.onUploadFileCompletedOffline(fileName, dataUrl);103 });104 },105 /**106 * Create an offline image107 * @param {} context 108 * @param {} url 109 * @param {} callback 110 * @returns {} 111 */112 getDataUri: function(url, callback) {113 var image = new Image();114 $(image).on("load", function() {115 var canvas = document.createElement("canvas");116 canvas.width = this.width;117 canvas.height = this.height;118 canvas.getContext("2d").drawImage(this, 0, 0);119 // Get raw image data120 var dataUrl = canvas.toDataURL("image/png");121 callback(dataUrl.replace(/^data:image\/(png|jpg|jpeg);base64,/, ""));122 });123 image.src = url;124 },125 saveAudio: function(context, dataAudio) {126 var self = context;127 window.resolveLocalFileSystemURI(dataAudio[0].fullPath, function(fileEntry) {128 fileEntry.file(function(file) {129 var reader = new FileReader();130 reader.onloadend = function(evt) {131 var fileExtension = bizagi.util.media.getFileExtension(dataAudio[0].name);132 var fileName = bizagi.util.uniqueID() + fileExtension;133 self.onUploadFileCompletedOffline(fileName, evt.target.result);134 };135 reader.readAsDataURL(file);136 }, self.failReadFile);137 }, self.failReadFile);138 },139 saveVideo: function(context, dataVideo) {140 var self = context;141 window.resolveLocalFileSystemURI(dataVideo[0].fullPath, function(fileEntry) {142 fileEntry.file(function(file) {143 var reader = new FileReader();144 reader.onloadend = function(evt) {145 var fileExtension = bizagi.util.media.getFileExtension(dataVideo[0].name);146 var fileName = bizagi.util.uniqueID() + fileExtension;147 self.onUploadFileCompletedOffline(fileName, evt.target.result);148 };149 reader.readAsDataURL(file);150 }, self.failReadFile);151 }, self.failReadFile);152 },153 renderUploadItem: function(objectUpload) {154 var self = this;155 var properties = self.properties;156 var mode = self.getMode();157 var template = self.renderFactory.getTemplate("uploadItem");158 var html = $.fasttmpl(template, {159 url: "javascript:void(0);",160 image: false,161 allowDelete: properties.allowDelete || false,162 id: bizagi.util.randomNumber(),163 mode: mode,164 editable: properties.editable,165 filename: objectUpload[0].value,166 isNativeContext: false,167 isOfflineForm: true,168 isCordovaSupported: bizagi.util.isCordovaSupported()169 });170 return html;171 },172 /**173 * Collect Data174 * @param {} renderValues 175 * @returns {} 176 */177 collectData: function(renderValues) {178 var self = this;179 if (self.filesCount > 0) {180 renderValues[self.properties.xpath] = self.files;181 } else if (self.properties.method === "delete") {182 renderValues[self.properties.xpath] = [];183 delete self.properties.method;184 }185 },186 onUploadFileCompletedOffline: function(name, dataimage) {187 var self = this;188 var control = self.getControl();189 var uploadWrapper = $(".bz-rn-upload-show-menu", control);190 var dataUrltoSave = dataimage.replace(/^data:.*;base64,/, "");191 var properties = self.properties;192 var fileToSave = [193 { xpath: "fileName", DataType: "15", value: name },194 { xpath: "data", DataType: "19", value: dataUrltoSave }195 ];196 // Locate it before the upload wrapper197 var newItem = self.renderUploadItem(fileToSave);198 $(newItem).insertBefore(uploadWrapper);199 // Copy the files value but not its reference200 var files = self.files.slice();201 //Add the new item to this temporal array202 files.push(fileToSave);203 // Increment counter204 self.filesCount = self.filesCount + 1;205 // Update value206 self.setValue(files, false);207 // Check maxFiles208 self.checkMaxFiles();209 self.triggerRenderChange();210 control.find(".ui-bizagi-render-upload-item-no-upload").hide();211 if (properties.allowDelete && properties.editable) {212 self.attachDeleteHandler();213 }214 // Close modalview215 self.closeModalView();216 bizagi.util.tablet.stopLoading();217 },218 failReadFile: function(evt) {219 try {220 bizagi.log("Error code: " + evt.target.error.code);221 } catch (e) {222 }223 },224 onFail: function(error) {225 this._super(error);226 this.closeModalView();227 },228 checkMaxFiles: function() {229 bizagi.rendering.upload.prototype.checkMaxFiles.apply(this, arguments);230 },231 checkExtensions: function() {232 bizagi.rendering.upload.prototype.checkExtensions.apply(this, arguments);233 },234 checkMaxSize: function(objectUri) {235 var self = this;236 return bizagi.util.media.checkMaxSize(objectUri, self.properties);237 },238 checkMaxSizeVideo: function(objectVideo) {239 var self = this;240 return bizagi.util.media.checkMaxSizeVideo.apply(objectVideo, self.properties);241 },242 /** 243 * This render cannot be sent because it is full ajax244 * @returns {} 245 */246 canBeSent: function() {247 return true;248 },249 /**250 * Attach delete option & Removes a file from the upload control251 * @returns {} 252 */253 attachDeleteHandler: function() {254 var self = this;255 var control = self.getControl();256 $(".bz-rn-upload-delete-icon", control).bind("click", function() {257 var context = $(this);258 var item = context.parent(".ui-bizagi-render-upload-item");259 var file = item.data();260 var fileIndex = item.index();261 // Substract counter262 self.filesCount = self.filesCount - 1;263 if (self.filesCount === 0) {264 self.properties.method = "delete";265 }266 // Remove from local collection267 self.files = $.grep(self.files, function(fileItem, index) {268 return (index !== fileIndex && fileItem !== file.name);269 });270 // Remove item271 item.hide();272 item.remove();273 // Update value274 self.setValue(self.files, false);275 // Check maxFiles276 self.checkMaxFiles();277 // Trigger change278 self.triggerRenderChange();279 });280 }...

Full Screen

Full Screen

nativebridge.js

Source:nativebridge.js Github

copy

Full Screen

1export const nativebridge = function(){2 if(window.nativemainapp != undefined){3 return window.nativemainapp.nativebridge4 }5 const BRIDGE_VERSION = "0.0.0"6 const COMMANDS = {7 REQUEST_LOGIN:"login",8 REQUEST_VERSION:"version",9 TEST_CONNECTIVITY:"test",10 TEST_ERROR:"testError"11 }12 13 const LEGACY_COMMANDS = {14 WEBAPP_READY_ACTION_URL = 'ntmsg://webapp_booted',15 CLOSE_ACTION_URL = 'norsktippingmainapp://back_from_webapp',16 LOGIN_ACTION_URL = 'ntmsg://request_native_log_in'17 }18 19 const ERRORS = {20 NOT_NATIVE_CONTEXT:"The application is not running in a native context",21 NOT_NATIVE_BRIDGE:"The current application dos not support nativebridge commands"22 23 }24 let isAppNativeBridgeEnabled = (() =>{25 //TODO: HVa med android?26 return window.webkit.messageHandlers.nativebridge != undefined27 })();28 let isNativeContext = (() =>{29 //TODO: Dette er ikke riktig test for dettte, trengs å utvides. 30 return window.webkit.messageHandlers.nativebridge != undefined31 })();32 33 let createHandlerId = () => { return `h_${Date.now()}${(Math.random() + 1).toString(36).substring(4)}`};34 let handlers = {}35 let appInterface = window.webkit.messageHandlers.nativebridge;36 var appVersion = null;37 var token = null;38 const bridge = {39 "version":BRIDGE_VERSION,40 // When the native app successfully completes a request.41 "onResponse":(handlerId, data)=>{42 let handle = handlers[handlerId];43 handle.resolve(data);44 delete handlers[handlerId];45 },46 47 // When the native app is unable for what ever reason to complete a request.48 "onError":(handlerId, err)=>{49 let handle = handlers[handlerId];50 handle.reject(new Error(err));51 delete handlers[handlerId];52 },53 "app_version":() =>{ //nativebridge only 54 if(isNativeContext){55 if(appVersion){ return appVersion} // Version number is known.56 // Se if we can get the version number from the url search string57 let params = new URLSearchParams(window.location.search)58 let version = params.has("version") ? params.get("version"):null59 if(version){60 appVersion = version;61 return Promise.resolve(version);62 } else if(isAppNativeBridgeEnabled){63 //We ask the app to provide the version number64 return new Promise((resolve,reject) =>{65 const handle = createHandlerId()66 handlers[handle] = {resolve, reject}67 appInterface.postMessage(JSON.stringify({callback:handle, cmd:COMMANDS.REQUEST_VERSION}))68 })69 }70 } 71 72 return Promise.reject(new Error(ERRORS.NOT_NATIVE_BRIDGE));73 },74 "isNativeContext": isAppNativeBridgeEnabled,75 "test":() =>{ //nativebridge only 76 if(isAppNativeBridgeEnabled){77 return new Promise((resolve,reject) =>{78 const handle = createHandlerId()79 handlers[handle] = {resolve, reject}80 appInterface.postMessage(JSON.stringify({callback:handle, cmd:COMMANDS.TEST_CONNECTIVITY}))81 })82 }83 return Promise.reject(new Error(ERRORS.NOT_NATIVE_BRIDGE));84 },85 "testErr":() =>{ //nativebridge only 86 if(isAppNativeBridgeEnabled){87 return new Promise((resolve,reject) =>{88 const handle = createHandlerId()89 handlers[handle] = {resolve, reject}90 appInterface.postMessage(JSON.stringify({callback:handle, cmd:COMMANDS.TEST_ERROR}))91 })92 }93 return Promise.reject(new Error(ERRORS.NOT_NATIVE_BRIDGE));94 },95 "requestLogin":() =>{96 if(isAppNativeBridgeEnabled){97 return new Promise((resolve,reject) =>{98 const handle = createHandlerId()99 handlers[handle] = {resolve, reject}100 appInterface.postMessage(JSON.stringify({callback:handle, cmd:COMMANDS.LOGIN}))101 })102 } else if(isNativeContext && window){103 window.location.href = LEGACY_COMMANDS.LOGIN_ACTION_URL;104 }105 return new Promise().resolve(null)106 },107 "signalReadyState":() =>{108 if(isNativeContext && window){109 window.location.href = LEGACY_COMMANDS.WEBAPP_READY_ACTION_URL;110 }111 },112 "leaveWebApp":() => {113 if(isNativeContext && window){114 window.location.href = CLOSE_ACTION_URL115 }116 }117 }118 window.nativemainapp={nativebridge : bridge}119 return bridge...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const wd = require('wd');2const chai = require('chai');3const chaiAsPromised = require('chai-as-promised');4chai.use(chaiAsPromised);5chai.should();6chaiAsPromised.transferPromiseness = wd.transferPromiseness;7const desired = {

Full Screen

Using AI Code Generation

copy

Full Screen

1const XCUITestDriver = require('appium-xcuitest-driver');2const isNativeContext = XCUITestDriver.prototype.isNativeContext;3console.log(isNativeContext);4const XCUITestDriver = require('appium-xcuitest-driver');5const isNativeContext = XCUITestDriver.prototype.isNativeContext;6console.log(isNativeContext);7const XCUITestDriver = require('appium-xcuitest-driver');8const isNativeContext = XCUITestDriver.prototype.isNativeContext;9console.log(isNativeContext);10const XCUITestDriver = require('appium-xcuitest-driver');11const isNativeContext = XCUITestDriver.prototype.isNativeContext;12console.log(isNativeContext);13const XCUITestDriver = require('appium-xcuitest-driver');14const isNativeContext = XCUITestDriver.prototype.isNativeContext;15console.log(isNativeContext);16const XCUITestDriver = require('appium-xcuitest-driver');17const isNativeContext = XCUITestDriver.prototype.isNativeContext;18console.log(isNativeContext);19const XCUITestDriver = require('appium-xcuitest-driver');20const isNativeContext = XCUITestDriver.prototype.isNativeContext;21console.log(isNativeContext);

Full Screen

Using AI Code Generation

copy

Full Screen

1const wd = require('wd');2const assert = require('assert');3const path = require('path');4const { AppiumServer } = require('appium-fake-driver');5const { XCUITestDriver } = require('appium-xcuitest-driver');6const PORT = 4723;

Full Screen

Using AI Code Generation

copy

Full Screen

1driver.init({platformName: 'iOS', platformVersion: '10.3', deviceName: 'iPhone 7', app: 'path to app', automationName: 'XCUITest'});2driver.isNativeContext().then(function(isNative) {3});4driver.quit();5driver.isNativeContext().then(function(isNative) {6});7driver.quit();8driver.isNativeContext().then(function(isNative) {9});10driver.quit();11driver.isNativeContext().then(function(isNative) {12});13driver.quit();14driver.isNativeContext().then(function(isNative) {15});16driver.quit();17driver.isNativeContext().then(function(isNative) {18});19driver.quit();20driver.isNativeContext().then(function(isNative) {21});22driver.quit();23driver.isNativeContext().then(function(isNative) {24});25driver.quit();26driver.isNativeContext().then(function(isNative) {27});28driver.quit();29driver.isNativeContext().then(function(isNative) {30});31driver.quit();32driver.isNativeContext().then(function(isNative) {33});34driver.quit();35driver.isNativeContext().then(function(isNative) {36});37driver.quit();38driver.isNativeContext().then(function(isNative) {39});40driver.quit();41driver.isNativeContext().then(function(isNative) {42});43driver.quit();44driver.isNativeContext().then(function(isNative) {45});46driver.quit();47driver.isNativeContext().then(function(isNative) {48});49driver.quit();50driver.isNativeContext().then(function(isNative) {51});52driver.quit();53driver.isNativeContext().then(function(isNative) {

Full Screen

Using AI Code Generation

copy

Full Screen

1var appium = require('appium');2var XCUITestDriver = appium.XCUITestDriver;3var driver = new XCUITestDriver();4driver.isNativeContext();5var appium = require('appium');6var XCUITestDriver = appium.XCUITestDriver;7var driver = new XCUITestDriver();8driver.isNativeContext();9var appium = require('appium');10var XCUITestDriver = appium.XCUITestDriver;11var driver = new XCUITestDriver();12driver.isNativeContext();

Full Screen

Using AI Code Generation

copy

Full Screen

1var appium = require('appium');2var driver = appium.XCUITestDriver;3var isNativeContext = driver.isNativeContext;4console.log(isNativeContext);5var appium = require('appium');6var driver = appium.XCUITestDriver;7var isNativeContext = driver.isNativeContext;8console.log(isNativeContext);9var appium = require('appium');10var driver = appium.XCUITestDriver;11var isNativeContext = driver.isNativeContext;12console.log(isNativeContext);13var appium = require('appium');14var driver = appium.XCUITestDriver;15var isNativeContext = driver.isNativeContext;16console.log(isNativeContext);17var appium = require('appium');18var driver = appium.XCUITestDriver;19var isNativeContext = driver.isNativeContext;20console.log(isNativeContext);21var appium = require('appium');22var driver = appium.XCUITestDriver;23var isNativeContext = driver.isNativeContext;24console.log(isNativeContext);25var appium = require('appium');26var driver = appium.XCUITestDriver;27var isNativeContext = driver.isNativeContext;28console.log(isNativeContext);29var appium = require('appium');30var driver = appium.XCUITestDriver;31var isNativeContext = driver.isNativeContext;32console.log(isNativeContext);33var appium = require('appium');34var driver = appium.XCUITestDriver;35var isNativeContext = driver.isNativeContext;36console.log(isNativeContext);37var appium = require('appium');38var driver = appium.XCUITestDriver;

Full Screen

Using AI Code Generation

copy

Full Screen

1const wd = require('wd');2const { AppiumDriver, AppiumServiceBuilder } = require('appium');3const { startServer } = require('appium-fake-driver');4const fakeDriver = startServer({5});6const service = new AppiumServiceBuilder()7 .withAppiumJS(fakeDriver.appiumPath)8 .withLogFile('/tmp/appium.log')9 .build();10service.start();11const driver = wd.promiseChainRemote('localhost', 4723);12driver.init({13}).then(function () {14 return driver.execute('mobile: isNativeContext');15}).then(function (isNativeContext) {16 console.log('isNativeContext', isNativeContext);17}).finally(function () {18 driver.quit();19 service.stop();20 fakeDriver.stop();21});

Full Screen

Using AI Code Generation

copy

Full Screen

1var isNativeContext = await driver.isNativeContext();2console.log(isNativeContext);3it('should return true if native context', async function () {4 await driver.isNativeContext().should.eventually.be.true;5});6it('should return false if webview context', async function () {7 await driver.isWebviewContext().should.eventually.be.true;8});9it('should return false if webview context', async function () {10 await driver.isWebviewContext().should.eventually.be.false;11});12it('should return true if native context', async function () {13 await driver.isNativeContext().should.eventually.be.true;14});15it('should return false if webview context', async function () {16 await driver.isWebviewContext().should.eventually.be.false;17});18it('should return true if native context', async function () {19 await driver.isNativeContext().should.eventually.be.true;20});21it('should return false if webview context', async function () {22 await driver.isWebviewContext().should.eventually.be.false;23});24it('should return false if webview context', async function () {25 await driver.isWebviewContext().should.eventually.be.false;26});27it('should return true if native context', async function () {28 await driver.isNativeContext().should.eventually.be.true;29});30it('should return false if webview context', async function () {31 await driver.isWebviewContext().should.eventually.be.false;32});33it('should return true if native context', async function () {34 await driver.isNativeContext().should.eventually.be.true;35});36it('should return false if webview context', async function () {37 await driver.isWebviewContext().should.eventually.be.false;38});39it('should return true if native context', async function () {40 await driver.isNativeContext().should.eventually.be.true;41});

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Appium Xcuitest Driver automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Sign up Free
_

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful