How to use convertHtmlToImage method in Cypress

Best JavaScript code snippet using cypress

Travel.js

Source:Travel.js Github

copy

Full Screen

...547                    valueWithoutFee: parseFloat((price - fee - planFee).toFixed(2))548                };549                let receipt = await _super.createReceiptHtml(travel, _fees, type === "driver", Messages(_language).receipt.file_html, offset);550                if (!receipt) return Promise.resolve();551                const url = await utils.convertHtmlToImage(receipt);552                if (!url) return Promise.resolve();553                if (type === "driver")554                    travel.set("receiptDriver", url);555                else556                    travel.set("receiptPassenger", url);557                await travel.save(null, {useMasterKey: true});558                return url;559            } catch (e) {560                return Promise.reject(e);561            }562        },563        refundTravelsCancelledBySystem: function () {564            return Promise.resolve();565            let query = new Parse.Query(Define.Travel);...

Full Screen

Full Screen

Utils.js

Source:Utils.js Github

copy

Full Screen

1const Define = require('./Define.js');2const Messages = require('./Locales/Messages.js');3const Mail = require('./mailTemplate.js');4const fs = require('fs');5const conf = require('config');6const pdf2png = require('pdf2png');7const html2pdf = require('html-pdf');8const os = require("os");9const crypto = require('crypto');10const iv = crypto.randomBytes(16);11const secretKey = "74F9969B759C644EF482829CD5C7EUNR";12const response = require('./response');13let Utils = {14    oldVersion: async (user) => {15        try {16            let appVersion;17            const deviceInfo = await Utils.findObject(Define.DeviceInfo, {user: user}, true, null, null, "updatedAt");18            if (deviceInfo && deviceInfo.get("manufacturer").toLowerCase() === "apple")19                return true;20            else {21                const userVersion = user.get("lastAppVersion");22                if (conf.appName.toLowerCase() === "cheguei") appVersion = 2022;23                else if (conf.appName.toLowerCase() === "flipmob") appVersion = 2024;24                else if (conf.appName.toLowerCase() === "mobdrive") appVersion = 2008;25                else if (conf.appName.toLowerCase() === "mova") appVersion = 4024;26                else if (conf.appName.toLowerCase() === "one") appVersion = 2016;27                else if (conf.appName.toLowerCase() === "022") appVersion = 2002;28                else if (conf.appName.toLowerCase() === "princessdriver") appVersion = 1056;29                else if (conf.appName.toLowerCase() === "upmobilidade") appVersion = 2018;30                else if (conf.appName.toLowerCase() === "yesgo") appVersion = 2030;31                else if (conf.appName.toLowerCase() === "uaimove") appVersion = 1048;32                else if (conf.appName.toLowerCase() === "ubx") appVersion = 1008;33                else if (conf.appName.toLowerCase() === "onecorporativo") appVersion = 2006;34                else if (conf.appName.toLowerCase() === "demodev" ||35                    conf.appName.toLowerCase() === "diuka" ||36                    conf.appName.toLowerCase() === "podd" ||37                    conf.appName.toLowerCase() === "escapp")38                    return false;39                else40                    return true;41                return userVersion < appVersion;42            }43        } catch (error) {44            console.log(error);45            return true;46        }47    },48    getMode: (array) => {49        let frequency = {}; // array of frequency.50        let maxFreq = 0; // holds the max frequency.51        let minFreq = 0; // holds the min frequency.52        let modes = [];53        for (let i in array) {54            frequency[array[i]] = (frequency[array[i]] || 0) + 1; // increment frequency.55            if (frequency[array[i]] > maxFreq) { // is this frequency > max so far ?56                maxFreq = frequency[array[i]]; // update max.57            }58            if (minFreq <= maxFreq - 1) { // is this frequency > max so far ?59                minFreq = maxFreq - 1; // update max.60            }61        }62        for (let k in frequency) {63            if (frequency[k] <= maxFreq && (frequency[k] >= minFreq)) {64                modes.push(k);65            }66        }67        return modes;68    },69    validateLocation: (location) => {70        try {71            if (!location || !location.latitude || !location.longitude)72                return false;73            return Utils.validateLatitude(location.latitude) && Utils.validateLongitude(location.longitude);74        } catch (e) {75            return false;76        }77    },78    validateLatitude: (lat) => {79        const regex = /^-?([1-8]?[1-9]|[1-9]0)\.{1}\d{1,15}/g;80        return regex.test(lat) && typeof lat === "number" && !isNaN(lat);81    },82    validateLongitude: (lng) => {83        const regex = /^-?(([-+]?)([\d]{1,3})((\.)(\d+))?)/g;84        return regex.test(lng) && typeof lng === "number" && !isNaN(lng);85    },86    saveUserLocation: async ({latitude, longitude, appVersion}, user) => {87        try {88            if (user && user.get("isDriver") && user.get("isDriverApp") && Utils.validateLatitude(latitude) && Utils.validateLongitude(longitude)) {89                const location = new Parse.GeoPoint({90                    latitude: latitude,91                    longitude: longitude92                });93                user.set("lastLocationDate", new Date());94                user.set("location", location);95                if (appVersion && typeof appVersion === 'string')96                    user.set("lastAppVersion", parseInt(appVersion.split(".").join("")));97                await user.save(null, {useMasterKey: true});98            }99        } catch (e) {100            console.log("Error in save location on end point.");101        }102    },103    getDuration: (date1, date2) => {104        try {105            const d = date2 - date1;106            const weekdays = Math.floor(d / 1000 / 60 / 60 / 24 / 7);107            const days = Math.floor(d / 1000 / 60 / 60 / 24 - weekdays * 7);108            const hours = Math.floor(d / 1000 / 60 / 60 - weekdays * 7 * 24 - days * 24);109            const minutes = Math.floor(d / 1000 / 60 - weekdays * 7 * 24 * 60 - days * 24 * 60 - hours * 60);110            const seconds = Math.floor(d / 1000 - weekdays * 7 * 24 * 60 * 60 - days * 24 * 60 * 60 - hours * 60 * 60 - minutes * 60);111            const milliseconds = Math.floor(d - weekdays * 7 * 24 * 60 * 60 * 1000 - days * 24 * 60 * 60 * 1000 - hours * 60 * 60 * 1000 - minutes * 60 * 1000 - seconds * 1000);112            let t = {};113            ['weekdays', 'days', 'hours', 'minutes', 'seconds', 'milliseconds'].forEach(q => {114                if (eval(q) > 0) {115                    t[q] = eval(q);116                }117            });118            return t;119        } catch (e) {120            console.log("Error in get duration: ", e);121            return {};122        }123    },124    verifyAppVersion: (curr = null, required = null) => {125        try {126            if (!curr || !required || typeof curr !== "string" || typeof required !== "string") return false;127            let _result;128            const versionNumbers = (str) => {129                return str.split(".")130                    .map((item) => parseInt(item))131            };132            const currValues = versionNumbers(curr);133            const requiredValues = versionNumbers(required);134            if (currValues.length !== requiredValues.length) return false;135            const verifyItem = (item, index) => {136                if (!item && item !== 0) return false;137                if (item === NaN) return false;138                if (!requiredValues[index] && requiredValues[index] !== 0) return false;139                if (requiredValues[index] === NaN) return false;140                return item > requiredValues[index] ? "bigger" : item < requiredValues[index] ? "smaller" : "equal";141            };142            const results = currValues.map((item, index) => {143                return verifyItem(item, index);144            });145            for (let i = 0; i < results.length; i++) {146                if (!results[i]) {147                    _result = false;148                    break;149                } else {150                    if (results[i] === "smaller") {151                        _result = false;152                        break;153                    } else if (results[i] === "bigger") {154                        _result = true;155                        break;156                    } else157                        _result = true;158                }159            }160            return _result;161        } catch (e) {162            return false;163        }164    },165    formatOrder: async (_params) => {166        if (_params.order) {167            if (_params.order[0] === "+") _params.ascendingBy = _params.order.substring(1);168            else if (_params.order[0] === "-") _params.descendingBy = _params.order.substring(1);169        }170    },171    findObjectOrQueries: async (className, conditionObj, firstCommand, ascendingBy, descendingBy, limit, page, queries) => {172        let query = new Parse.Query(className);173        if (conditionObj) {174            for (let key in conditionObj) {175                query.equalTo(key, conditionObj[key]);176            }177        }178        if (ascendingBy) query.ascending(ascendingBy);179        if (descendingBy) query.descending(descendingBy);180        if (queries) {181            query = await Utils.createOrQuery(queries);182        }183        limit = limit || 9999999;184        query.limit(limit); //CAN'T CHANGE THIS BECAUSE OF MANUAL PAGINATION WITH COUNTING185        if (page)186            query.skip(page);187        return firstCommand ? query.first() : query.find({useMasterKey: true});188    },189    formatParamsStateAndCity: async (_params, object, stateInicials) => {190        _params.isPrimary = (!_params.city && !_params.state) && (!_params.stateId);191        if (_params.stateId) {192            const state = await Utils.getObjectById(_params.stateId, Define.State) || undefined;193            _params.state = stateInicials ? state.get("sigla") : (state.get("name")).trim();194            if (_params.cityId) {195                const city = await Utils.getObjectById(_params.cityId, Define.City) || undefined;196                _params.city = (city.get("name")).trim();197            } else object.unset("city");198        } else if (_params.state) {199            _params.state = Utils.removeDiacritics(_params.state).trim();200            if (_params.city) _params.city = (_params.city).trim();201            else object.unset("city");202        } else {203            object.unset("state");204            object.unset("city");205        }206        delete _params.stateId;207        delete _params.cityId;208    },209    getStateAndCity: async (output, object) => {210        let state;211        if (object.get("state") && object.get("state").length < 4) {212            state = object.get("state") ? await Utils.findObject(Define.State, {"sigla": Utils.removeDiacritics(object.get("state").trim())}, true) : undefined;213        } else {214            state = object.get("state") ? await Utils.findObject(Define.State, {"searchName": Utils.removeDiacritics(object.get("state").toLowerCase().trim())}, true) : undefined;215        }216        const city = object.get("state") && object.get("city") ? await Utils.findObject(Define.City, {217            "searchName": Utils.removeDiacritics(object.get("city").toLowerCase().trim()),218            "state": state219        }, true) : undefined;220        output.stateId = state ? state.id : undefined;221        output.cityId = city ? city.id : undefined;222    },223    verifyIsoDate: (str = null) => {224        if (!str) return false;225        return (new Date(str) !== "Invalid Date") && !isNaN(new Date(str));226    },227    getTravelsTolistRecentAddresses: (type, user) => {228        let queryTravel = new Parse.Query(Define.Travel);229        queryTravel.equalTo(type, user);230        queryTravel.descending("createdAt");231        queryTravel.equalTo("status", "completed");232        queryTravel.limit(100);233        queryTravel.include(["destination"]);234        queryTravel.select(["destination", "destinationJson"]);235        return queryTravel.find();236    },237    cleanObject: (obj) => {238        obj = null;239        return obj;240    },241    formatMobileFieldReceipt: (type, language, name, value) => {242        let field = Messages(language).receipt[type][name];243        let output = {244            name: field,245            value246        };247        return output;248    },249    formatWebFieldReceipt: (type, language, name, value, specialField) => {250        let field = Messages(language).receipt[type][name];251        value = value && typeof value === "number" ? value.toFixed(2) : 0.00;252        let currency = Messages(language).receipt.currency;253        let output;254        if (!specialField)255            output = " <div style=\"float: left;\">" + field + "</div>" +256                " <div style=\"float: right; margin-right: 20px;\">" + currency + " " + value + "</div>\n <br>";257        else258            output = " <br><div style=\"float: left; color: #333;\"><b>" + field + "</b></div>\n" +259                " <div style=\"float: right; margin-right: 20px; color: #333;\"><b>" + currency + " " + value + "</b></div>";260        return output;261    },262    formatPaymentData: (travel, date, month, language) => {263        let output, paymentData = Messages(language).receipt.typePayment;264        if (travel.has("card")) {265            output = "                    <td>\n" +266                "                        <span class=\"dark\">" + travel.get("card").get("brand") + " " + travel.get("card").get("numberCrip").slice(15) + "</span><br>\n" +267                date.getDate() + "/" + month + "/" + date.getFullYear() + " " + date.getHours() + ":" + (date.getMinutes() < 10 ? '0' + date.getMinutes().toString() : date.getMinutes()) + "</td>\n";268        } else {269            output = "                    <td>\n" +270                "                        <span class=\"dark\"> " + paymentData + "</span><br>\n" +271                travel.get("endDate").getDate() + "/" + month + "/" + date.getFullYear() + " " + date.getHours() + ":" + (date.getMinutes() < 10 ? '0' + date.getMinutes().toString() : date.getMinutes()) + "</td>\n";272        }273        return output;274    },275    encrypt: (text) => {276        let cipher = crypto.createCipheriv('aes-256-cbc',277            new Buffer(secretKey), iv);278        let crypted = cipher.update(text, 'utf8', 'hex');279        crypted += cipher.final('hex');280        return crypted;281    },282    decrypt: (text) => {283        let decipher = crypto.createDecipheriv('aes-256-cbc',284            new Buffer(secretKey), iv);285        let decrypted = decipher.update(text, 'hex', 'utf8');286        return (decrypted + decipher.final('utf8'));287    },288    setTimezone: function (date, offset) {289        return new Date(date.getTime() + (offset * 60000));290    },291    printLogAPI: function (request) {292        console.log("\n-->> METHOD: ", request.functionName);293        console.log("-->> JSON: ", request.params);294        console.log("-->> USER: ", request.user ? request.user.id : "Not logged")295    },296    sendEmailByStage: function (user) {297        let data = {298            phone: user.get("phone"),299            name: user.get("name") || Utils.capitalizeFirstLetter(user.get("email").replace(/[\W_]+/, " ").split(" ")[0])300        };301        return Mail.sendTemplateEmail(user.get("email"), Define.emailByStage[user.get("profileStage")].html, data, Define.emailByStage[user.get("profileStage")].subject);302        // return Utils.readHtml(Define.emailByStage[user.get("profileStage")].html, data).then(function (htmlBody) {303        //     return Mail.sendEmail(user.get("email"), Define.emailByStage[user.get("profileStage")].subject, htmlBody);304        // });305    },306    sendEmailAlertBug: async (msg) => {307        let emails = "axel.andrade@usemobile.xyz,ana.moraes@usemobile.xyz,mateus.freire@usemobile.xyz,patrick+xyz@usemobile.com.br";308        await Mail.sendTemplateEmail(emails, Define.emailByStage.alertBug.html, {msg}, Define.emailByStage.alertBug.subject.replace("{{name}}", conf.appName));309    },310    getMonth: function (date, language) {311        date = date || new Date();312        let months;313        switch (language) {314            case "us":315            case "en":316            case "en_en":317                months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];318                break;319            case "es_es":320            case "es":321                months = ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"];322                break;323            default:324                months = ["Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"];325        }326        return months[date.getMonth()];327    },328    addOffsetToDate: function (date, offset) {329        let newDate = new Date(date); //just in case it is a string330        return new Date(newDate.setMinutes(newDate.getMinutes() + offset));331    },332    getObjectById: function (id, className, includes, equals, contains, select) {333        let query = new Parse.Query(className);334        if (select) {335            query.select(select);336        }337        if (includes) {338            query.include(includes);339        }340        if (equals) {341            for (let key in equals) {342                query.equalTo(key, equals[key]);343            }344        }345        if (contains) {346            for (let key in contains) {347                query.containedIn(key, contains[key]);348            }349        }350        return query.get(id, {useMasterKey: true});351    },352    findObjects: function ({className, conditionObj, firstCommand, include, ascendingBy, descendingBy, contained, notEq, limit, exists, contains, page, select}) {353        return Utils.findObject(className, conditionObj, firstCommand, include, ascendingBy, descendingBy, contained, notEq, limit, exists, contains, page, select);354    },355    findObject: function (className, conditionObj, firstCommand, include, ascendingBy, descendingBy, contained, notEq, limit, exists, contains, page, select, matches) {356        let query = new Parse.Query(className);357        if (conditionObj) {358            for (let key in conditionObj) {359                query.equalTo(key, conditionObj[key]);360            }361        }362        if (include) {363            query.include(include);364        }365        if (select) query.select(select);366        if (ascendingBy) query.ascending(ascendingBy);367        if (descendingBy) query.descending(descendingBy);368        if (contained) {369            for (let key in contained) {370                query.containedIn(key, contained[key]);371            }372        }373        if (contains) {374            for (let key in contains) {375                query.contains(key, contains[key]);376            }377        }378        if (matches) {379            for (let match in matches) {380                query.matches(match, matches[match], "i");381            }382        }383        if (exists) {384            (!Array.isArray(exists)) && (exists = [exists]);385            for (let i = 0; i < exists.length; i++) {386                query.exists(exists[i]);387            }388        }389        if (notEq) {390            for (let key in notEq) {391                query.notEqualTo(key, notEq[key]);392            }393        }394        limit = limit || 9999999;395        query.limit(limit); //CAN'T CHANGE THIS BECAUSE OF MANUAL PAGINATION WITH COUNTING396        if (page)397            query.skip(page);398        return firstCommand ? query.first() : query.find({useMasterKey: true});399    },400    convertDateToPsql: function (date) {401        let d = new Date(date),402            month = '' + (d.getMonth() + 1),403            day = '' + d.getDate(),404            year = d.getFullYear();405        if (month.length < 2)406            month = '0' + month;407        if (day.length < 2)408            day = '0' + day;409        return [year, month, day].join('-') + ((d.toLocaleString().split(',')[1] != undefined) ? d.toLocaleString().split(',')[1] : '');410    },411    countObject: function (className, conditionObj, contained, exists, greaterThanOrEqualTo, matches) {412        let query = new Parse.Query(className);413        if (conditionObj) {414            for (let key in conditionObj) {415                query.equalTo(key, conditionObj[key]);416            }417        }418        if (contained) {419            for (let key in contained) {420                query.containedIn(key, contained[key]);421            }422        }423        if (greaterThanOrEqualTo) {424            for (let key in greaterThanOrEqualTo) {425                query.greaterThanOrEqualTo(key, greaterThanOrEqualTo[key]);426            }427        }428        if (exists) {429            (!Array.isArray(exists)) && (exists = [exists]);430            for (let i = 0; i < exists.length; i++) {431                query.exists(exists[i]);432            }433        }434        if (matches) {435            for (let match in matches) {436                query.matches(match, matches[match], "i");437            }438        }439        return query.count({useMasterKey: true});440    },441    verifyRequiredFields: function (arrayFields, requiredFields, response) {442        let missingFields = [];443        for (let i = 0; i < requiredFields.length; i++) {444            if (arrayFields[requiredFields[i]] == null) {445                missingFields.push(requiredFields[i]);446            }447        }448        if (missingFields.length > 0) {449            return response.error(600, "Field(s) '" + missingFields + "' are required.");450            return false;451        }452        return true;453    },454    verifyStringNull: function (text) {455        return text == undefined ? "" : text;456    },457    verifyCNPJ: function (c) {458        let b = [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2];459        if ((c = c.replace(/[^\d]/g, "")).length != 14)460            return false;461        if (/0{14}/.test(c))462            return false;463        let n = 0;464        for (let i = 0; i < 12; n += c[i] * b[++i]) ;465        if (c[12] != (((n %= 11) < 2) ? 0 : 11 - n))466            return false;467        n = 0;468        for (let i = 0; i <= 12; n += c[i] * b[i++]) ;469        if (c[13] != (((n %= 11) < 2) ? 0 : 11 - n))470            return false;471        return true;472    },473    verifyBilletId: function (strBillet) {474        return strBillet.length === 14 && !isNaN(strBillet.substr(0, 9)) && isNaN(strBillet.substr(9, 11)) && !isNaN(strBillet.substr(11, 14));475    },476    verifyCi: function (strCi) {477        let result;478        strCi.length === 7 ? result = true : result = false;479        return result;480        //return ci_node.validate_ci(strCi);481    },482    verifyCpf: function (strCPF) {483        let Soma;484        let Resto;485        Soma = 0;486        let mapCPFs = {487            "00000000000": true,488            "11111111111": true,489            "22222222222": true,490            "33333333333": true,491            "44444444444": true,492            "55555555555": true,493            "66666666666": true,494            "77777777777": true,495            "88888888888": true,496            "99999999999": true,497        };498        if (mapCPFs[strCPF]) return false;499        for (let i = 1; i <= 9; i++) Soma = Soma + parseInt(strCPF.substring(i - 1, i)) * (11 - i);500        Resto = (Soma * 10) % 11;501        if ((Resto == 10) || (Resto == 11)) Resto = 0;502        if (Resto != parseInt(strCPF.substring(9, 10))) return false;503        Soma = 0;504        for (let i = 1; i <= 10; i++) Soma = Soma + parseInt(strCPF.substring(i - 1, i)) * (12 - i);505        Resto = (Soma * 10) % 11;506        if ((Resto == 10) || (Resto == 11)) Resto = 0;507        if (Resto != parseInt(strCPF.substring(10, 11))) return false;508        return true;509    },510    convertMinToHHMMSS: function (minutes) {511        if (!minutes) return "00:01:00";512        let date = new Date(null);513        date.setSeconds(minutes * 60); // specify value for SECONDS here514        return date.toISOString().substr(11, 8);515    },516    verifyAccessAuth: function (user, type, response) {517        if (!user) {518            response.error(Messages().error.ERROR_ACCESS_REQUIRED.code, Messages((user && user.get) ? user.get("language") : undefined).error.ERROR_ACCESS_REQUIRED.message);519            return false;520        }521        let userType = user.get("isDriverApp") ? "driver" : "passenger";522        let denied = (!user || (type && type.indexOf(userType) < 0));523        denied = user.get("isAdmin") ? false : denied; //denied could already be false524        if (denied) {525            response.error(Messages().error.ERROR_ACCESS_REQUIRED.code, Messages(user.get("language")).error.ERROR_ACCESS_REQUIRED.message);526            return false;527        }528        return true;529    },530    formatParams: function (params) {531        let obj = {};532        if (params) {533            for (let key in params) {534                if (key == "password") {535                    obj[key] = params[key];536                    continue;537                }538                let a = key.replace("[]", "");539                obj[a] = (key.indexOf("[]") >= 0 && typeof params[key] == "string") ? params[key].split('\"') : Utils.tryJsonParse(params[key]);540            }541        }542        return obj;543    },544    padWithZeros: function (number, length) {545        let my_string = '' + number;546        while (my_string.length < length) {547            my_string = '0' + my_string;548        }549        return my_string;550    },551    generateMapImage: function (originLatitude, originLongitude, destinationLatitude, destinationLongitude) {552        let bigMap = 'https://maps.googleapis.com/maps/api/staticmap?key=' + Define.MapsKey + '&size=600x300&maptype=roadmap&markers=color:green%7Clabel:I%7C' +553            originLatitude + ',' + originLongitude + '&markers=color:red%7Clabel:F%7C' + destinationLatitude + ',' + destinationLongitude;554        return Utils.saveImageFromUrl(bigMap);555    },556    capitalizeFirstLetter: function (string) {557        return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();558    },559    tryJsonParse: function (variable, returnJsonInFail) {560        try {561            return JSON.parse(variable);562        } catch (e) {563            return returnJsonInFail ? {} : variable;564        }565    },566    verify: function verify(listElements, listFields) {567        let wrongFields = [];568        for (let k in listElements) {569            if (listFields.indexOf(k) < 0 && (listElements[k] && (!listElements[k].__op || listElements[k].__op !== "Delete"))) {570                wrongFields.push(k);571            }572        }573        return wrongFields;574    },575    formatDayOfWeek: function (date, offset) {576        date = date || new Date();577        date = new Date(date.setMinutes(date.getMinutes() + offset));578        let days = ["Dom", "Seg", "Ter", "Qua", "Qui", 'Sex', "Sab"];579        return days[date.getDay()];580    },581    formatPFObjectInJson: function (object, fields) {582        if (!object) return {};583        let json = {};584        for (let i = 0; i < fields.length; i++) {585            if (object.get(fields[i]) !== undefined) {586                json[fields[i]] = object.get(fields[i]);587                if (fields[i] === "email" || fields[i] === "phone") {588                    json[fields[i]] = Utils.hideInformation(json[fields[i]]);589                }590            }591        }592        json.objectId = object.id;593        delete json.createdAt;594        delete json.updatedAt;595        return json;596    },597    readHtml: function (file, data) {598        data = data || {};599        let filepath = './mails/' + file + ".html";600        let promise = new Promise((resolve, reject) => {601            fs.readFile(filepath, "utf8", function (err, htmlBody) {602                if (err) {603                    reject(err);604                }605                for (let key in data) {606                    htmlBody = htmlBody.replace(new RegExp("{{" + key + "}}", "g"), data[key]);607                }608                resolve(htmlBody);609            });610        });611        return promise;612    },613    readHtmlFromDatabase: function (body, data) {614        data = data || {};615        for (let key in data) {616            body = body.replace(new RegExp("{{" + key + "}}", "g"), data[key]);617        }618        return body;619    },620    readHtmlMultipleTimes: function (file, users) {621        let filepath = './mails/' + file + ".html";622        let promise = new Promise((resolve, reject) => {623            fs.readFile(filepath, "utf8", function (err, htmlBody) {624                if (err) {625                    reject(err);626                }627                for (let i = 0; i < users.length; i++) {628                    let html = htmlBody.repeat(1);629                    for (let key in users[i].data) {630                        html = html.replace("{{" + key + "}}", users[i].data[key]);631                    }632                    users[i].html = html;633                }634                resolve(users);635            });636        });637        return promise;638    },639    verifyPatternOfPlate: function (plate) {640        if (!plate) return false;641        const platePattern = RegExp('([a-zA-Z]{3}[0-9]{4})|(^[a-zA-Z]{3}[0-9][a-zA-Z][0-9]{2})');642        return platePattern.test(plate);643    },644    verifyPatternOfPlateBolivia: function (plate) {645        if (!plate) return false;646        const platePattern = RegExp('([0-9]{4}[a-zA-Z]{3})');647        return platePattern.test(plate);648    },649    verifyPatternOfPlateAngola: function (plate) {650        if (!plate) return false;651        const platePattern = RegExp('([a-zA-Z]{2}[0-9]{4}[a-zA-Z]{2})');652        return platePattern.test(plate);653    },654    convertHtmlToImage: function (rawHtml) {655        let pdfPath = "html2pdf.pdf";656        let imgPath = "pdf2png.png";657        let options = {658            format: "Tabloid",//A2659            border: "2cm"660        };661        let promise = new Promise((resolve, reject) => {662            try {663                html2pdf.create(rawHtml, options).toFile(pdfPath, function (err, res) {664                    if (err) reject(err);665                    else {666                        pdf2png.convert(pdfPath, {quality: 300}, function (resp) {667                            if (!resp.success) {668                                reject(resp.error);669                                return670                            }671                            fs.writeFile(imgPath, resp.data, function (err) {672                                if (err) {673                                    reject(err);674                                } else {675                                    //remover o pdf676                                    fs.unlink(pdfPath, function (err) {677                                        if (err) reject(err);678                                        else {679                                            let buffer = new Buffer(resp.data);680                                            let base64File = buffer.toString('base64');681                                            let file = new Parse.File("receipt.png", {base64: base64File});682                                            return file.save().then(function (newFile) {683                                                fs.unlink(imgPath, function (err) {684                                                    if (err) reject(err);685                                                    else {686                                                        resolve(newFile.url());687                                                    }688                                                });689                                            })690                                        }691                                    });692                                }693                            });694                        });695                    }696                });697            } catch (e) {698                reject({code: 400, message: "Não foi possivel gerar seu recibo no momento."});699            }700        });701        return promise;702    },703    saveImageFromUrl: function (url) {704        return Parse.Cloud.httpRequest({url: url}).then(function (response) {705            let data = "data:" + response.headers["content-type"] + ";base64," + new Buffer(response.buffer).toString('base64');706            return new Parse.File("image", {base64: data}).save();707        }).then(function (file) {708            return Promise.resolve(file ? file.url() : null);709        }, function (error) {710            return Promise.resolve();711        });712    },713    getDistanceInformation: function (originLat, originLng, destLat, destLng, attempt) {714        attempt = attempt || 0;715        if (attempt == 3) return Promise.resolve({});716        let origin = originLat + "," + originLng;717        let destiny = destLat + "," + destLng;718        let url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=" + origin + "&destinations=" + destiny + "&key=" + Define.MapsKey;719        return Parse.Cloud.httpRequest({url: url}).then(function (httpResponse) {720            let data = httpResponse.data;721            if (data.status === "OVER_QUERY_LIMIT" || data.error_message) {722                return Promise.resolve({});723            }724            if (data && data.rows && data.rows.length > 0 && data.rows[0].elements && data.rows[0].elements.length > 0) {725                return Promise.resolve({726                    distance: data.rows[0].elements[0].distance.value / 1000,727                    time: parseFloat(data.rows[0].elements[0].duration.value / 60)728                });729            } else {730                return Utils.getLocationInformation(originLat, originLng, destLat, destLng, ++attempt);731            }732        })733    },734    getCityByLatLng: function (lat, lng) {735        if (!lat || !lng) return Promise.resolve({});736        return Parse.Cloud.httpRequest({url: "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + lat + "," + lng + "&sensor=true&key=" + Define.MapsKey}).then(function (httpResponse) {737            if (httpResponse.data && httpResponse.data.error_message) {738                console.log(httpResponse.data.error_message);739            }740            let json = {city: null, state: null}, hasCity, hasState;741            for (let i = 0; i < httpResponse.data.results.length; i++) {742                let address_components = httpResponse.data.results[i].address_components;743                for (let j = 0; j < address_components.length; j++) {744                    let types = address_components[j].types;745                    for (let k = 0; k < types.length; k++) {746                        if (types[k] == "administrative_area_level_2") {747                            json.city = address_components[j].long_name;748                            hasCity = true;749                        }750                        if (types[k] == "administrative_area_level_1") {751                            json.state = address_components[j].long_name;752                            hasState = true;753                        }754                        if (hasState && hasCity) return Promise.resolve(json);755                    }756                }757            }758            return Promise.resolve(json);759        });760    },761    getLocationInformation: function (lat, lng, attempt) {762        attempt = attempt || 0;763        if (attempt == 3) return Promise.resolve({});764        let promise = new Promise((resolve, reject) => {765            if (!lat || !lng) {766                resolve({});767            }768            let url = "https://maps.googleapis.com/maps/api/geocode/json?key=" + Define.MapsKey + "&address=";769            Parse.Cloud.httpRequest({url: url + lat + "," + lng}).then(function (httpResponse) {770                let data = httpResponse.data;771                if (data.error_message) {772                    return Utils.getLocationInformation(lat, lng, ++attempt); //pending for too long without api key773                    // reject(data.error_message);774                } else {775                    if (data && data.results.length > 0 && data.results[0].formatted_address) {776                        let formatted_address = data.results[0].formatted_address;777                        let indexOfHifen = formatted_address.indexOf(',');778                        formatted_address = formatted_address.substring(0, indexOfHifen);779                        let auxIndex = formatted_address.indexOf('-');780                        indexOfHifen = auxIndex >= 0 ? auxIndex : indexOfHifen;781                        let street = formatted_address.substring(0, indexOfHifen);782                        formatted_address = formatted_address.substring(indexOfHifen + 1);783                        resolve({784                            street: street.trim(),785                            number: formatted_address.substring(0, formatted_address.indexOf('-')).trim()786                        });787                    } else {788                        resolve({});789                    }790                }791            });792        });793        return promise;794    },795    formatDateCalendar: function (date) {796        return date.getDate() + ' ' + date.getMonth() + 1 + ' ' + date.getFullYear();797    },798    formatDateCalendarUSA: function (date) {799        return date.getMonth() + 1 + ' ' + date.getDate() + ' ' + date.getFullYear();800    },801    formatTime: function (seconds) {802        return Math.floor(seconds / 60) + ":" + ((Math.floor(seconds % 60) < 10) ? "0" : "") + Math.floor(seconds % 60);803    },804    diffTimeinMinutes: function (date, endDate) {805        let now = endDate || new Date();806        let diffMs = (now - date);807        return Math.abs((diffMs / 1000) / 60);808    },809    convertTextToSearchText: function (text) {810        if (!text || text.length == 0)811            return "";812        let _ = require('../node_modules/underscore/underscore.js');813        let toLowerCase = function (w) {814            return w.toLowerCase();815        };816        return Utils.replaceSpecialChars(text).toLowerCase();817    },818    formatCurrencyToFloat: function (currency) {819        try {820            return Number(currency.replace(".", "").replace(",", ".").replace(/[^0-9.-]+/g, ""));821        } catch (e) {822            return parseFloat(currency.split(" ")[1].replace(",", ".").replace(/[^0-9.-]+/g, ""));823        }824    },825    replaceSpecialChars: function (palavra) {826        let com_acento = 'åáàãâäéèêëíìîïóòõôöúùûüçÅÁÀÃÂÄÉÈÊËÍÌÎÏÓÒÕÖÔÚÙÛÜÇ';827        let sem_acento = 'aaaaaaeeeeiiiiooooouuuucAAAAAAEEEEIIIIOOOOOUUUUC';828        let nova = '';829        for (let i = 0; i < palavra.length; i++) {830            if (com_acento.indexOf(palavra.substr(i, 1)) >= 0) {831                nova += sem_acento.substr(com_acento.indexOf(palavra.substr(i, 1)), 1);832            } else {833                nova += palavra.substr(i, 1);834            }835        }836        return nova;837    },838    convertTextToSearchArray: function (text) {839        if (!text || text.length == 0)840            return [];841        let _ = require('../node_modules/underscore/underscore.js');842        let toLowerCase = function (w) {843            return w.toLowerCase();844        };845        let stopWords = ["e", "o", "a", "i", "u"];846        let words = Utils.replaceSpecialChars(text).split(/\b/);847        words = _.map(words, toLowerCase);848        words = _.filter(words, function (w) {849            return w.match(/^\w+$/) && !_.contains(stopWords, w);850        });851        return words;852    },853    convertTimestampToDateTime: function (date) {854        // Hours part from the timestamp855        let hours = date.getHours();856        // Minutes part from the timestamp857        let minutes = "0" + date.getMinutes();858        // Seconds part from the timestamp859        let seconds = "0" + date.getSeconds();860        // Will display time in 10:30:23 format861        return date.getDay() + "/" + date.getMonth() + "/" + date.getYear() + " " + hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);862    },863    formatHour: function (date, offset) {864        if (offset) {865            date = new Date(date.setMinutes(date.getMinutes() + offset));866        }867        let hours = "0" + date.getHours();868        let minutes = "0" + date.getMinutes();869        return hours.substr(-2) + ':' + minutes.substr(-2);870    },871    formatMinutsToHour: function formatMinutsToHour(minutes) {872        let hoursStr = "0" + parseInt(minutes / 60);873        let minutesStr = "0" + (minutes - (hoursStr * 60));874        return hoursStr.substr(-2) + ':' + minutesStr.substr(-2);875    },876    createOrQuery: (querys) => {877        return Parse.Query.or(...querys);878    },879    createQuery: ({Class, conditions, matches, exists, matchesQuery, order, skip, limit, greatherThan, lessThan, select, contained}) => {880        let query = new Parse.Query(Class);881        if (conditions) {882            Object.keys(conditions).forEach((key) => {883                query.equalTo(key, conditions[key])884            });885        }886        if (contained) {887            Object.keys(contained).forEach((key) => {888                query.containedIn(key, contained[key])889            });890        }891        if (select) {892            query.select(select)893        }894        if (greatherThan) {895            Object.keys(greatherThan).forEach((key) => {896                query.greaterThan(key, greatherThan[key])897            });898        }899        if (lessThan) {900            Object.keys(lessThan).forEach((key) => {901                query.lessThan(key, lessThan[key])902            });903        }904        if (matches) {905            Object.keys(matches).forEach((key) => {906                query.matches(key, matches[key])907            });908        }909        if (exists) {910            Object.keys(exists).forEach((key) => {911                query.exists(key, exists[key])912            });913        }914        if (matchesQuery) {915            Object.keys(matchesQuery).forEach((key) => {916                query.matchesQuery(key, matchesQuery[key])917            });918        }919        return query;920    },921    toFloat: function (value, decimals) {922        if (value === undefined) return 0;923        decimals = decimals || 2;924        return parseFloat(value.toFixed(2));925    },926    verifyDateIsThisWeek: function (date) {927        date = date || new Date();928        let dateDiff = date.getDay() || 7;929        let startDate = new Date(date.setDate(date.getDate() - dateDiff + 1));930        startDate = new Date(startDate.setHours(0, 0, 0, 0));931        dateDiff = date.getDay() ? 7 - date.getDay() : 6;932        let endDate = new Date(date.setDate(date.getDate() + dateDiff));933        endDate = new Date(endDate.setHours(23, 59, 50, 0));934        let now = new Date();935        return startDate.getTime() <= now.getTime() && now.getTime() <= endDate.getTime();936    },937    formatDate: function (date, verifyIfNull) {938        if (verifyIfNull && !date) return null;939        date = date || new Date(date);940        let day = date.getDate();941        let month = date.getMonth() + 1;942        return (day < 10 ? "0" + day : day) + "/" + (month < 10 ? "0" + month : month) + "/" + date.getFullYear();943    },944    styleTitle: function (title, markers) {945        if (!title) return "";946        if (!markers || markers.length == 0) return title;947        let text = "";948        let j = 0;949        for (let i = 0; i < title.length; i++) {950            if (j < markers.length && i == markers[j]) {951                if (j++ % 2 == 0) text += "<span style='color: red;'>";952                else text += "</span>";953            }954            text += title.charAt(i);955        }956        return text;957    },958    checkIfJsonIsEmpty: function (json) {959        return JSON.stringify(json) === JSON.stringify({})960    },961    validateEmail: function (email) {962        let re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;963        return re.test(email);964    },965    compareContent: function (a, b) {966        return JSON.stringify(a) === JSON.stringify(b)967    },968    convertParseObjectToJsonObject: function (array) {969        let objects = [];970        for (let i = 0; i < array.length; i++) {971            objects.push(array[i].toJSON());972        }973        return objects;974    },975    formatErrorsList: function (error) {976        if (!Array.isArray(error)) return error;977        for (let i = 0; i < error.length; i++) {978            if (error[i]) {979                return error[i];980            }981        }982        return error;983    },984    verifyUser: function (user, userType) {985        return new Promise(function (resolve, reject) {986            if (user != null) {987                let query = new Parse.Query(Parse.User);988                query.get(user.id, {989                    success: function (userAgain) {990                        // Check if userType is "user", other usertypes can't create campaigns991                        if (userAgain.get("userType") != userType) {992                            reject("User do not have permission.");993                        } else {994                            resolve();995                        }996                    }997                });998            } else {999                reject("Access unauthorized");1000            }1001        });1002    },1003    exitsValueInArray: function (array, value) {1004        for (let i = 0; i < array.length; i++) {1005            if (array[i].username && array[i].username == value) {1006                return i;1007            }1008        }1009        return -1;1010    },1011    isArrayOrJson: function (variable) {1012        try {1013            JSON.parse(str);1014            return true;1015        } catch (e) {1016            return Array.isArray((variable))1017        }1018    },1019    formatListInJson: function (array, fields) {1020        let objects = [];1021        for (let i = 0; i < array.length; i++) {1022            objects.push(Utils.formatObjectToJson(array[i], fields));1023        }1024        return objects;1025    },1026    randomString: function (size) {1027        let _crypto = require('crypto');1028        if (size === 0) {1029            throw new Error('Zero-length randomString is useless.');1030        }1031        let chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789';1032        let objectId = '';1033        let bytes = (0, _crypto.randomBytes)(size);1034        for (let i = 0; i < bytes.length; ++i) {1035            objectId += chars[bytes.readUInt8(i) % chars.length];1036        }1037        return objectId;1038    },1039    hexOctet: function () {1040        return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);1041    },1042    generateId: function () {1043        return Utils.hexOctet() + Utils.hexOctet() + '-' + Utils.hexOctet() + '-' + Utils.hexOctet() + '-' + Utils.hexOctet() + '-' + Utils.hexOctet() + Utils.hexOctet() + Utils.hexOctet();1044    },1045    GenerateUrlComponent: function (title) {1046        title = title.toLowerCase().trim();1047        title = Utils.removeDiacritics(title);1048        title = title.replace(/\s+/g, "-");1049        title = title.replace(/[^a-zA-Z0-9-]/g, "-");1050        title = title.replace(/[-]+/g, "-");1051        return title.replace(/(^-)|(-$)/g, "");1052    },1053    verifyExisting: function (prefix, limit, step) {1054        let stepString = step.toString();1055        if (prefix.length + stepString.length <= limit)1056            return prefix + stepString;1057        else {1058            let length = prefix.length - stepString.length + 1;1059            if (length <= 0) // Ignorar por enquanto1060                ;1061            return prefix.substring(0, prefix.length - stepString.length + 1) + stepString;1062        }1063    },1064    formatUrlTitle: function (className, id, title, limit) {1065        limit = limit || 80;1066        let step = 0;1067        title = Utils.GenerateUrlComponent(title);1068        let query = new Parse.Query(className);1069        query.startsWith("link", title.substring(0, title.length - 5));1070        if (id) {1071            query.notEqualTo("objectId", id);1072            query.limit(1000);1073        }1074        return query.find().then(function (objects) {1075            let mapObjects = {};1076            for (let i = 0; i < objects.length; i++) {1077                mapObjects[objects[i].get("link")] = true;1078            }1079            let url = title;1080            while (mapObjects[url]) {1081                url = Utils.verifyExisting(title, limit, step++);1082            }1083            return Promise.resolve(url);1084        });1085    },1086    hideInformation: function (info) {1087        if (info) info = conf.hidePersonInformation ? "******" : info;1088        return info;1089    },1090    formatObjectToJson: function (object, fields) {1091        if (!object) return {};1092        let json = {};1093        for (let i = 0; i < fields.length; i++) {1094            json[fields[i]] = object.get(fields[i]);1095        }1096        json.createdAt = object.createdAt;1097        json.updatedAt = object.updatedAt;1098        json.objectId = object.id;1099        return json;1100    },1101    formatObjectArrayToJson: function (array, fields, createdAt) {1102        let objects = [];1103        for (let i = 0; i < array.length; i++) {1104            let obj = Utils.formatPFObjectInJson(array[i], fields);1105            if (createdAt) obj.createdAt = array[i].createdAt;1106            objects.push(obj);1107        }1108        return objects;1109    },1110    formatUserFields: function (user) {1111        let userJson = {1112            objectId: user.id,1113            name: user.get("name"),1114            username: user.get("isSocial") ? user.get("authUser") : user.get("username"),1115            profileImage: user.get("profileImage"),1116            languages: user.get("languages"),1117            language: user.get("language"),1118            lastName: user.get("lastName"),1119            email: user.get("email"),1120            picture: user.get("picture"),1121            userType: user.get("userType"),1122            isAdmin: user.get("isAdmin"),1123            config: user.get("config"),1124            isSocial: user.get("isSocial"),1125            isCompleted: user.get("isCompleted"),1126            sessionToken: user.getSessionToken()1127        };1128        return userJson;1129    },1130    cleanStringUTF8: function (input) {1131        let output = "";1132        for (let i = 0; i < input.length; i++) {1133            if (input.charCodeAt(i) <= 127) {1134                output += input.charAt(i);1135            }1136        }1137        return output;1138    },1139    removeDiacritics: function (str) {1140        let diacriticsMap = {1141            A: /[\u0041\u24B6\uFF21\u00C0\u00C1\u00C2\u1EA6\u1EA4\u1EAA\u1EA8\u00C3\u0100\u0102\u1EB0\u1EAE\u1EB4\u1EB2\u0226\u01E0\u00C4\u01DE\u1EA2\u00C5\u01FA\u01CD\u0200\u0202\u1EA0\u1EAC\u1EB6\u1E00\u0104\u023A\u2C6F]/g,1142            AA: /[\uA732]/g,1143            AE: /[\u00C6\u01FC\u01E2]/g,1144            AO: /[\uA734]/g,1145            AU: /[\uA736]/g,1146            AV: /[\uA738\uA73A]/g,1147            AY: /[\uA73C]/g,1148            B: /[\u0042\u24B7\uFF22\u1E02\u1E04\u1E06\u0243\u0182\u0181]/g,1149            C: /[\u0043\u24B8\uFF23\u0106\u0108\u010A\u010C\u00C7\u1E08\u0187\u023B\uA73E]/g,1150            D: /[\u0044\u24B9\uFF24\u1E0A\u010E\u1E0C\u1E10\u1E12\u1E0E\u0110\u018B\u018A\u0189\uA779]/g,1151            DZ: /[\u01F1\u01C4]/g,1152            Dz: /[\u01F2\u01C5]/g,1153            E: /[\u0045\u24BA\uFF25\u00C8\u00C9\u00CA\u1EC0\u1EBE\u1EC4\u1EC2\u1EBC\u0112\u1E14\u1E16\u0114\u0116\u00CB\u1EBA\u011A\u0204\u0206\u1EB8\u1EC6\u0228\u1E1C\u0118\u1E18\u1E1A\u0190\u018E]/g,1154            F: /[\u0046\u24BB\uFF26\u1E1E\u0191\uA77B]/g,1155            G: /[\u0047\u24BC\uFF27\u01F4\u011C\u1E20\u011E\u0120\u01E6\u0122\u01E4\u0193\uA7A0\uA77D\uA77E]/g,1156            H: /[\u0048\u24BD\uFF28\u0124\u1E22\u1E26\u021E\u1E24\u1E28\u1E2A\u0126\u2C67\u2C75\uA78D]/g,1157            I: /[\u0049\u24BE\uFF29\u00CC\u00CD\u00CE\u0128\u012A\u012C\u0130\u00CF\u1E2E\u1EC8\u01CF\u0208\u020A\u1ECA\u012E\u1E2C\u0197]/g,1158            J: /[\u004A\u24BF\uFF2A\u0134\u0248]/g,1159            K: /[\u004B\u24C0\uFF2B\u1E30\u01E8\u1E32\u0136\u1E34\u0198\u2C69\uA740\uA742\uA744\uA7A2]/g,1160            L: /[\u004C\u24C1\uFF2C\u013F\u0139\u013D\u1E36\u1E38\u013B\u1E3C\u1E3A\u0141\u023D\u2C62\u2C60\uA748\uA746\uA780]/g,1161            LJ: /[\u01C7]/g,1162            Lj: /[\u01C8]/g,1163            M: /[\u004D\u24C2\uFF2D\u1E3E\u1E40\u1E42\u2C6E\u019C]/g,1164            N: /[\u004E\u24C3\uFF2E\u01F8\u0143\u00D1\u1E44\u0147\u1E46\u0145\u1E4A\u1E48\u0220\u019D\uA790\uA7A4]/g,1165            NJ: /[\u01CA]/g,1166            Nj: /[\u01CB]/g,1167            O: /[\u004F\u24C4\uFF2F\u00D2\u00D3\u00D4\u1ED2\u1ED0\u1ED6\u1ED4\u00D5\u1E4C\u022C\u1E4E\u014C\u1E50\u1E52\u014E\u022E\u0230\u00D6\u022A\u1ECE\u0150\u01D1\u020C\u020E\u01A0\u1EDC\u1EDA\u1EE0\u1EDE\u1EE2\u1ECC\u1ED8\u01EA\u01EC\u00D8\u01FE\u0186\u019F\uA74A\uA74C]/g,1168            OI: /[\u01A2]/g,1169            OO: /[\uA74E]/g,1170            OU: /[\u0222]/g,1171            P: /[\u0050\u24C5\uFF30\u1E54\u1E56\u01A4\u2C63\uA750\uA752\uA754]/g,1172            Q: /[\u0051\u24C6\uFF31\uA756\uA758\u024A]/g,1173            R: /[\u0052\u24C7\uFF32\u0154\u1E58\u0158\u0210\u0212\u1E5A\u1E5C\u0156\u1E5E\u024C\u2C64\uA75A\uA7A6\uA782]/g,1174            S: /[\u0053\u24C8\uFF33\u1E9E\u015A\u1E64\u015C\u1E60\u0160\u1E66\u1E62\u1E68\u0218\u015E\u2C7E\uA7A8\uA784]/g,1175            T: /[\u0054\u24C9\uFF34\u1E6A\u0164\u1E6C\u021A\u0162\u1E70\u1E6E\u0166\u01AC\u01AE\u023E\uA786]/g,1176            TZ: /[\uA728]/g,1177            U: /[\u0055\u24CA\uFF35\u00D9\u00DA\u00DB\u0168\u1E78\u016A\u1E7A\u016C\u00DC\u01DB\u01D7\u01D5\u01D9\u1EE6\u016E\u0170\u01D3\u0214\u0216\u01AF\u1EEA\u1EE8\u1EEE\u1EEC\u1EF0\u1EE4\u1E72\u0172\u1E76\u1E74\u0244]/g,1178            V: /[\u0056\u24CB\uFF36\u1E7C\u1E7E\u01B2\uA75E\u0245]/g,1179            VY: /[\uA760]/g,1180            W: /[\u0057\u24CC\uFF37\u1E80\u1E82\u0174\u1E86\u1E84\u1E88\u2C72]/g,1181            X: /[\u0058\u24CD\uFF38\u1E8A\u1E8C]/g,1182            Y: /[\u0059\u24CE\uFF39\u1EF2\u00DD\u0176\u1EF8\u0232\u1E8E\u0178\u1EF6\u1EF4\u01B3\u024E\u1EFE]/g,1183            Z: /[\u005A\u24CF\uFF3A\u0179\u1E90\u017B\u017D\u1E92\u1E94\u01B5\u0224\u2C7F\u2C6B\uA762]/g,1184            a: /[\u0061\u24D0\uFF41\u1E9A\u00E0\u00E1\u00E2\u1EA7\u1EA5\u1EAB\u1EA9\u00E3\u0101\u0103\u1EB1\u1EAF\u1EB5\u1EB3\u0227\u01E1\u00E4\u01DF\u1EA3\u00E5\u01FB\u01CE\u0201\u0203\u1EA1\u1EAD\u1EB7\u1E01\u0105\u2C65\u0250]/g,1185            aa: /[\uA733]/g,1186            ae: /[\u00E6\u01FD\u01E3]/g,1187            ao: /[\uA735]/g,1188            au: /[\uA737]/g,1189            av: /[\uA739\uA73B]/g,1190            ay: /[\uA73D]/g,1191            b: /[\u0062\u24D1\uFF42\u1E03\u1E05\u1E07\u0180\u0183\u0253]/g,1192            c: /[\u0063\u24D2\uFF43\u0107\u0109\u010B\u010D\u00E7\u1E09\u0188\u023C\uA73F\u2184]/g,1193            d: /[\u0064\u24D3\uFF44\u1E0B\u010F\u1E0D\u1E11\u1E13\u1E0F\u0111\u018C\u0256\u0257\uA77A]/g,1194            dz: /[\u01F3\u01C6]/g,1195            e: /[\u0065\u24D4\uFF45\u00E8\u00E9\u00EA\u1EC1\u1EBF\u1EC5\u1EC3\u1EBD\u0113\u1E15\u1E17\u0115\u0117\u00EB\u1EBB\u011B\u0205\u0207\u1EB9\u1EC7\u0229\u1E1D\u0119\u1E19\u1E1B\u0247\u025B\u01DD]/g,1196            f: /[\u0066\u24D5\uFF46\u1E1F\u0192\uA77C]/g,1197            g: /[\u0067\u24D6\uFF47\u01F5\u011D\u1E21\u011F\u0121\u01E7\u0123\u01E5\u0260\uA7A1\u1D79\uA77F]/g,1198            h: /[\u0068\u24D7\uFF48\u0125\u1E23\u1E27\u021F\u1E25\u1E29\u1E2B\u1E96\u0127\u2C68\u2C76\u0265]/g,1199            hv: /[\u0195]/g,1200            i: /[\u0069\u24D8\uFF49\u00EC\u00ED\u00EE\u0129\u012B\u012D\u00EF\u1E2F\u1EC9\u01D0\u0209\u020B\u1ECB\u012F\u1E2D\u0268\u0131]/g,1201            j: /[\u006A\u24D9\uFF4A\u0135\u01F0\u0249]/g,1202            k: /[\u006B\u24DA\uFF4B\u1E31\u01E9\u1E33\u0137\u1E35\u0199\u2C6A\uA741\uA743\uA745\uA7A3]/g,1203            l: /[\u006C\u24DB\uFF4C\u0140\u013A\u013E\u1E37\u1E39\u013C\u1E3D\u1E3B\u017F\u0142\u019A\u026B\u2C61\uA749\uA781\uA747]/g,1204            lj: /[\u01C9]/g,1205            m: /[\u006D\u24DC\uFF4D\u1E3F\u1E41\u1E43\u0271\u026F]/g,1206            n: /[\u006E\u24DD\uFF4E\u01F9\u0144\u00F1\u1E45\u0148\u1E47\u0146\u1E4B\u1E49\u019E\u0272\u0149\uA791\uA7A5]/g,1207            nj: /[\u01CC]/g,1208            o: /[\u006F\u24DE\uFF4F\u00F2\u00F3\u00F4\u1ED3\u1ED1\u1ED7\u1ED5\u00F5\u1E4D\u022D\u1E4F\u014D\u1E51\u1E53\u014F\u022F\u0231\u00F6\u022B\u1ECF\u0151\u01D2\u020D\u020F\u01A1\u1EDD\u1EDB\u1EE1\u1EDF\u1EE3\u1ECD\u1ED9\u01EB\u01ED\u00F8\u01FF\u0254\uA74B\uA74D\u0275]/g,1209            oi: /[\u01A3]/g,1210            ou: /[\u0223]/g,1211            oo: /[\uA74F]/g,1212            p: /[\u0070\u24DF\uFF50\u1E55\u1E57\u01A5\u1D7D\uA751\uA753\uA755]/g,1213            q: /[\u0071\u24E0\uFF51\u024B\uA757\uA759]/g,1214            r: /[\u0072\u24E1\uFF52\u0155\u1E59\u0159\u0211\u0213\u1E5B\u1E5D\u0157\u1E5F\u024D\u027D\uA75B\uA7A7\uA783]/g,1215            s: /[\u0073\u24E2\uFF53\u015B\u1E65\u015D\u1E61\u0161\u1E67\u1E63\u1E69\u0219\u015F\u023F\uA7A9\uA785\u1E9B]/g,1216            ss: /[\u00DF]/g,1217            t: /[\u0074\u24E3\uFF54\u1E6B\u1E97\u0165\u1E6D\u021B\u0163\u1E71\u1E6F\u0167\u01AD\u0288\u2C66\uA787]/g,1218            tz: /[\uA729]/g,1219            u: /[\u0075\u24E4\uFF55\u00F9\u00FA\u00FB\u0169\u1E79\u016B\u1E7B\u016D\u00FC\u01DC\u01D8\u01D6\u01DA\u1EE7\u016F\u0171\u01D4\u0215\u0217\u01B0\u1EEB\u1EE9\u1EEF\u1EED\u1EF1\u1EE5\u1E73\u0173\u1E77\u1E75\u0289]/g,1220            v: /[\u0076\u24E5\uFF56\u1E7D\u1E7F\u028B\uA75F\u028C]/g,1221            vy: /[\uA761]/g,1222            w: /[\u0077\u24E6\uFF57\u1E81\u1E83\u0175\u1E87\u1E85\u1E98\u1E89\u2C73]/g,1223            x: /[\u0078\u24E7\uFF58\u1E8B\u1E8D]/g,1224            y: /[\u0079\u24E8\uFF59\u1EF3\u00FD\u0177\u1EF9\u0233\u1E8F\u00FF\u1EF7\u1E99\u1EF5\u01B4\u024F\u1EFF]/g,1225            z: /[\u007A\u24E9\uFF5A\u017A\u1E91\u017C\u017E\u1E93\u1E95\u01B6\u0225\u0240\u2C6C\uA763]/g1226        };1227        for (let x in diacriticsMap) {1228            // Iterate through each keys in the above object and perform a replace1229            str = str.replace(diacriticsMap[x], x);1230        }1231        return str;1232    },1233    UUID: function () {1234        let lut = [];1235        for (let i = 0; i < 256; i++) {1236            lut[i] = (i < 16 ? '0' : '') + (i).toString(16);1237        }1238        let d0 = Math.random() * 0xffffffff | 0;1239        let d1 = Math.random() * 0xffffffff | 0;1240        let d2 = Math.random() * 0xffffffff | 0;1241        let d3 = Math.random() * 0xffffffff | 0;1242        let token = lut[d0 & 0xff] + lut[d0 >> 8 & 0xff] + lut[d0 >> 16 & 0xff] + lut[d0 >> 24 & 0xff] + '-' +1243            lut[d1 & 0xff] + lut[d1 >> 8 & 0xff] + '-' + lut[d1 >> 16 & 0x0f | 0x40] + lut[d1 >> 24 & 0xff] + '-' +1244            lut[d2 & 0x3f | 0x80] + lut[d2 >> 8 & 0xff] + '-' + lut[d2 >> 16 & 0xff] + lut[d2 >> 24 & 0xff] +1245            lut[d3 & 0xff] + lut[d3 >> 8 & 0xff] + lut[d3 >> 16 & 0xff] + lut[d3 >> 24 & 0xff];1246        return token;1247    },1248    CPULoad: function (avgTime, callback) {1249        function cpuAverage() {1250            //Initialise sum of idle and time of cores and fetch CPU info1251            let totalIdle = 0, totalTick = 0;1252            let cpus = os.cpus();1253            //Loop through CPU cores1254            for (let i = 0, len = cpus.length; i < len; i++) {1255                //Select CPU core1256                let cpu = cpus[i];1257                //Total up the time in the cores tick1258                for (type in cpu.times) {1259                    totalTick += cpu.times[type];1260                }1261                //Total up the idle time of the core1262                totalIdle += cpu.times.idle;1263            }1264            //Return the average Idle and Tick times1265            return {idle: totalIdle / cpus.length, total: totalTick / cpus.length};1266        }1267        this.samples = [];1268        this.samples[1] = cpuAverage();1269        this.refresh = setInterval(() => {1270            this.samples[0] = this.samples[1];1271            this.samples[1] = cpuAverage();1272            var totalDiff = this.samples[1].total - this.samples[0].total;1273            var idleDiff = this.samples[1].idle - this.samples[0].idle;1274            callback(1 - idleDiff / totalDiff);1275        }, avgTime);1276    }1277};...

Full Screen

Full Screen

DragHtmlElements_AnimateCC_or.js

Source:DragHtmlElements_AnimateCC_or.js Github

copy

Full Screen

1(function (cjs, an) {2    var p; // shortcut to reference prototypes3    var lib = {}; var ss = {}; var img = {};4    lib.ssMetadata = [];5    // symbols:6    // helper functions:7    // stage content:8    (lib.DragHtmlElements_AnimateCC_2 = function (mode, startPosition, loop) {9        this.initialize(mode, startPosition, loop, {});10        // timeline functions:11        this.frame_0 = function () {12            if (!container) {13                var container = new createjs.Container(); // globla container14            }15            function parseXmlStr(xmlStr) {16                var parseXml;17                if (typeof window.DOMParser != "undefined") {18                    parseXml = function (xmlStr) {19                        return (new window.DOMParser()).parseFromString(xmlStr, "text/xml");20                    };21                } else if (typeof window.ActiveXObject != "undefined" && new window.ActiveXObject("Microsoft.XMLDOM")) {22                    parseXml = function (xmlStr) {23                        var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");24                        xmlDoc.async = "false";25                        xmlDoc.loadXML(xmlStr);26                        return xmlDoc;27                    };28                } else {29                    return false;30                }31                try {32                    return parseXml(xmlStr);33                } catch (e) {34                    return xmlStr;35                }36            }37            ////////////////////////////test purpose========================38            ////var s = new XMLSerializer();39            ////var newXmlStr = s.serializeToString(stage.children[0].Arcadix.ResultArcadix_Data_Xml);40            ////console.log(newXmlStr);41            ////////////////////////////test purpose========================42            //this.Arcadix = {};43            //this.Arcadix["InitialArcadix_Data"] =44            //    {45            //        'BckgElements': [46            //            {47            //                'BckgElementId': 'Id1',48            //                'Type': 'Img',49            //                'XPosition': 488,50            //                'YPosition': 251,51            //                'Img': 'http://192.168.129.120:8082/editor/main/dragdrophtml/Elephant.png'52            //            },53            //            {   54            //                'BckgElementId': 'Id2',55            //                'Type': 'Img',56            //                'XPosition': 488,57            //                'YPosition': 251,58            //                'Img': 'http://192.168.129.120:8082/editor/main/dragdrophtml/butterfly.png'59            //            }60            //        ],61            //        'ChildElements': [62            //            {63            //                'ChildElementId': 'CId2',64            //                'Type': 'TextBox',65            //                'XPosition': 30,66            //                'YPosition': 30,67            //                'BcgElementId': 'Id1',68            //                'Status' : 'Control',69            //'Status' : 'Placeholder'70            //                'ElmXml': '<Element iElementTypeId="5" iElementType="Input" iElementId="510776" iElementAccessId="510776" cHasMeasurementPrefix=" " vMeasurementUnit="" cIsCaseSensitive="N" iWidthInPixel="15" iNumberOfInputDisplay="0" cIsNumber="Y" cIsFormula="N" cIsSimpleCalculator="N" cHasLeftFixedFormula="N" cIsEditableInput="N" iTextFieldType="4" dWrongPoint="" dNotAnsweredPoint="" dCorrectPoint=""><Value iDisplayOrder="2" vTolerance="0.00" iElementInputValueId="95116">4</Value></Element>'71            //            },72            //            {73            //                'ChildElementId': 'CId3',74            //                'Type': 'TextBox',75            //                'XPosition': 40,76            //                'YPosition': 40,77            //                'BcgElementId': 'Id1',78            //                'ElmXml': '<Element iElementTypeId="5" iElementType="Input" iElementId="510777" iElementAccessId="510776" cHasMeasurementPrefix=" " vMeasurementUnit="" cIsCaseSensitive="N" iWidthInPixel="15" iNumberOfInputDisplay="0" cIsNumber="Y" cIsFormula="N" cIsSimpleCalculator="N" cHasLeftFixedFormula="N" cIsEditableInput="N" iTextFieldType="4" dWrongPoint="" dNotAnsweredPoint="" dCorrectPoint=""><Value iDisplayOrder="2" vTolerance="0.00" iElementInputValueId="95116">4</Value></Element>'79            //            },80            //            {81            //                'ChildElementId': 'CId4',82            //                'Type': 'DropDown',83            // 'ObjType' : 'placeholder',84            //                'XPosition': 60,85            //                'YPosition': 60,86            //                'Options': ['Eye', 'Teeth', 'Tail', 'Ear', 'Leg'],87            //                'BcgElementId': 'Id1',88            //                'ElmXml': '<Element iElementTypeId="6" iElementType="Dropdown" iElementId="508255" iElementAccessId="508255" cIsRandomizedDisplay="N" cIsFixedWidth="N" iWidth="0" vDefaultText="" dCorrectPoint="" dNotAnsweredPoint="" cIsDefaultTextEmpty="Y" cHidePleaseSelect="N"><Value iDisplayOrder="1" cIsCorrectValue="N" dWrongPoint="" iElementDropDownValueId="92426">stolz</Value><Value iDisplayOrder="2" cIsCorrectValue="N" dWrongPoint="" iElementDropDownValueId="92427">dumm</Value><Value iDisplayOrder="3" cIsCorrectValue="Y" dWrongPoint="" iElementDropDownValueId="92428">bös</Value><Value iDisplayOrder="4" cIsCorrectValue="N" dWrongPoint="" iElementDropDownValueId="92429">nett</Value><Value iDisplayOrder="5" cIsCorrectValue="N" dWrongPoint="" iElementDropDownValueId="92430">frech</Value></Element>'89            //            },90            //            {91            //                'ChildElementId': 'CId5',92            //                'Type': 'DropDown',93            //                'XPosition': 60,94            //                'YPosition': 60,95            //                'Options': ['Eye', 'Teeth', 'Tail', 'Ear', 'Leg'],96            //                'BcgElementId': 'Id1',97            //                'ElmXml': '<Element iElementTypeId="6" iElementType="Dropdown" iElementId="508256" iElementAccessId="508255" cIsRandomizedDisplay="N" cIsFixedWidth="N" iWidth="0" vDefaultText="" dCorrectPoint="" dNotAnsweredPoint="" cIsDefaultTextEmpty="Y" cHidePleaseSelect="N"><Value iDisplayOrder="1" cIsCorrectValue="N" dWrongPoint="" iElementDropDownValueId="92426">stolz</Value><Value iDisplayOrder="2" cIsCorrectValue="N" dWrongPoint="" iElementDropDownValueId="92427">dumm</Value><Value iDisplayOrder="3" cIsCorrectValue="Y" dWrongPoint="" iElementDropDownValueId="92428">bös</Value><Value iDisplayOrder="4" cIsCorrectValue="N" dWrongPoint="" iElementDropDownValueId="92429">nett</Value><Value iDisplayOrder="5" cIsCorrectValue="N" dWrongPoint="" iElementDropDownValueId="92430">frech</Value></Element>'98            //            },99            //            {100            //                'ChildElementId': 'CId6',101            //                'Type': 'DropDown',102            //                'XPosition': 60,103            //                'YPosition': 60,104            //                'Options': ['Eye', 'Teeth', 'Tail', 'Ear', 'Leg'],105            //                'BcgElementId': 'Id1',106            //                'ElmXml': '<Element iElementTypeId="6" iElementType="Dropdown" iElementId="508257" iElementAccessId="508255" cIsRandomizedDisplay="N" cIsFixedWidth="N" iWidth="0" vDefaultText="" dCorrectPoint="" dNotAnsweredPoint="" cIsDefaultTextEmpty="Y" cHidePleaseSelect="N"><Value iDisplayOrder="1" cIsCorrectValue="N" dWrongPoint="" iElementDropDownValueId="92426">stolz</Value><Value iDisplayOrder="2" cIsCorrectValue="N" dWrongPoint="" iElementDropDownValueId="92427">dumm</Value><Value iDisplayOrder="3" cIsCorrectValue="Y" dWrongPoint="" iElementDropDownValueId="92428">bös</Value><Value iDisplayOrder="4" cIsCorrectValue="N" dWrongPoint="" iElementDropDownValueId="92429">nett</Value><Value iDisplayOrder="5" cIsCorrectValue="N" dWrongPoint="" iElementDropDownValueId="92430">frech</Value></Element>'107            //            }108            //        ]109            //    };110            this.Arcadix = {};111            this.Arcadix['InitialArcadix_HasSidebar'] = 'Y';112            this.Arcadix['ResultArcadix_Data'] = {};113            this.Arcadix['InitialArcadix_Data'] = {114                "BckgElements": [],115                "ChildElements": []116            };117            this.Arcadix['InitialArcadix_Mode'] = 'edit';118            this.Arcadix['ResultArcadix_Data_Xml'] = '';119            this.clearStage = function () {120                container.removeAllChildren();121                stage.update();122            }123            this.clearAllElements = function () {124                debugger125                let contIndex = [];126                for (i = 0; i < stage.children.length; i++) {127                    if (i != 0) {128                        stage.children[i].removeAllChildren();129                    }130                }131            }132            this.clearBckgElements = function () {133                debugger134                if (stage.children[1]) {135                    for (let i = 0; i < stage.children[1].children.length; i++) {136                        let bckElement = stage.children[0].Arcadix['InitialArcadix_Data']['BckgElements'].find(a => a['BckgElementId'] === stage.children[1].children[i]['BckgElementId']);137                        if (!bckElement) {138                            stage.children[1].removeChildAt(i);139                        }140                    }141                }142            }143            this.clearChildElements = function () {144                debugger145                if (stage.children && stage.children.length > 2) {146                    for (let i = 2; i < stage.children.length; i++) {147                        //  try {148                        let childElement = stage.children[0].Arcadix['InitialArcadix_Data']['ChildElements'].find(a => a['ChildElementId'] === stage.children[i]['ChildElementId']);149                        //} catch (e){150                        //    console.log('index', i);151                        //}152                        if (!childElement) {153                            stage.removeChildAt(i);154                        }155                    }156                }157            }158            this.updateStage = function () {159                debugger160                this.clearBckgElements();161                this.clearChildElements();162            }163            this.generateElements = function () {164                debugger165                this.updateStage();166                //////================================================167                if (stage.children[0].Arcadix['InitialArcadix_Data'] && stage.children[0].Arcadix['InitialArcadix_Data'].BckgElements) {168                    for (let i = 0; i < stage.children[0].Arcadix['InitialArcadix_Data'].BckgElements.length; i++) {169                        let BckgElement = new Image();170                        BckgElement.src = stage.children[0].Arcadix['InitialArcadix_Data'].BckgElements[i].Img;171                        BckgElement.onload = function (event) {172                            jsonBckElementCreator(stage.children[0].Arcadix['InitialArcadix_Data'].BckgElements[i], event, stage.children[0].Arcadix['InitialArcadix_Data'].BckgElements[i].BckgElementId);173                        }174                    }175                }176                if (stage.children[0].Arcadix['InitialArcadix_Data'] && stage.children[0].Arcadix['InitialArcadix_Data'].ChildElements) {177                    debugger178                    for (let i = 0; i < stage.children[0].Arcadix['InitialArcadix_Data'].ChildElements.length; i++) {                      179                        objectCreator(stage.children[0].Arcadix['InitialArcadix_Data'].ChildElements[i]);180                    }181                }182                ////////==============test purpose==================183                var active = ''184                185                //var evntSwitchImg = new Image();186                //evntSwitchImg.src = 'http://localhost/Intranet/Data/Repo/Image/97/626385_Image_1.png';187                //evntSwitchImg.onload = function (evnt) {188                //    var evntSwitchBitmap = new createjs.Bitmap(evnt.target);189                //    evntSwitchBitmap.x = 200;190                //    evntSwitchBitmap.y = 50;191                //    container.addChild(evntSwitchBitmap);192                //    evntSwitchBitmap.on('click', function (evnt) {193                //        if (active === '') {194                //            active = 'pressmove';195                //            for (var i = 0; i < stage.children.length; i++) {196                //                if (stage.children[i].hasOwnProperty('ChildElementId')) {197                //                    if (stage.children[i].children) {198                //                        stage.children[i].children[0].addEventListener('pressmove', pressmoveEvt);199                //                        // stage.children[i].children[0].off('dblclick', dblclickEvt);200                //                    }201                //                }202                //            }203                //        } else if (active === 'pressmove') {204                //            for (var i = 0; i < stage.children.length; i++) {205                //                if (stage.children[i].hasOwnProperty('ChildElementId')) {206                //                    if (stage.children[i].children) {207                //                        stage.children[i].children[0].addEventListener('dblclick', dblclickEvt);208                //                        stage.children[i].children[0].removeEventListener('pressmove', pressmoveEvt);209                //                        active = 'dblclick';210                //                    }211                //                }212                //            }213                //        } else if (active === 'dblclick') {214                //            for (var i = 0; i < stage.children.length; i++) {215                //                if (stage.children[i].hasOwnProperty('ChildElementId')) {216                //                    if (stage.children[i].children) {217                //                        stage.children[i].children[0].addEventListener('pressmove', pressmoveEvt);218                //                        stage.children[i].children[0].removeEventListener('dblclick', dblclickEvt);219                //                        active = 'pressmove';220                //                    }221                //                }222                //            }223                //        }224                //    })225                //}226                function pressmoveEvt(evt) {227                   // HtmlPlaceholder.on('pressmove', function (evt) {228                        //if (!dblClicked) {229                        var p = evt.currentTarget.parent.globalToLocal(evt.stageX, evt.stageY);230                        evt.currentTarget.x = p.x;231                        evt.currentTarget.y = p.y;232                        //text.x = p.x;233                        //text.y = p.y;234                        var objElement = stage.children[0].Arcadix.InitialArcadix_Data.ChildElements.find(a => a['ChildElementId'] === evt.target.ChildElementId);235                        container.setChildIndex(this, container.getNumChildren() - 1);236                        updatePosition(objElement, 'ChildElements', { x: p.x, y: p.y });237                        stage.update();238                        //}239                        //dblClicked = false;240                 //   });241                }242                function dblclickEvt(evt) {243                  //  HtmlPlaceholder.on('dblclick', function (evt) {244                      //  OpenInputPopup(this);245                  //  });246                }247                ///////============test purpose=====================248            }249            ////==============test purpose====================//250            this.LoadResult = function (data) {251                stage.children[0].Arcadix['ResultArcadix_Data_Xml'] = data;252            }253            ////==============test purpose=========end===========//254            this.LoadSolution = function () {255                console.log('running loadsolution');256                stage.children[0].Arcadix['InitialArcadix_HasSidebar'] = 'Y';257                if (stage.children[0].Arcadix['InitialArcadix_Mode'] && stage.children[0].Arcadix['InitialArcadix_Mode'] != '') {258                    if (stage.children[0].Arcadix['InitialArcadix_Mode'].toLowerCase() === 'edit' || stage.children[0].Arcadix['InitialArcadix_Mode'].toLowerCase() === 'solution') {259                        this.generateElements();260                    }261                }262            }263            this.LoadInitialize = function (data, mode) {264                // var data, mode;265                // this.Arcadix['InitialArcadix_Data'] = data;266                debugger267                if (mode == undefined || mode == '') {268                    if (!this.Arcadix['InitialArcadix_Mode'] && this.Arcadix['InitialArcadix_Mode'] != '') {269                        this.Arcadix['InitialArcadix_Mode'] = 'edit';270                    }271                    let sidebarJSON = data || {272                        'BckgElements': [],273                        'ChildElements': []274                    };275                    if (!this.Arcadix['ResultArcadix_Data'] || this.Arcadix['ResultArcadix_Data'] == '') {276                        this.Arcadix['ResultArcadix_Data'] = {};277                    }278                    //   this.frame_0(this.mergeJSON(data, AnimationJSON), 'edit');279                    if (data) {280                        stage.children[0].Arcadix['InitialArcadix_Data'] = this.mergeJSON(sidebarJSON, stage.children[0].Arcadix['InitialArcadix_Data']);281                        //  this.updateResult(); /// updating the InitialArcadix_Data after merging282                        stage.children[0].Arcadix['InitialArcadix_Mode'] = 'edit';283                    }284                    if (stage.children[0].Arcadix['InitialArcadix_Mode'] && stage.children[0].Arcadix['InitialArcadix_Mode'].toLowerCase() === 'display') {285                        //  stage.clearAllElements();286                        this.generateElements();287                    }288                    // this.generateElements();289                    if (window.parent.OnConstructLoadComplete) {290                        window.parent.OnConstructLoadComplete();291                    }292                    if (window.parent.OnAnimationLoadComplete) {293                        window.parent.OnAnimationLoadComplete();294                    }295                    //stage.update();296                    //	this.frame_0();297                }298                else {299                    let AnimationJSON = data || {300                        'BckgElements': [],301                        'ChildElements': []302                    };303                    if (!this.Arcadix['ResultArcadix_Data'] || this.Arcadix['ResultArcadix_Data'] == '') {304                        this.Arcadix['ResultArcadix_Data'] = {};305                    }306                    stage.children[0].Arcadix['InitialArcadix_Data'] = this.mergeJSON(data, AnimationJSON);307                    stage.children[0].Arcadix['InitialArcadix_Mode'] = mode.toLowerCase();308                    this.generateElements();309                    if (window.parent.OnConstructLoadComplete) {310                        window.parent.OnConstructLoadComplete();311                    }312                    if (window.parent.OnAnimationLoadComplete) {313                        window.parent.OnAnimationLoadComplete();314                    }315                }316            }317            window.setTimeout(this.LoadInitialize.bind(this), 100);318            this.mergeJSON = function (SideBarJSON, AnimationJSON) {319                if (AnimationJSON.Elements && AnimationJSON.BckgElements != null && AnimationJSON.BckgElements.length > 0) {320                    var resultObj = {321                        BckgElementId: SideBarJSON.BckgElements.map(item => {322                            return Object.assign(item, AnimationJSON.BckgElements.find(a => a['BckgElementId'] === item['BckgElementId']))323                        }), ChildElements: SideBarJSON.ChildElements.map(item => {324                            return Object.assign(item, AnimationJSON.ChildElements.find(a => a['ChildElementId'] === item['ChildElementId']))325                        })326                    }327                } else {328                    return SideBarJSON;329                }330                ////console.log('result object after merging', JSON.stringify(resultObj));331                return resultObj;332            }333            this.GetData = function () {334                //  return stage.children[0].Arcadix;335                // var returnObj = stage.children[0].Arcadix;336                var returnObj = Object.assign({}, stage.children[0].Arcadix);337                if (returnObj['InitialArcadix_Data']['ChildElements']) {338                    for (var i = 0; i < returnObj['InitialArcadix_Data']['ChildElements'].length; i++) {339                        returnObj['InitialArcadix_Data']['ChildElements'][i]['StrElmXml'] = returnObj['InitialArcadix_Data']['ChildElements'][i]['ElmXml'] ? stringifyXML(returnObj['InitialArcadix_Data']['ChildElements'][i]['ElmXml']) : '';340                    }341                    return returnObj;342                } else {343                    return stage.children[0].Arcadix;344                }345            }346            function jsonBckElementCreator(element, evt, BckgElementId) {347                if (!stage.children[1].children.find(a => a['BckgElementId'] === BckgElementId)) {348                    BckElementBitmap = new createjs.Bitmap(evt.target);349                    container.addChild(BckElementBitmap);350                    BckElementBitmap.regX = BckElementBitmap.image.width / 2 | 0;351                    BckElementBitmap.regY = BckElementBitmap.image.height / 2 | 0;352                    jsonElement = stage.children[0].Arcadix['InitialArcadix_Data']['BckgElements'].find(a => a['BckgElementId'] === BckgElementId);353                    if (jsonElement['XPosition'] && jsonElement['YPosition']) {354                        BckElementBitmap.x = jsonElement['XPosition'];355                        BckElementBitmap.y = jsonElement['YPosition'];356                    }357                    if (stage.children[0].Arcadix['InitialArcadix_Mode'] && stage.children[0].Arcadix['InitialArcadix_Mode'].toLowerCase() === 'edit') {358                        BckElementBitmap.on('pressmove', function (evt) {359                            var p = evt.currentTarget.parent.globalToLocal(evt.stageX, evt.stageY);360                            evt.currentTarget.x = p.x;361                            evt.currentTarget.y = p.y;362                            updatePosition(element, 'BckgElements', evt.currentTarget);363                        });364                    }365                }366            }367            function OpenInputPopup(sourceElement,objParam) {368                window.parent.parent.LoadScripts({369                    ScriptsJSON: [window.parent.parent.JConfiguration.BaseUrl + "Applications/JIntranet/Tasks/Editor/EditorWorkArea/Objects/Element/Text/TextPopupPlugins/JInputProperty.js", window.parent.parent.JConfiguration.BaseUrl + "Applications/JIntranet/Tasks/Editor/EditorWorkArea/TextEditor/JTextEditorSidebarTemplate.js", window.parent.parent.JConfiguration.BaseUrl + "Framework/Controls/JValidator/JValidator.js"], LoadCompleteScripts: function () {370                        window.parent.parent.JLoadInputPopup(sourceElement, textPopupCallback, objParam);371                    }372                });373            }374            function updateAnswerXml(element) {375                debugger376                var parsedXml;377                if (!element['ElmXml'].URL || element['ElmXml'].URL == null) {378                    parsedXml = parseXmlStr(element['StrElmXml']);379                } else {380                    parsedXml = element['ElmXml'];381                }382                iElementId = parsedXml.getElementsByTagName("Element")[0].getAttribute('iElementId');383                iElementType = parsedXml.getElementsByTagName("Element")[0].getAttribute('iElementType');384                if (stage.children[0].Arcadix['ResultArcadix_Data_Xml'] === '' || stage.children[0].Arcadix['ResultArcadix_Data_Xml'] === undefined) {385                    stage.children[0].Arcadix['ResultArcadix_Data_Xml'] = document.implementation.createDocument("", "", null);386                    root = stage.children[0].Arcadix['ResultArcadix_Data_Xml'].createElement("AS");387                    stage.children[0].Arcadix['ResultArcadix_Data_Xml'].appendChild(root);388                }389                xmlDoc = document.implementation.createDocument("", "", null);390                let length = stage.children[0]['Arcadix']['ResultArcadix_Data_Xml'].getElementsByTagName('AS')[0].childNodes.length;391                let isExists = false;392                for (let i = 0; i < length; i++) {393                    if (stage.children[0]['Arcadix']['ResultArcadix_Data_Xml'].getElementsByTagName('AS')[0].childNodes[i].getElementsByTagName('VS')[0].innerHTML === iElementId) {394                        isExists = true;395                    }396                }397                if (!isExists) {398                    let AXml = xmlDoc.createElement("A");399                    let icXml = xmlDoc.createElement("iC");400                    icXml.setAttribute("ExclamatoryiC", '154134');401                    icXml.innerHTML = '154134';402                    let iEXml = xmlDoc.createElement("iE");403                    iEXml.innerHTML = iElementId;404                    let iETXml = xmlDoc.createElement("iET");405                    iETXml.innerHTML = iElementType;406                    let TXml = xmlDoc.createElement("T");407                    TXml.innerHTML = iElementType;408                    let CXml = xmlDoc.createElement("C");409                    CXml.innerHTML = '0';410                    let VSXml = xmlDoc.createElement("VS");411                    VSXml.setAttribute("ExclamatoryVID", '510776');412                    VSXml.setAttribute('iED', '1');413                    VSXml.setAttribute('iAC', '1');414                    AXml.appendChild(icXml);415                    AXml.appendChild(iEXml);416                    AXml.appendChild(TXml);417                    AXml.appendChild(CXml);418                    AXml.appendChild(VSXml);419                    xmlDoc.appendChild(AXml);420                    stage.children[0].Arcadix['ResultArcadix_Data_Xml'].getElementsByTagName('AS')[0].appendChild(AXml);421                }422            }423            function updateAnswerOnChange(evnt, iElementId) {424                console.log('evnt', evnt);425                //console.log(evnt);426                debugger427                for (i = 0; i < stage.children[0]['Arcadix']['ResultArcadix_Data_Xml'].getElementsByTagName('AS')[0].childNodes.length; i++) {428                    console.log("stage.children[0]['Arcadix']['ResultArcadix_Data_Xml'].getElementsByTagName('AS')[0].childNodes[i]", stage.children[0]['Arcadix']['ResultArcadix_Data_Xml'].getElementsByTagName('AS')[0].childNodes[i]);429                    if (stage.children[0]['Arcadix']['ResultArcadix_Data_Xml'].getElementsByTagName('AS')[0].childNodes[i].getElementsByTagName('iE')[0].innerHTML === evnt.currentTarget.id) {430                        stage.children[0]['Arcadix']['ResultArcadix_Data_Xml'].getElementsByTagName('AS')[0].childNodes[i].getElementsByTagName('VS')[0].innerHTML = '';431                        xmlDoc = document.implementation.createDocument("", "", null);432                        valueXml = xmlDoc.createElement('V');433                        if (evnt.target.tagName === 'SELECT') {434                            valueXml.innerHTML = evnt.currentTarget.options[evnt.currentTarget.selectedIndex].text;435                        } else {436                            valueXml.innerHTML = evnt.currentTarget.value;437                        }438                        stage.children[0]['Arcadix']['ResultArcadix_Data_Xml'].getElementsByTagName('AS')[0].childNodes[i].getElementsByTagName('VS')[0].appendChild(valueXml);439                        if (evnt.target.tagName === 'SELECT') {440                            vidXml = xmlDoc.createElement('VID');441                            vidXml.innerHTML = evnt.currentTarget.value;442                            stage.children[0]['Arcadix']['ResultArcadix_Data_Xml'].getElementsByTagName('AS')[0].childNodes[i].getElementsByTagName('VS')[0].appendChild(vidXml);443                        }444                    }445                }446            }447            function stringifyXML(xml) {448                var s = new XMLSerializer();449                var newXmlStr = s.serializeToString(xml);450                return newXmlStr;451            }452            function jsonChildElmtCreator(element) {453                updateAnswerXml(element);454                console.log('element', element);455                var parsedXml;456                if (!element['ElmXml'].URL || element['ElmXml'].URL == null) {457                    parsedXml = parseXmlStr(element['StrElmXml']);458                } else {459                    parsedXml = element['ElmXml'];460                }461                iElementId = parsedXml.getElementsByTagName("Element")[0].getAttribute('iElementId');462                iElementType = parsedXml.getElementsByTagName("Element")[0].getAttribute('iElementType');463                var inp;464                if (iElementType && iElementType === 'Input') {465                    inp = document.createElement('input');466                    inp.id = iElementId;467                    inp.setAttribute('type', 'text');468                    inp.style.position = "absolute";469                    inp.addEventListener('change', function (evt) {470                        updateAnswerOnChange(evt, iElementId);471                    });472                    inp.style.top = 0;473                    inp.style.left = 0;474                } else if (iElementType && iElementType === 'Dropdown') {475                    inp = document.createElement('select');476                    inp.id = iElementId;477                    inp.style.position = "absolute";478                    inp.style.width = '150px';479                    inp.addEventListener('change', function (evt) {480                        updateAnswerOnChange(evt, iElementId);481                    });482                    inp.style.top = 0;483                    inp.style.left = 0;484                    let options = parsedXml.getElementsByTagName("Element")[0].childNodes;485                    if (options) {486                        for (let i = 0; i < options.length; i++) {487                            var option = document.createElement("option");488                            option.setAttribute("value", options[i].getAttribute('AnswerValue'));489                            option.text = options[i].getAttribute('AnswerValue');490                            inp.appendChild(option);491                        }492                    }493                }494                console.log('inp', inp);495                document.body.appendChild(inp);496                var gg = new createjs.DOMElement(inp);497                gg.x = element['XPosition'];498                gg.y = element['YPosition'];499                container.addChild(gg);500                stage.update();501            }502            var dblClicked = false;503            function objectCreator(element) {504                if (stage.children[0].Arcadix['InitialArcadix_Mode'] && stage.children[0].Arcadix['InitialArcadix_Mode'].toLowerCase() === 'display') {505                    jsonChildElmtCreator(element);506                } else {507                    if (element['ObjType'] === 'placeholder') {508                        //let ChildElement = new Image();509                        //ChildElement.src = element.Img;510                        //ChildElement.onload = function (event) {511                        jsonElementPlaceholderCreator(element);512                        // }513                    } else {514                        let ChildElement = new Image();515                        ChildElement.src = element.Img;516                        ChildElement.onload = function (event) {517                            jsonHtmlplaceholderCreator(element, event);518                        }519                    }520                }521            }522            function jsonHtmlplaceholderCreator(element, evt) {523                debugger524                //var rect = new createjs.Rectangle(0, 0, 180, 30);525                var plhldrContainer;526             527                var iElementId = element['ChildElementId'];528                if (!stage.children.find(a => a['ChildElementId'] === iElementId)) {529                    iElementType = element['Type'];530                    if (!document.getElementById(iElementId)) {531                        if (!stage.children.find(a => a['ChildElementId'] === iElementId)) {532                            plhldrContainer = new createjs.Container();533                            plhldrContainer['ChildElementId'] = iElementId;534                            if (element['XPosition'] && element['YPosition']) {535                                plhldrContainer.x = element['XPosition'];536                                plhldrContainer.y = element['YPosition'];537                            } else {538                                plhldrContainer.x = 200;539                                plhldrContainer.y = 50;540                            }541                            stage.addChild(plhldrContainer);542                        }543                        containerIndex = stage.children.findIndex(a => a['ChildElementId'] === iElementId);544                        HtmlPlaceholder = new createjs.Bitmap(evt.target);545                        HtmlPlaceholder['ChildElementId'] = element['ChildElementId'];546                        //HtmlPlaceholder.regX = HtmlPlaceholder.image.width / 2;547                        //HtmlPlaceholder.regY = HtmlPlaceholder.image.height / 2;548                       549                        stage.children[containerIndex].addChild(HtmlPlaceholder);550                551                        if (stage.children[0].Arcadix['InitialArcadix_Mode'] && stage.children[0].Arcadix['InitialArcadix_Mode'].toLowerCase() === 'display') {552                            //HtmlPlaceholder.on('dblclick', function (evt) {553                            //    OpenInputPopup(this);554                            //});555                        }556                        //HtmlPlaceholder.on('click', function (evt) {557                            558                        //})559                        HtmlPlaceholder.on('pressmove', function (evt) {560                            //if (!dblClicked) {561                            var p = evt.currentTarget.parent.globalToLocal(evt.stageX, evt.stageY);562                            evt.currentTarget.x = p.x;563                            evt.currentTarget.y = p.y;564                            //text.x = p.x;565                            //text.y = p.y;566                            container.setChildIndex(this, container.getNumChildren() - 1);567                            updatePosition(element, 'ChildElements', { x: p.x, y: p.y });568                            stage.update();569                            //}570                            //dblClicked = false;571                        });572                        //HtmlPlaceholder.on('pressmove', function (evt) {573                        //    //if (!dblClicked) {574                        //        var p = evt.currentTarget.parent.globalToLocal(evt.stageX, evt.stageY);575                        //        evt.currentTarget.x = p.x;576                        //        evt.currentTarget.y = p.y;577                        //        //text.x = p.x;578                        //        //text.y = p.y;579                        //        container.setChildIndex(this, container.getNumChildren() - 1);580                        //        updatePosition(element, 'ChildElements', { x: p.x, y: p.y });581                        //        stage.update();582                        //    //}583                        //    //dblClicked = false;584                        //});585                        stage.update();586                    }587                }588            }589            function textPopupCallback(objJson, objParam) {590                debugger591              //  var EmlXml = parseXml(JSONToXml(objJson, 'input'));592                var ElmntIndex = stage.children[0].Arcadix.InitialArcadix_Data.ChildElements.findIndex(a => a['ChildElementId'] === objParam['ChildElementId']);593                // stage.children[0].Arcadix.InitialArcadix_Data.ChildElements[ElmntIndex]['ElmXml'] = EmlXml;594                var StagedElmIndex = stage.children.findIndex(a => a['ChildElementId'] == objParam['ChildElementId']);595                stage.removeChildAt(StagedElmIndex);596                var inpHtml = getHtmlElement('textbox', objJson);597                getImgPathFromHtml(inpHtml.outerHTML, { type: 'textbox', ChildElementId: objParam['ChildElementId']} , ImagepathCallback);598            }599            function ImagepathCallback(objJson, objParams) {600                var ImgPath = objJson.ConvertHtmlToImage.ImagePath;601                var elmIndex = stage.children[0].Arcadix.InitialArcadix_Data.ChildElements.findIndex(a => a['ChildElementId'] === objParams['ChildElementId']);602                stage.children[0].Arcadix.InitialArcadix_Data.ChildElements[elmIndex]['Img'] = ImgPath;603                var newHtmlImg = new Image();604                newHtmlImg.src = ImgPath;605                newHtmlImg.onload = function (event) {606                    jsonHtmlplaceholderCreator(stage.children[0].Arcadix.InitialArcadix_Data.ChildElements[elmIndex], event);607                }608               609            }610            function getHtmlElement(iElementType,objJson) {611                //function ControlToPngCreator(iElementType, uploadControlPng) {612                    var inp;613                    if (iElementType && iElementType === 'textbox') {614                        inp = document.createElement('input');615                        // inp.id = iElementId;616                        inp.setAttribute('type', 'text');617                        inp.setAttribute('value', objJson.Values[0].AnswerValue);618                        // inp.style.position = "absolute";619                        //inp.addEventListener('change', function (evt) {620                        //    updateAnswerOnChange(evt, iElementId);621                        //});622                        //inp.style.top = 0;623                        //inp.style.left = 0;624                    } else if (iElementType && iElementType === 'dropdown') {625                        inp = document.createElement('select');626                        //   inp.id = iElementId;627                        //inp.style.position = "absolute";628                        inp.style.width = '150px';629                        //inp.addEventListener('change', function (evt) {630                        //    updateAnswerOnChange(evt, iElementId);631                        //});632                        //inp.style.top = 0;633                        //inp.style.left = 0;634                        //let options = parsedXml.getElementsByTagName("Element")[0].childNodes;635                        //if (options) {636                        //    for (let i = 0; i < options.length; i++) {637                        //var option = document.createElement("option");638                        //option.setAttribute("value", 'test');639                        //option.text = '          >'640                        //inp.appendChild(option);641                        //    }642                        //}643                    }644                    return inp;645                    //  return html2Png(inp);646                    // html2Png(inp = inp, uploadControlPng = uploadControlPng, type = iElementType);647                    //$('#html-content-inner').html('');648                    //$('#html-content-inner').html(inp);649                   // getImgPathFromHtml(inp, iElementType);650                    // domToImage(document.getElementById('html-content-inner'), uploadControlPng = uploadControlPng, type = iElementType);651            //    }652            }653            function getImgPathFromHtml(strHtml, objParam, ImagepathCallback) {654                debugger655                var strNewHtml = window.parent.ReplaceStringForXML(strHtml);656                //var strNewHtml = strHtml.replace(/\"/g, '\\"');657                window.parent.parent.JEditorWorkArea_ConvertHtmlToImage(strNewHtml, ImagepathCallback, objParam);658            }659            function jsonplaceholderCreator(element) {660                var rect = new createjs.Rectangle(0, 0, 180, 30);661                var plhldrContainer;662                var parsedXml;663                if (!element['ElmXml'].URL || element['ElmXml'].URL == null) {664                    parsedXml = parseXmlStr(element['StrElmXml']);665                } else {666                    parsedXml = element['ElmXml'];667                }668                iElementId = parsedXml.getElementsByTagName("Element")[0].getAttribute('iElementId');669                if (!stage.children.find(a => a['ChildElementId'] === iElementId)) {670                    iElementType = parsedXml.getElementsByTagName("Element")[0].getAttribute('iElementType');671                    if (!document.getElementById(iElementId)) {672                        if (!stage.children.find(a => a['ChildElementId'] === iElementId)) {673                            plhldrContainer = new createjs.Container();674                            plhldrContainer['ChildElementId'] = iElementId;675                            if (element['XPosition'] && element['YPosition']) {676                                plhldrContainer.x = element['XPosition'];677                                plhldrContainer.y = element['YPosition'];678                            } else {679                                plhldrContainer.x = 100;680                                plhldrContainer.y = 50;  681                            }682                            stage.addChild(plhldrContainer);683                        }684                        containerIndex = stage.children.findIndex(a => a['ChildElementId'] === iElementId);685                        var bckgnd = new createjs.Shape();686                        bckgnd['ChildElementId'] = iElementId;687                        bckgnd.graphics.beginFill('#f2f2f2').drawRect(0, 0, rect.width, rect.height);688                        var text = new createjs.Text();689                        text.set({690                            text: iElementType,691                            textAlign: "center",692                            textBaseline: "middle",693                            x: 0,694                            y: 0695                        });696                        bckgnd.regX = rect.width / 2;697                        bckgnd.regY = rect.height / 2;698                        stage.children[containerIndex].addChild(bckgnd, text);699                        bckgnd.on('click', function () {700                            dblClicked = true;701                            console.log(' clicked..............');702                        })703                        if (stage.children[0].Arcadix['InitialArcadix_Mode'] && stage.children[0].Arcadix['InitialArcadix_Mode'].toLowerCase() === 'display') {704                            bckgnd.on('dblclick', function (evt) {705                                debugger706                                var item = stage.children.find(a => a['ChildElementId'] === evt.target.ChildElementId);707                                var stagedBckgnd = item.children[0];708                                stage.removeChild(item);709                                element['XPosition'] = stagedBckgnd.x;710                                element['YPosition'] = stagedBckgnd.y;711                                var childElementIndex = stage.children[0].Arcadix['InitialArcadix_Data']['ChildElements'].findIndex(a => a['ChildElementId'] === evt.target.ChildElementId);712                                stage.children[0].Arcadix['InitialArcadix_Data']['ChildElements'][childElementIndex]['ObjType'] = 'control';713                                jsonChildElmtCreator(element);714                            });715                        }716                        bckgnd.on('pressmove', function (evt) {717                            if (!dblClicked) {718                                var p = evt.currentTarget.parent.globalToLocal(evt.stageX, evt.stageY);719                                evt.currentTarget.x = p.x;720                                evt.currentTarget.y = p.y;721                                text.x = p.x;722                                text.y = p.y;723                                container.setChildIndex(this, container.getNumChildren() - 1);724                                updatePosition(element, 'ChildElements', { x: p.x, y: p.y });725                                stage.update();726                            }727                            dblClicked = false;728                        });729                        stage.update();730                    }731                }732            }733            function JSONToXml(json, type) {734                let xmlDoc = document.implementation.createDocument("", "", null);735                let ElmXml = xmlDoc.createElement('Element');736                for (let item in json) {737                    console.log('typeof txtJSON[item]', typeof json[item]);738                    if (typeof json[item] != 'object') {739                        ElmXml.setAttribute(item, json[item]);740                    }741                    else if (typeof json[item] == 'object') {742                        for (i = 0; i < json[item].length; i++) {743                            let valueXML = xmlDoc.createElement('Value');744                            for (valItem in json[item][i]) {745                                valueXML.setAttribute(valItem, json[item][i][valItem]);746                            }747                            ElmXml.appendChild(valueXML);748                        }749                    }750                    if (type.toLowerCase() === 'input') {751                        ElmXml.setAttribute('iElementTypeId', '5');752                        ElmXml.setAttribute('iElementType', 'Input');753                    }754                    else if (type.toLowerCase() === 'dropdown') {755                        ElmXml.setAttribute('iElementTypeId', '6');756                        ElmXml.setAttribute('iElementType', 'Dropdown');757                    }758                    ElmXml.setAttribute('iElementId', parent.GetUniqueId());759                }760                // console.log(serializeXML(ElmXml));761                return parseXml(serializeXML(ElmXml));762            }763            function parseXml(text) {764                if (text instanceof XMLDocument) {765                    return text;766                } else {767                    var parser = new DOMParser();768                    var xmlDoc = parser.parseFromString(text, "text/xml");769                    return xmlDoc;770                }771            }772            function jsonElementPlaceholderCreator(element) {773                var rect = new createjs.Rectangle(0, 0, 180, 30);774                var plhldrContainer;775                var parsedXml;776               // if (element['ElmXml'])     777                if (!element['ElmXml'].URL || element['ElmXml'].URL == null) {778                    parsedXml = parseXmlStr(element['StrElmXml']);779                } else {780                    parsedXml = element['ElmXml'];781                }782                iElementId = element['ChildElementId'];783                if (!stage.children.find(a => a['ChildElementId'] === iElementId)) {784                    iElementType = "Input";785                    if (!document.getElementById(iElementId)) {786                        if (!stage.children.find(a => a['ChildElementId'] === iElementId)) {787                            plhldrContainer = new createjs.Container();788                            plhldrContainer['ChildElementId'] = iElementId;789                            if (element['XPosition'] && element['YPosition']) {790                                plhldrContainer.x = element['XPosition'];791                                plhldrContainer.y = element['YPosition'];792                            } else {793                                plhldrContainer.x = 100;794                                plhldrContainer.y = 50;795                            }796                            stage.addChild(plhldrContainer);797                        }798                        containerIndex = stage.children.findIndex(a => a['ChildElementId'] === iElementId);799                        var bckgnd = new createjs.Shape();800                        bckgnd['ChildElementId'] = iElementId;801                        bckgnd.graphics.beginFill('#f2f2f2').drawRect(0, 0, rect.width, rect.height);802                        var text = new createjs.Text();803                        text.set({804                            text: iElementType,805                            textAlign: "center",806                            textBaseline: "middle",807                            x: 0,808                            y: 0809                        });810                        bckgnd.regX = rect.width / 2;811                        bckgnd.regY = rect.height / 2;812                        stage.children[containerIndex].addChild(bckgnd, text);813                        bckgnd.on('click', function () {814                            dblClicked = true;815                            console.log(' clicked..............');816                        })817                        //  if (stage.children[0].Arcadix['InitialArcadix_Mode'] && stage.children[0].Arcadix['InitialArcadix_Mode'].toLowerCase() === 'display') {818                        bckgnd.on('dblclick', function (evt) {819                            //var item = stage.children.find(a => a['ChildElementId'] === evt.target.ChildElementId);820                            //var stagedBckgnd = item.children[0];821                            //stage.removeChild(item);822                            //element['XPosition'] = stagedBckgnd.x;823                            //element['YPosition'] = stagedBckgnd.y;824                            //var childElementIndex = stage.children[0].Arcadix['InitialArcadix_Data']['ChildElements'].findIndex(a => a['ChildElementId'] === evt.target.ChildElementId);825                            //stage.children[0].Arcadix['InitialArcadix_Data']['ChildElements'][childElementIndex]['ObjType'] = 'control';826                            //jsonChildElmtCreator(element);827                            OpenInputPopup(this, { ChildElementId: evt.target.ChildElementId });828                        });829                        //  }830                        bckgnd.on('pressmove', function (evt) {831                            if (!dblClicked) {832                                var p = evt.currentTarget.parent.globalToLocal(evt.stageX, evt.stageY);833                                evt.currentTarget.x = p.x;834                                evt.currentTarget.y = p.y;835                                text.x = p.x;836                                text.y = p.y;837                                container.setChildIndex(this, container.getNumChildren() - 1);838                                updatePosition(element, 'ChildElements', { x: p.x, y: p.y });839                                stage.update();840                            }841                            dblClicked = false;842                        });843                        stage.update();844                    }845                } 846            }847            function updatePosition(objJsonElm, type, objevt) {848                console.log('updating position of element', objJsonElm);849                if (type === 'BckgElements') {850                    intelmIndex = stage.children[0].Arcadix['InitialArcadix_Data'][type].findIndex(a => a['BckgElementId'] === objJsonElm['BckgElementId']);851                    stage.children[0].Arcadix['InitialArcadix_Data'][type][intelmIndex]['XPosition'] = objevt.x;852                    stage.children[0].Arcadix['InitialArcadix_Data'][type][intelmIndex]['YPosition'] = objevt.y;853                }854                else if (type === 'ChildElements') {855                    intelmIndex = stage.children[0].Arcadix['InitialArcadix_Data'][type].findIndex(a => a['ChildElementId'] === objJsonElm['ChildElementId']);856                    stage.children[0].Arcadix['InitialArcadix_Data'][type][intelmIndex]['XPosition'] = objevt.x;857                    stage.children[0].Arcadix['InitialArcadix_Data'][type][intelmIndex]['YPosition'] = objevt.y;858                }859                console.log("after updating  stage.children[0].Arcadix['InitialArcadix_Data']", stage.children[0].Arcadix['InitialArcadix_Data']);860            }861            window.setTimeout(this.LoadInitialize.bind(this), 100);862            stage.addChild(container); // adding container to the stage863            stage.mouseMoveOutside = false;864            stage.enableMouseOver();865            stage.preventSelection = false;866            createjs.Touch.enable(stage /*, true, true*/);867            stage.update();868        }869        // actions tween:870        this.timeline.addTween(cjs.Tween.get(this).call(this.frame_0).wait(1));871    }).prototype = p = new cjs.MovieClip();872    p.nominalBounds = null;873    // library properties:874    lib.properties = {875        id: 'DAC903424E7A8A47BF57C8A648F8ADF8',876        width: 1120,877        height: 500,878        fps: 12,879        color: "#CCCCCC",880        opacity: 1.00,881        manifest: [],882        preloads: []883    };884    // bootstrap callback support:885    (lib.Stage = function (canvas) {886        createjs.Stage.call(this, canvas);887    }).prototype = p = new createjs.Stage();888    p.setAutoPlay = function (autoPlay) {889        this.tickEnabled = autoPlay;890    }891    p.play = function () { this.tickEnabled = true; this.getChildAt(0).gotoAndPlay(this.getTimelinePosition()) }892    p.stop = function (ms) { if (ms) this.seek(ms); this.tickEnabled = false; }893    p.seek = function (ms) { this.tickEnabled = true; this.getChildAt(0).gotoAndStop(lib.properties.fps * ms / 1000); }894    p.getDuration = function () { return this.getChildAt(0).totalFrames / lib.properties.fps * 1000; }895    p.getTimelinePosition = function () { return this.getChildAt(0).currentFrame / lib.properties.fps * 1000; }896    an.bootcompsLoaded = an.bootcompsLoaded || [];897    if (!an.bootstrapListeners) {898        an.bootstrapListeners = [];899    }900    an.bootstrapCallback = function (fnCallback) {901        an.bootstrapListeners.push(fnCallback);902        if (an.bootcompsLoaded.length > 0) {903            for (var i = 0; i < an.bootcompsLoaded.length; ++i) {904                fnCallback(an.bootcompsLoaded[i]);905            }906        }907    };908    an.compositions = an.compositions || {};909    an.compositions['DAC903424E7A8A47BF57C8A648F8ADF8'] = {910        getStage: function () { return exportRoot.getStage(); },911        getLibrary: function () { return lib; },912        getSpriteSheet: function () { return ss; },913        getImages: function () { return img; }914    };915    an.compositionLoaded = function (id) {916        an.bootcompsLoaded.push(id);917        for (var j = 0; j < an.bootstrapListeners.length; j++) {918            an.bootstrapListeners[j](id);919        }920    }921    an.getComposition = function (id) {922        return an.compositions[id];923    }924})(createjs = createjs || {}, AdobeAn = AdobeAn || {});...

Full Screen

Full Screen

DragHtmlElements_AnimateCC.js

Source:DragHtmlElements_AnimateCC.js Github

copy

Full Screen

1(function (cjs, an) {2    var p; // shortcut to reference prototypes3    var lib = {}; var ss = {}; var img = {};4    lib.ssMetadata = [];5    // symbols:6    // helper functions:7    // stage content:8    (lib.DragHtmlElements_AnimateCC_2 = function (mode, startPosition, loop) {9        this.initialize(mode, startPosition, loop, {});10        // timeline functions:11        this.frame_0 = function () {12            if (!container) {13                var container = new createjs.Container(); // globla container14            }15            function parseXmlStr(xmlStr) {16                var parseXml;17                if (typeof window.DOMParser != "undefined") {18                    parseXml = function (xmlStr) {19                        return (new window.DOMParser()).parseFromString(xmlStr, "text/xml");20                    };21                } else if (typeof window.ActiveXObject != "undefined" && new window.ActiveXObject("Microsoft.XMLDOM")) {22                    parseXml = function (xmlStr) {23                        var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");24                        xmlDoc.async = "false";25                        xmlDoc.loadXML(xmlStr);26                        return xmlDoc;27                    };28                } else {29                    return false;30                }31                try {32                    return parseXml(xmlStr);33                } catch (e) {34                    return xmlStr;35                }36            }37            ////////////////////////////test purpose========================38            ////var s = new XMLSerializer();39            ////var newXmlStr = s.serializeToString(stage.children[0].Arcadix.ResultArcadix_Data_Xml);40            ////console.log(newXmlStr);41            ////////////////////////////test purpose========================42            //this.Arcadix = {};43            //this.Arcadix["InitialArcadix_Data"] =44            //    {45            //        'BckgElements': [46            //            {47            //                'BckgElementId': 'Id1',48            //                'Type': 'Img',49            //                'XPosition': 488,50            //                'YPosition': 251,51            //                'Img': 'http://192.168.129.120:8082/editor/main/dragdrophtml/Elephant.png'52            //            },53            //            {   54            //                'BckgElementId': 'Id2',55            //                'Type': 'Img',56            //                'XPosition': 488,57            //                'YPosition': 251,58            //                'Img': 'http://192.168.129.120:8082/editor/main/dragdrophtml/butterfly.png'59            //            }60            //        ],61            //        'ChildElements': [62            //            {63            //                'ChildElementId': 'CId2',64            //                'Type': 'TextBox',65            //                'XPosition': 30,66            //                'YPosition': 30,67            //                'BcgElementId': 'Id1',68            //                'Status' : 'Control',69            //'Status' : 'Placeholder'70            //                'ElmXml': '<Element iElementTypeId="5" iElementType="Input" iElementId="510776" iElementAccessId="510776" cHasMeasurementPrefix=" " vMeasurementUnit="" cIsCaseSensitive="N" iWidthInPixel="15" iNumberOfInputDisplay="0" cIsNumber="Y" cIsFormula="N" cIsSimpleCalculator="N" cHasLeftFixedFormula="N" cIsEditableInput="N" iTextFieldType="4" dWrongPoint="" dNotAnsweredPoint="" dCorrectPoint=""><Value iDisplayOrder="2" vTolerance="0.00" iElementInputValueId="95116">4</Value></Element>'71            //            },72            //            {73            //                'ChildElementId': 'CId3',74            //                'Type': 'TextBox',75            //                'XPosition': 40,76            //                'YPosition': 40,77            //                'BcgElementId': 'Id1',78            //                'ElmXml': '<Element iElementTypeId="5" iElementType="Input" iElementId="510777" iElementAccessId="510776" cHasMeasurementPrefix=" " vMeasurementUnit="" cIsCaseSensitive="N" iWidthInPixel="15" iNumberOfInputDisplay="0" cIsNumber="Y" cIsFormula="N" cIsSimpleCalculator="N" cHasLeftFixedFormula="N" cIsEditableInput="N" iTextFieldType="4" dWrongPoint="" dNotAnsweredPoint="" dCorrectPoint=""><Value iDisplayOrder="2" vTolerance="0.00" iElementInputValueId="95116">4</Value></Element>'79            //            },80            //            {81            //                'ChildElementId': 'CId4',82            //                'Type': 'DropDown',83            // 'ObjType' : 'placeholder',84            //                'XPosition': 60,85            //                'YPosition': 60,86            //                'Options': ['Eye', 'Teeth', 'Tail', 'Ear', 'Leg'],87            //                'BcgElementId': 'Id1',88            //                'ElmXml': '<Element iElementTypeId="6" iElementType="Dropdown" iElementId="508255" iElementAccessId="508255" cIsRandomizedDisplay="N" cIsFixedWidth="N" iWidth="0" vDefaultText="" dCorrectPoint="" dNotAnsweredPoint="" cIsDefaultTextEmpty="Y" cHidePleaseSelect="N"><Value iDisplayOrder="1" cIsCorrectValue="N" dWrongPoint="" iElementDropDownValueId="92426">stolz</Value><Value iDisplayOrder="2" cIsCorrectValue="N" dWrongPoint="" iElementDropDownValueId="92427">dumm</Value><Value iDisplayOrder="3" cIsCorrectValue="Y" dWrongPoint="" iElementDropDownValueId="92428">bös</Value><Value iDisplayOrder="4" cIsCorrectValue="N" dWrongPoint="" iElementDropDownValueId="92429">nett</Value><Value iDisplayOrder="5" cIsCorrectValue="N" dWrongPoint="" iElementDropDownValueId="92430">frech</Value></Element>'89            //            },90            //            {91            //                'ChildElementId': 'CId5',92            //                'Type': 'DropDown',93            //                'XPosition': 60,94            //                'YPosition': 60,95            //                'Options': ['Eye', 'Teeth', 'Tail', 'Ear', 'Leg'],96            //                'BcgElementId': 'Id1',97            //                'ElmXml': '<Element iElementTypeId="6" iElementType="Dropdown" iElementId="508256" iElementAccessId="508255" cIsRandomizedDisplay="N" cIsFixedWidth="N" iWidth="0" vDefaultText="" dCorrectPoint="" dNotAnsweredPoint="" cIsDefaultTextEmpty="Y" cHidePleaseSelect="N"><Value iDisplayOrder="1" cIsCorrectValue="N" dWrongPoint="" iElementDropDownValueId="92426">stolz</Value><Value iDisplayOrder="2" cIsCorrectValue="N" dWrongPoint="" iElementDropDownValueId="92427">dumm</Value><Value iDisplayOrder="3" cIsCorrectValue="Y" dWrongPoint="" iElementDropDownValueId="92428">bös</Value><Value iDisplayOrder="4" cIsCorrectValue="N" dWrongPoint="" iElementDropDownValueId="92429">nett</Value><Value iDisplayOrder="5" cIsCorrectValue="N" dWrongPoint="" iElementDropDownValueId="92430">frech</Value></Element>'98            //            },99            //            {100            //                'ChildElementId': 'CId6',101            //                'Type': 'DropDown',102            //                'XPosition': 60,103            //                'YPosition': 60,104            //                'Options': ['Eye', 'Teeth', 'Tail', 'Ear', 'Leg'],105            //                'BcgElementId': 'Id1',106            //                'ElmXml': '<Element iElementTypeId="6" iElementType="Dropdown" iElementId="508257" iElementAccessId="508255" cIsRandomizedDisplay="N" cIsFixedWidth="N" iWidth="0" vDefaultText="" dCorrectPoint="" dNotAnsweredPoint="" cIsDefaultTextEmpty="Y" cHidePleaseSelect="N"><Value iDisplayOrder="1" cIsCorrectValue="N" dWrongPoint="" iElementDropDownValueId="92426">stolz</Value><Value iDisplayOrder="2" cIsCorrectValue="N" dWrongPoint="" iElementDropDownValueId="92427">dumm</Value><Value iDisplayOrder="3" cIsCorrectValue="Y" dWrongPoint="" iElementDropDownValueId="92428">bös</Value><Value iDisplayOrder="4" cIsCorrectValue="N" dWrongPoint="" iElementDropDownValueId="92429">nett</Value><Value iDisplayOrder="5" cIsCorrectValue="N" dWrongPoint="" iElementDropDownValueId="92430">frech</Value></Element>'107            //            }108            //        ]109            //    };110            this.Arcadix = {};111            this.Arcadix['InitialArcadix_HasSidebar'] = 'Y';112            this.Arcadix['ResultArcadix_Data'] = {};113            this.Arcadix['InitialArcadix_Data'] = {114                "BckgElements": [],115                "ChildElements": []116            };117            this.Arcadix['InitialArcadix_Mode'] = 'edit';118            this.Arcadix['ResultArcadix_Data_Xml'] = '';119            this.clearStage = function () {120                container.removeAllChildren();121                stage.update();122            }123            this.clearAllElements = function () {124                debugger125                let contIndex = [];126                for (i = 0; i < stage.children.length; i++) {127                    if (i != 0) {128                        stage.children[i].removeAllChildren();129                    }130                }131            }132            this.clearBckgElements = function () {133                debugger134                if (stage.children[1]) {135                    for (let i = 0; i < stage.children[1].children.length; i++) {136                        let bckElement = stage.children[0].Arcadix['InitialArcadix_Data']['BckgElements'].find(a => a['BckgElementId'] === stage.children[1].children[i]['BckgElementId']);137                        if (!bckElement) {138                            stage.children[1].removeChildAt(i);139                        }140                    }141                }142            }143            this.clearChildElements = function () {144                debugger145                if (stage.children && stage.children.length > 2) {146                    for (let i = 2; i < stage.children.length; i++) {147                        //  try {148                        let childElement = stage.children[0].Arcadix['InitialArcadix_Data']['ChildElements'].find(a => a['ChildElementId'] === stage.children[i]['ChildElementId']);149                        //} catch (e){150                        //    console.log('index', i);151                        //}152                        if (!childElement) {153                            stage.removeChildAt(i);154                        }155                    }156                }157            }158            this.updateStage = function () {159                debugger160                this.clearBckgElements();161                this.clearChildElements();162            }163            this.generateElements = function () {164                debugger165                this.updateStage();166                //////================================================167                if (stage.children[0].Arcadix['InitialArcadix_Data'] && stage.children[0].Arcadix['InitialArcadix_Data'].BckgElements) {168                    for (let i = 0; i < stage.children[0].Arcadix['InitialArcadix_Data'].BckgElements.length; i++) {169                        let BckgElement = new Image();170                        BckgElement.src = stage.children[0].Arcadix['InitialArcadix_Data'].BckgElements[i].Img;171                        BckgElement.onload = function (event) {172                            jsonBckElementCreator(stage.children[0].Arcadix['InitialArcadix_Data'].BckgElements[i], event, stage.children[0].Arcadix['InitialArcadix_Data'].BckgElements[i].BckgElementId);173                        }174                    }175                }176                if (stage.children[0].Arcadix['InitialArcadix_Data'] && stage.children[0].Arcadix['InitialArcadix_Data'].ChildElements) {177                    debugger178                    for (let i = 0; i < stage.children[0].Arcadix['InitialArcadix_Data'].ChildElements.length; i++) {                      179                        objectCreator(stage.children[0].Arcadix['InitialArcadix_Data'].ChildElements[i]);180                    }181                }182                ////////==============test purpose==================183                var active = ''184                185                var evntSwitchImg = new Image();186                evntSwitchImg.src = 'http://localhost/Intranet/Data/Repo/Image/97/626385_Image_1.png';187                evntSwitchImg.onload = function (evnt) {188                    var evntSwitchBitmap = new createjs.Bitmap(evnt.target);189                    evntSwitchBitmap.x = 200;190                    evntSwitchBitmap.y = 50;191                    container.addChild(evntSwitchBitmap);192                    evntSwitchBitmap.on('click', function (evnt) {193                        if (active === '') {194                            active = 'pressmove';195                            for (var i = 0; i < stage.children.length; i++) {196                                if (stage.children[i].hasOwnProperty('ChildElementId')) {197                                    if (stage.children[i].children) {198                                        stage.children[i].children[0].addEventListener('pressmove', pressmoveEvt);199                                        // stage.children[i].children[0].off('dblclick', dblclickEvt);200                                    }201                                }202                            }203                        } else if (active === 'pressmove') {204                            for (var i = 0; i < stage.children.length; i++) {205                                if (stage.children[i].hasOwnProperty('ChildElementId')) {206                                    if (stage.children[i].children) {207                                        stage.children[i].children[0].addEventListener('dblclick', dblclickEvt);208                                        stage.children[i].children[0].removeEventListener('pressmove', pressmoveEvt);209                                        active = 'dblclick';210                                    }211                                }212                            }213                        } else if (active === 'dblclick') {214                            for (var i = 0; i < stage.children.length; i++) {215                                if (stage.children[i].hasOwnProperty('ChildElementId')) {216                                    if (stage.children[i].children) {217                                        stage.children[i].children[0].addEventListener('pressmove', pressmoveEvt);218                                        stage.children[i].children[0].removeEventListener('dblclick', dblclickEvt);219                                        active = 'pressmove';220                                    }221                                }222                            }223                        }224                    })225                }226                function pressmoveEvt(evt) {227                   // HtmlPlaceholder.on('pressmove', function (evt) {228                        //if (!dblClicked) {229                        var p = evt.currentTarget.parent.globalToLocal(evt.stageX, evt.stageY);230                        evt.currentTarget.x = p.x;231                        evt.currentTarget.y = p.y;232                        //text.x = p.x;233                        //text.y = p.y;234                        var objElement = stage.children[0].Arcadix.InitialArcadix_Data.ChildElements.find(a => a['ChildElementId'] === evt.target.ChildElementId);235                        container.setChildIndex(this, container.getNumChildren() - 1);236                        updatePosition(objElement, 'ChildElements', { x: p.x, y: p.y });237                        stage.update();238                        //}239                        //dblClicked = false;240                 //   });241                }242                function dblclickEvt(evt) {243                  //  HtmlPlaceholder.on('dblclick', function (evt) {244                      //  OpenInputPopup(this);245                  //  });246                }247                ///////============test purpose=====================248            }249            ////==============test purpose====================//250            this.LoadResult = function (data) {251                stage.children[0].Arcadix['ResultArcadix_Data_Xml'] = data;252            }253            ////==============test purpose=========end===========//254            this.LoadSolution = function () {255                console.log('running loadsolution');256                stage.children[0].Arcadix['InitialArcadix_HasSidebar'] = 'Y';257                if (stage.children[0].Arcadix['InitialArcadix_Mode'] && stage.children[0].Arcadix['InitialArcadix_Mode'] != '') {258                    if (stage.children[0].Arcadix['InitialArcadix_Mode'].toLowerCase() === 'edit' || stage.children[0].Arcadix['InitialArcadix_Mode'].toLowerCase() === 'solution') {259                        this.generateElements();260                    }261                }262            }263            this.LoadInitialize = function (data, mode) {264                // var data, mode;265                // this.Arcadix['InitialArcadix_Data'] = data;266                debugger267                if (mode == undefined || mode == '') {268                    if (!this.Arcadix['InitialArcadix_Mode'] && this.Arcadix['InitialArcadix_Mode'] != '') {269                        this.Arcadix['InitialArcadix_Mode'] = 'edit';270                    }271                    let sidebarJSON = data || {272                        'BckgElements': [],273                        'ChildElements': []274                    };275                    if (!this.Arcadix['ResultArcadix_Data'] || this.Arcadix['ResultArcadix_Data'] == '') {276                        this.Arcadix['ResultArcadix_Data'] = {};277                    }278                    //   this.frame_0(this.mergeJSON(data, AnimationJSON), 'edit');279                    if (data) {280                        stage.children[0].Arcadix['InitialArcadix_Data'] = this.mergeJSON(sidebarJSON, stage.children[0].Arcadix['InitialArcadix_Data']);281                        //  this.updateResult(); /// updating the InitialArcadix_Data after merging282                        stage.children[0].Arcadix['InitialArcadix_Mode'] = 'edit';283                    }284                    if (stage.children[0].Arcadix['InitialArcadix_Mode'] && stage.children[0].Arcadix['InitialArcadix_Mode'].toLowerCase() === 'display') {285                        //  stage.clearAllElements();286                        this.generateElements();287                    }288                    // this.generateElements();289                    if (window.parent.OnConstructLoadComplete) {290                        window.parent.OnConstructLoadComplete();291                    }292                    if (window.parent.OnAnimationLoadComplete) {293                        window.parent.OnAnimationLoadComplete();294                    }295                    //stage.update();296                    //	this.frame_0();297                }298                else {299                    let AnimationJSON = data || {300                        'BckgElements': [],301                        'ChildElements': []302                    };303                    if (!this.Arcadix['ResultArcadix_Data'] || this.Arcadix['ResultArcadix_Data'] == '') {304                        this.Arcadix['ResultArcadix_Data'] = {};305                    }306                    stage.children[0].Arcadix['InitialArcadix_Data'] = this.mergeJSON(data, AnimationJSON);307                    stage.children[0].Arcadix['InitialArcadix_Mode'] = mode.toLowerCase();308                    this.generateElements();309                    if (window.parent.OnConstructLoadComplete) {310                        window.parent.OnConstructLoadComplete();311                    }312                    if (window.parent.OnAnimationLoadComplete) {313                        window.parent.OnAnimationLoadComplete();314                    }315                }316            }317            window.setTimeout(this.LoadInitialize.bind(this), 100);318            this.mergeJSON = function (SideBarJSON, AnimationJSON) {319                if (AnimationJSON.Elements && AnimationJSON.BckgElements != null && AnimationJSON.BckgElements.length > 0) {320                    var resultObj = {321                        BckgElementId: SideBarJSON.BckgElements.map(item => {322                            return Object.assign(item, AnimationJSON.BckgElements.find(a => a['BckgElementId'] === item['BckgElementId']))323                        }), ChildElements: SideBarJSON.ChildElements.map(item => {324                            return Object.assign(item, AnimationJSON.ChildElements.find(a => a['ChildElementId'] === item['ChildElementId']))325                        })326                    }327                } else {328                    return SideBarJSON;329                }330                ////console.log('result object after merging', JSON.stringify(resultObj));331                return resultObj;332            }333            this.GetData = function () {334                //  return stage.children[0].Arcadix;335                // var returnObj = stage.children[0].Arcadix;336                var returnObj = Object.assign({}, stage.children[0].Arcadix);337                if (returnObj['InitialArcadix_Data']['ChildElements']) {338                    for (var i = 0; i < returnObj['InitialArcadix_Data']['ChildElements'].length; i++) {339                        returnObj['InitialArcadix_Data']['ChildElements'][i]['StrElmXml'] = returnObj['InitialArcadix_Data']['ChildElements'][i]['ElmXml'] ? stringifyXML(returnObj['InitialArcadix_Data']['ChildElements'][i]['ElmXml']) : '';340                    }341                    return returnObj;342                } else {343                    return stage.children[0].Arcadix;344                }345            }346            function jsonBckElementCreator(element, evt, BckgElementId) {347                if (!stage.children[1].children.find(a => a['BckgElementId'] === BckgElementId)) {348                    BckElementBitmap = new createjs.Bitmap(evt.target);349                    container.addChild(BckElementBitmap);350                    BckElementBitmap.regX = BckElementBitmap.image.width / 2 | 0;351                    BckElementBitmap.regY = BckElementBitmap.image.height / 2 | 0;352                    jsonElement = stage.children[0].Arcadix['InitialArcadix_Data']['BckgElements'].find(a => a['BckgElementId'] === BckgElementId);353                    if (jsonElement['XPosition'] && jsonElement['YPosition']) {354                        BckElementBitmap.x = jsonElement['XPosition'];355                        BckElementBitmap.y = jsonElement['YPosition'];356                    }357                    if (stage.children[0].Arcadix['InitialArcadix_Mode'] && stage.children[0].Arcadix['InitialArcadix_Mode'].toLowerCase() === 'edit') {358                        BckElementBitmap.on('pressmove', function (evt) {359                            var p = evt.currentTarget.parent.globalToLocal(evt.stageX, evt.stageY);360                            evt.currentTarget.x = p.x;361                            evt.currentTarget.y = p.y;362                            updatePosition(element, 'BckgElements', evt.currentTarget);363                        });364                    }365                }366            }367            function OpenInputPopup(sourceElement,objParam) {368                window.parent.parent.LoadScripts({369                    ScriptsJSON: [window.parent.parent.JConfiguration.BaseUrl + "Applications/JIntranet/Tasks/Editor/EditorWorkArea/Objects/Element/Text/TextPopupPlugins/JInputProperty.js", window.parent.parent.JConfiguration.BaseUrl + "Applications/JIntranet/Tasks/Editor/EditorWorkArea/TextEditor/JTextEditorSidebarTemplate.js", window.parent.parent.JConfiguration.BaseUrl + "Framework/Controls/JValidator/JValidator.js"], LoadCompleteScripts: function () {370                        window.parent.parent.JLoadInputPopup(sourceElement, textPopupCallback, objParam);371                    }372                });373            }374            function updateAnswerXml(element) {375                debugger376                var parsedXml;377                if (!element['ElmXml'].URL || element['ElmXml'].URL == null) {378                    parsedXml = parseXmlStr(element['StrElmXml']);379                } else {380                    parsedXml = element['ElmXml'];381                }382                iElementId = parsedXml.getElementsByTagName("Element")[0].getAttribute('iElementId');383                iElementType = parsedXml.getElementsByTagName("Element")[0].getAttribute('iElementType');384                if (stage.children[0].Arcadix['ResultArcadix_Data_Xml'] === '' || stage.children[0].Arcadix['ResultArcadix_Data_Xml'] === undefined) {385                    stage.children[0].Arcadix['ResultArcadix_Data_Xml'] = document.implementation.createDocument("", "", null);386                    root = stage.children[0].Arcadix['ResultArcadix_Data_Xml'].createElement("AS");387                    stage.children[0].Arcadix['ResultArcadix_Data_Xml'].appendChild(root);388                }389                xmlDoc = document.implementation.createDocument("", "", null);390                let length = stage.children[0]['Arcadix']['ResultArcadix_Data_Xml'].getElementsByTagName('AS')[0].childNodes.length;391                let isExists = false;392                for (let i = 0; i < length; i++) {393                    if (stage.children[0]['Arcadix']['ResultArcadix_Data_Xml'].getElementsByTagName('AS')[0].childNodes[i].getElementsByTagName('VS')[0].innerHTML === iElementId) {394                        isExists = true;395                    }396                }397                if (!isExists) {398                    let AXml = xmlDoc.createElement("A");399                    let icXml = xmlDoc.createElement("iC");400                    icXml.setAttribute("ExclamatoryiC", '154134');401                    icXml.innerHTML = '154134';402                    let iEXml = xmlDoc.createElement("iE");403                    iEXml.innerHTML = iElementId;404                    let iETXml = xmlDoc.createElement("iET");405                    iETXml.innerHTML = iElementType;406                    let TXml = xmlDoc.createElement("T");407                    TXml.innerHTML = iElementType;408                    let CXml = xmlDoc.createElement("C");409                    CXml.innerHTML = '0';410                    let VSXml = xmlDoc.createElement("VS");411                    VSXml.setAttribute("ExclamatoryVID", '510776');412                    VSXml.setAttribute('iED', '1');413                    VSXml.setAttribute('iAC', '1');414                    AXml.appendChild(icXml);415                    AXml.appendChild(iEXml);416                    AXml.appendChild(TXml);417                    AXml.appendChild(CXml);418                    AXml.appendChild(VSXml);419                    xmlDoc.appendChild(AXml);420                    stage.children[0].Arcadix['ResultArcadix_Data_Xml'].getElementsByTagName('AS')[0].appendChild(AXml);421                }422            }423            function updateAnswerOnChange(evnt, iElementId) {424                console.log('evnt', evnt);425                //console.log(evnt);426                debugger427                for (i = 0; i < stage.children[0]['Arcadix']['ResultArcadix_Data_Xml'].getElementsByTagName('AS')[0].childNodes.length; i++) {428                    console.log("stage.children[0]['Arcadix']['ResultArcadix_Data_Xml'].getElementsByTagName('AS')[0].childNodes[i]", stage.children[0]['Arcadix']['ResultArcadix_Data_Xml'].getElementsByTagName('AS')[0].childNodes[i]);429                    if (stage.children[0]['Arcadix']['ResultArcadix_Data_Xml'].getElementsByTagName('AS')[0].childNodes[i].getElementsByTagName('iE')[0].innerHTML === evnt.currentTarget.id) {430                        stage.children[0]['Arcadix']['ResultArcadix_Data_Xml'].getElementsByTagName('AS')[0].childNodes[i].getElementsByTagName('VS')[0].innerHTML = '';431                        xmlDoc = document.implementation.createDocument("", "", null);432                        valueXml = xmlDoc.createElement('V');433                        if (evnt.target.tagName === 'SELECT') {434                            valueXml.innerHTML = evnt.currentTarget.options[evnt.currentTarget.selectedIndex].text;435                        } else {436                            valueXml.innerHTML = evnt.currentTarget.value;437                        }438                        stage.children[0]['Arcadix']['ResultArcadix_Data_Xml'].getElementsByTagName('AS')[0].childNodes[i].getElementsByTagName('VS')[0].appendChild(valueXml);439                        if (evnt.target.tagName === 'SELECT') {440                            vidXml = xmlDoc.createElement('VID');441                            vidXml.innerHTML = evnt.currentTarget.value;442                            stage.children[0]['Arcadix']['ResultArcadix_Data_Xml'].getElementsByTagName('AS')[0].childNodes[i].getElementsByTagName('VS')[0].appendChild(vidXml);443                        }444                    }445                }446            }447            function stringifyXML(xml) {448                var s = new XMLSerializer();449                var newXmlStr = s.serializeToString(xml);450                return newXmlStr;451            }452            function jsonChildElmtCreator(element) {453                updateAnswerXml(element);454                console.log('element', element);455                var parsedXml;456                if (!element['ElmXml'].URL || element['ElmXml'].URL == null) {457                    parsedXml = parseXmlStr(element['StrElmXml']);458                } else {459                    parsedXml = element['ElmXml'];460                }461                iElementId = parsedXml.getElementsByTagName("Element")[0].getAttribute('iElementId');462                iElementType = parsedXml.getElementsByTagName("Element")[0].getAttribute('iElementType');463                var inp;464                if (iElementType && iElementType === 'Input') {465                    inp = document.createElement('input');466                    inp.id = iElementId;467                    inp.setAttribute('type', 'text');468                    inp.style.position = "absolute";469                    inp.addEventListener('change', function (evt) {470                        updateAnswerOnChange(evt, iElementId);471                    });472                    inp.style.top = 0;473                    inp.style.left = 0;474                } else if (iElementType && iElementType === 'Dropdown') {475                    inp = document.createElement('select');476                    inp.id = iElementId;477                    inp.style.position = "absolute";478                    inp.style.width = '150px';479                    inp.addEventListener('change', function (evt) {480                        updateAnswerOnChange(evt, iElementId);481                    });482                    inp.style.top = 0;483                    inp.style.left = 0;484                    let options = parsedXml.getElementsByTagName("Element")[0].childNodes;485                    if (options) {486                        for (let i = 0; i < options.length; i++) {487                            var option = document.createElement("option");488                            option.setAttribute("value", options[i].getAttribute('AnswerValue'));489                            option.text = options[i].getAttribute('AnswerValue');490                            inp.appendChild(option);491                        }492                    }493                }494                console.log('inp', inp);495                document.body.appendChild(inp);496                var gg = new createjs.DOMElement(inp);497                gg.x = element['XPosition'];498                gg.y = element['YPosition'];499                container.addChild(gg);500                stage.update();501            }502            var dblClicked = false;503            function objectCreator(element) {504                if (stage.children[0].Arcadix['InitialArcadix_Mode'] && stage.children[0].Arcadix['InitialArcadix_Mode'].toLowerCase() === 'display') {505                    jsonChildElmtCreator(element);506                } else {507                    if (element['ObjType'] === 'placeholder') {508                        //let ChildElement = new Image();509                        //ChildElement.src = element.Img;510                        //ChildElement.onload = function (event) {511                        jsonElementPlaceholderCreator(element);512                        // }513                    } else {514                        let ChildElement = new Image();515                        ChildElement.src = element.Img;516                        ChildElement.onload = function (event) {517                            jsonHtmlplaceholderCreator(element, event);518                        }519                    }520                }521            }522            function jsonHtmlplaceholderCreator(element, evt) {523                debugger524                //var rect = new createjs.Rectangle(0, 0, 180, 30);525                var plhldrContainer;526             527                var iElementId = element['ChildElementId'];528                if (!stage.children.find(a => a['ChildElementId'] === iElementId)) {529                    iElementType = element['Type'];530                    if (!document.getElementById(iElementId)) {531                        if (!stage.children.find(a => a['ChildElementId'] === iElementId)) {532                            plhldrContainer = new createjs.Container();533                            plhldrContainer['ChildElementId'] = iElementId;534                            if (element['XPosition'] && element['YPosition']) {535                                plhldrContainer.x = element['XPosition'];536                                plhldrContainer.y = element['YPosition'];537                            } else {538                                plhldrContainer.x = 200;539                                plhldrContainer.y = 50;540                            }541                            stage.addChild(plhldrContainer);542                        }543                        containerIndex = stage.children.findIndex(a => a['ChildElementId'] === iElementId);544                        HtmlPlaceholder = new createjs.Bitmap(evt.target);545                        HtmlPlaceholder['ChildElementId'] = element['ChildElementId'];546                        //HtmlPlaceholder.regX = HtmlPlaceholder.image.width / 2;547                        //HtmlPlaceholder.regY = HtmlPlaceholder.image.height / 2;548                       549                        stage.children[containerIndex].addChild(HtmlPlaceholder);550                551                        if (stage.children[0].Arcadix['InitialArcadix_Mode'] && stage.children[0].Arcadix['InitialArcadix_Mode'].toLowerCase() === 'display') {552                            //HtmlPlaceholder.on('dblclick', function (evt) {553                            //    OpenInputPopup(this);554                            //});555                        }556                        //HtmlPlaceholder.on('click', function (evt) {557                            558                        //})559                        HtmlPlaceholder.on('pressmove', function (evt) {560                            //if (!dblClicked) {561                            var p = evt.currentTarget.parent.globalToLocal(evt.stageX, evt.stageY);562                            evt.currentTarget.x = p.x;563                            evt.currentTarget.y = p.y;564                            //text.x = p.x;565                            //text.y = p.y;566                            container.setChildIndex(this, container.getNumChildren() - 1);567                            updatePosition(element, 'ChildElements', { x: p.x, y: p.y });568                            stage.update();569                            //}570                            //dblClicked = false;571                        });572                        //HtmlPlaceholder.on('pressmove', function (evt) {573                        //    //if (!dblClicked) {574                        //        var p = evt.currentTarget.parent.globalToLocal(evt.stageX, evt.stageY);575                        //        evt.currentTarget.x = p.x;576                        //        evt.currentTarget.y = p.y;577                        //        //text.x = p.x;578                        //        //text.y = p.y;579                        //        container.setChildIndex(this, container.getNumChildren() - 1);580                        //        updatePosition(element, 'ChildElements', { x: p.x, y: p.y });581                        //        stage.update();582                        //    //}583                        //    //dblClicked = false;584                        //});585                        stage.update();586                    }587                }588            }589            function textPopupCallback(objJson, objParam) {590                debugger591              //  var EmlXml = parseXml(JSONToXml(objJson, 'input'));592                var ElmntIndex = stage.children[0].Arcadix.InitialArcadix_Data.ChildElements.findIndex(a => a['ChildElementId'] === objParam['ChildElementId']);593                // stage.children[0].Arcadix.InitialArcadix_Data.ChildElements[ElmntIndex]['ElmXml'] = EmlXml;594                var StagedElmIndex = stage.children.findIndex(a => a['ChildElementId'] == objParam['ChildElementId']);595                stage.removeChildAt(StagedElmIndex);596                var inpHtml = getHtmlElement('textbox', objJson);597                getImgPathFromHtml(inpHtml.outerHTML, { type: 'textbox', ChildElementId: objParam['ChildElementId']} , ImagepathCallback);598            }599            function ImagepathCallback(objJson, objParams) {600                var ImgPath = objJson.ConvertHtmlToImage.ImagePath;601                var elmIndex = stage.children[0].Arcadix.InitialArcadix_Data.ChildElements.findIndex(a => a['ChildElementId'] === objParams['ChildElementId']);602                stage.children[0].Arcadix.InitialArcadix_Data.ChildElements[elmIndex]['Img'] = ImgPath;603                var newHtmlImg = new Image();604                newHtmlImg.src = ImgPath;605                newHtmlImg.onload = function (event) {606                    jsonHtmlplaceholderCreator(stage.children[0].Arcadix.InitialArcadix_Data.ChildElements[elmIndex], event);607                }608               609            }610            function getHtmlElement(iElementType,objJson) {611                //function ControlToPngCreator(iElementType, uploadControlPng) {612                    var inp;613                    if (iElementType && iElementType === 'textbox') {614                        inp = document.createElement('input');615                        // inp.id = iElementId;616                        inp.setAttribute('type', 'text');617                        inp.setAttribute('value', objJson.Values[0].AnswerValue);618                        // inp.style.position = "absolute";619                        //inp.addEventListener('change', function (evt) {620                        //    updateAnswerOnChange(evt, iElementId);621                        //});622                        //inp.style.top = 0;623                        //inp.style.left = 0;624                    } else if (iElementType && iElementType === 'dropdown') {625                        inp = document.createElement('select');626                        //   inp.id = iElementId;627                        //inp.style.position = "absolute";628                        inp.style.width = '150px';629                        //inp.addEventListener('change', function (evt) {630                        //    updateAnswerOnChange(evt, iElementId);631                        //});632                        //inp.style.top = 0;633                        //inp.style.left = 0;634                        //let options = parsedXml.getElementsByTagName("Element")[0].childNodes;635                        //if (options) {636                        //    for (let i = 0; i < options.length; i++) {637                        //var option = document.createElement("option");638                        //option.setAttribute("value", 'test');639                        //option.text = '          >'640                        //inp.appendChild(option);641                        //    }642                        //}643                    }644                    return inp;645                         //  return html2Png(inp);646                        // html2Png(inp = inp, uploadControlPng = uploadControlPng, type = iElementType);647                       //$('#html-content-inner').html('');648                      //$('#html-content-inner').html(inp);649                     // getImgPathFromHtml(inp, iElementType);650                    // domToImage(document.getElementById('html-content-inner'), uploadControlPng = uploadControlPng, type = iElementType);651                   //    }652            }653            function getImgPathFromHtml(strHtml, objParam, ImagepathCallback) {654                debugger655                var strNewHtml = window.parent.ReplaceStringForXML(strHtml);656                //var strNewHtml = strHtml.replace(/\"/g, '\\"');657                window.parent.parent.JEditorWorkArea_ConvertHtmlToImage(strNewHtml, ImagepathCallback, objParam);658            }659            function jsonplaceholderCreator(element) {660                var rect = new createjs.Rectangle(0, 0, 180, 30);661                var plhldrContainer;662                var parsedXml;663                if (!element['ElmXml'].URL || element['ElmXml'].URL == null) {664                    parsedXml = parseXmlStr(element['StrElmXml']);665                } else {666                    parsedXml = element['ElmXml'];667                }668                iElementId = parsedXml.getElementsByTagName("Element")[0].getAttribute('iElementId');669                if (!stage.children.find(a => a['ChildElementId'] === iElementId)) {670                    iElementType = parsedXml.getElementsByTagName("Element")[0].getAttribute('iElementType');671                    if (!document.getElementById(iElementId)) {672                        if (!stage.children.find(a => a['ChildElementId'] === iElementId)) {673                            plhldrContainer = new createjs.Container();674                            plhldrContainer['ChildElementId'] = iElementId;675                            if (element['XPosition'] && element['YPosition']) {676                                plhldrContainer.x = element['XPosition'];677                                plhldrContainer.y = element['YPosition'];678                            } else {679                                plhldrContainer.x = 100;680                                plhldrContainer.y = 50;  681                            }682                            stage.addChild(plhldrContainer);683                        }684                        containerIndex = stage.children.findIndex(a => a['ChildElementId'] === iElementId);685                        var bckgnd = new createjs.Shape();686                        bckgnd['ChildElementId'] = iElementId;687                        bckgnd.graphics.beginFill('#f2f2f2').drawRect(0, 0, rect.width, rect.height);688                        var text = new createjs.Text();689                        text.set({690                            text: iElementType,691                            textAlign: "center",692                            textBaseline: "middle",693                            x: 0,694                            y: 0  695                        });696                        bckgnd.regX = rect.width / 2;697                        bckgnd.regY = rect.height / 2;698                        stage.children[containerIndex].addChild(bckgnd, text);699                        bckgnd.on('click', function () {700                            dblClicked = true;701                            console.log(' clicked..............');702                        })703                        if (stage.children[0].Arcadix['InitialArcadix_Mode'] && stage.children[0].Arcadix['InitialArcadix_Mode'].toLowerCase() === 'display') {704                            bckgnd.on('dblclick', function (evt) {705                                debugger706                                var item = stage.children.find(a => a['ChildElementId'] === evt.target.ChildElementId);707                                var stagedBckgnd = item.children[0];708                                stage.removeChild(item);709                                element['XPosition'] = stagedBckgnd.x;710                                element['YPosition'] = stagedBckgnd.y;711                                var childElementIndex = stage.children[0].Arcadix['InitialArcadix_Data']['ChildElements'].findIndex(a => a['ChildElementId'] === evt.target.ChildElementId);712                                stage.children[0].Arcadix['InitialArcadix_Data']['ChildElements'][childElementIndex]['ObjType'] = 'control';713                                jsonChildElmtCreator(element);714                            });715                        }716                        bckgnd.on('pressmove', function (evt) {717                            if (!dblClicked) {718                                var p = evt.currentTarget.parent.globalToLocal(evt.stageX, evt.stageY);719                                evt.currentTarget.x = p.x;720                                evt.currentTarget.y = p.y;721                                text.x = p.x;722                                text.y = p.y;723                                container.setChildIndex(this, container.getNumChildren() - 1);724                                updatePosition(element, 'ChildElements', { x: p.x, y: p.y });725                                stage.update();726                            }727                            dblClicked = false;728                        });729                        stage.update();730                    }731                }732            }733            function JSONToXml(json, type) {734                let xmlDoc = document.implementation.createDocument("", "", null);735                let ElmXml = xmlDoc.createElement('Element');736                for (let item in json) {737                    console.log('typeof txtJSON[item]', typeof json[item]);738                    if (typeof json[item] != 'object') {739                        ElmXml.setAttribute(item, json[item]);740                    }741                    else if (typeof json[item] == 'object') {742                        for (i = 0; i < json[item].length; i++) {743                            let valueXML = xmlDoc.createElement('Value');744                            for (valItem in json[item][i]) {745                                valueXML.setAttribute(valItem, json[item][i][valItem]);746                            }747                            ElmXml.appendChild(valueXML);748                        }749                    }750                    if (type.toLowerCase() === 'input') {751                        ElmXml.setAttribute('iElementTypeId', '5');752                        ElmXml.setAttribute('iElementType', 'Input');753                    }754                    else if (type.toLowerCase() === 'dropdown') {755                        ElmXml.setAttribute('iElementTypeId', '6');756                        ElmXml.setAttribute('iElementType', 'Dropdown');757                    }758                    ElmXml.setAttribute('iElementId', parent.GetUniqueId());759                }760                // console.log(serializeXML(ElmXml));761                return parseXml(serializeXML(ElmXml));762            }763            function parseXml(text) {764                if (text instanceof XMLDocument) {765                    return text;766                } else {767                    var parser = new DOMParser();768                    var xmlDoc = parser.parseFromString(text, "text/xml");769                    return xmlDoc;770                }771            }772            function jsonElementPlaceholderCreator(element) {773                var rect = new createjs.Rectangle(0, 0, 180, 30);774                var plhldrContainer;775                var parsedXml;776               // if (element['ElmXml'])     777                if (!element['ElmXml'].URL || element['ElmXml'].URL == null) {778                    parsedXml = parseXmlStr(element['StrElmXml']);779                } else {780                    parsedXml = element['ElmXml'];781                }782                iElementId = element['ChildElementId'];783                if (!stage.children.find(a => a['ChildElementId'] === iElementId)) {784                    iElementType = "Input";785                    if (!document.getElementById(iElementId)) {786                        if (!stage.children.find(a => a['ChildElementId'] === iElementId)) {787                            plhldrContainer = new createjs.Container();788                            plhldrContainer['ChildElementId'] = iElementId;789                            if (element['XPosition'] && element['YPosition']) {790                                plhldrContainer.x = element['XPosition'];791                                plhldrContainer.y = element['YPosition'];792                            } else {793                                plhldrContainer.x = 100;794                                plhldrContainer.y = 50;795                            }796                            stage.addChild(plhldrContainer);797                        }798                        containerIndex = stage.children.findIndex(a => a['ChildElementId'] === iElementId);799                        var bckgnd = new createjs.Shape();800                        bckgnd['ChildElementId'] = iElementId;801                        bckgnd.graphics.beginFill('#f2f2f2').drawRect(0, 0, rect.width, rect.height);802                        var text = new createjs.Text();803                        text.set({804                            text: iElementType,805                            textAlign: "center",806                            textBaseline: "middle",807                            x: 0,808                            y: 0809                        });810                        bckgnd.regX = rect.width / 2;811                        bckgnd.regY = rect.height / 2;812                        stage.children[containerIndex].addChild(bckgnd, text);813                        bckgnd.on('click', function () {814                            dblClicked = true;815                            console.log(' clicked..............');816                        })817                        //  if (stage.children[0].Arcadix['InitialArcadix_Mode'] && stage.children[0].Arcadix['InitialArcadix_Mode'].toLowerCase() === 'display') {818                        bckgnd.on('dblclick', function (evt) {819                            //var item = stage.children.find(a => a['ChildElementId'] === evt.target.ChildElementId);820                            //var stagedBckgnd = item.children[0];821                            //stage.removeChild(item);822                            //element['XPosition'] = stagedBckgnd.x;823                            //element['YPosition'] = stagedBckgnd.y;824                            //var childElementIndex = stage.children[0].Arcadix['InitialArcadix_Data']['ChildElements'].findIndex(a => a['ChildElementId'] === evt.target.ChildElementId);825                            //stage.children[0].Arcadix['InitialArcadix_Data']['ChildElements'][childElementIndex]['ObjType'] = 'control';826                            //jsonChildElmtCreator(element);827                            OpenInputPopup(this, { ChildElementId: evt.target.ChildElementId });828                        });829                        //  }830                        bckgnd.on('pressmove', function (evt) {831                            if (!dblClicked) {832                                var p = evt.currentTarget.parent.globalToLocal(evt.stageX, evt.stageY);833                                evt.currentTarget.x = p.x;834                                evt.currentTarget.y = p.y;835                                text.x = p.x;836                                text.y = p.y;837                                container.setChildIndex(this, container.getNumChildren() - 1);838                                updatePosition(element, 'ChildElements', { x: p.x, y: p.y });839                                stage.update();840                            }841                            dblClicked = false;842                        });843                        stage.update();844                    }845                } 846            }847            function updatePosition(objJsonElm, type, objevt) {848                console.log('updating position of element', objJsonElm);849                if (type === 'BckgElements') {850                    intelmIndex = stage.children[0].Arcadix['InitialArcadix_Data'][type].findIndex(a => a['BckgElementId'] === objJsonElm['BckgElementId']);851                    stage.children[0].Arcadix['InitialArcadix_Data'][type][intelmIndex]['XPosition'] = objevt.x;852                    stage.children[0].Arcadix['InitialArcadix_Data'][type][intelmIndex]['YPosition'] = objevt.y;853                }854                else if (type === 'ChildElements') {855                    intelmIndex = stage.children[0].Arcadix['InitialArcadix_Data'][type].findIndex(a => a['ChildElementId'] === objJsonElm['ChildElementId']);856                    stage.children[0].Arcadix['InitialArcadix_Data'][type][intelmIndex]['XPosition'] = objevt.x;857                    stage.children[0].Arcadix['InitialArcadix_Data'][type][intelmIndex]['YPosition'] = objevt.y;858                }859                console.log("after updating  stage.children[0].Arcadix['InitialArcadix_Data']", stage.children[0].Arcadix['InitialArcadix_Data']);860            }861            window.setTimeout(this.LoadInitialize.bind(this), 100);862            stage.addChild(container); // adding container to the stage863            stage.mouseMoveOutside = false;864            stage.enableMouseOver();865            stage.preventSelection = false;866            createjs.Touch.enable(stage /*, true, true*/);867            stage.update();868        }869        // actions tween:870        this.timeline.addTween(cjs.Tween.get(this).call(this.frame_0).wait(1));871    }).prototype = p = new cjs.MovieClip();872    p.nominalBounds = null;873    // library properties:874    lib.properties = {875        id: 'DAC903424E7A8A47BF57C8A648F8ADF8',876        width: 1120,877        height: 500,878        fps: 12,879        color: "#CCCCCC",880        opacity: 1.00,881        manifest: [],882        preloads: []883    };884    // bootstrap callback support:885    (lib.Stage = function (canvas) {886        createjs.Stage.call(this, canvas);887    }).prototype = p = new createjs.Stage();888    p.setAutoPlay = function (autoPlay) {889        this.tickEnabled = autoPlay;890    }891    p.play = function () { this.tickEnabled = true; this.getChildAt(0).gotoAndPlay(this.getTimelinePosition()) }892    p.stop = function (ms) { if (ms) this.seek(ms); this.tickEnabled = false; }893    p.seek = function (ms) { this.tickEnabled = true; this.getChildAt(0).gotoAndStop(lib.properties.fps * ms / 1000); }894    p.getDuration = function () { return this.getChildAt(0).totalFrames / lib.properties.fps * 1000; }895    p.getTimelinePosition = function () { return this.getChildAt(0).currentFrame / lib.properties.fps * 1000; }896    an.bootcompsLoaded = an.bootcompsLoaded || [];897    if (!an.bootstrapListeners) {898        an.bootstrapListeners = [];899    }900    an.bootstrapCallback = function (fnCallback) {901        an.bootstrapListeners.push(fnCallback);902        if (an.bootcompsLoaded.length > 0) {903            for (var i = 0; i < an.bootcompsLoaded.length; ++i) {904                fnCallback(an.bootcompsLoaded[i]);905            }906        }907    };908    an.compositions = an.compositions || {};909    an.compositions['DAC903424E7A8A47BF57C8A648F8ADF8'] = {910        getStage: function () { return exportRoot.getStage(); },911        getLibrary: function () { return lib; },912        getSpriteSheet: function () { return ss; },913        getImages: function () { return img; }914    };915    an.compositionLoaded = function (id) {916        an.bootcompsLoaded.push(id);917        for (var j = 0; j < an.bootstrapListeners.length; j++) {918            an.bootstrapListeners[j](id);919        }920    }921    an.getComposition = function (id) {922        return an.compositions[id];923    }924})(createjs = createjs || {}, AdobeAn = AdobeAn || {});...

Full Screen

Full Screen

image-provider.js

Source:image-provider.js Github

copy

Full Screen

...76        assetLoader.loadImages([getPortraitUrl(minionCard), "image/card/Card_Frame.png", "image/mana.png", "image/card/attack.png", "image/card/health.png"], function (portrait, frame, mana, attack, health) {77            const descriptionImageWidth = 250;78            const descriptionImageHeight = 130;79            const descriptionImageFontSize = 28;80            convertHtmlToImage(minionCard.description, descriptionImageWidth, descriptionImageHeight, descriptionImageFontSize, function (descriptionImage) {81                const canvas = document.createElement("canvas");82                canvas.width = 512;83                canvas.height = 550;84                const context = canvas.getContext("2d");85                if (portrait) {86                    context.save();87                    context.beginPath();88                    context.ellipse(260, 240, 160, 220, 0, 0, Math.PI*2);89                    context.clip();90                    drawScaledImage(context, portrait, 0.6, 0, -100);91                    context.restore();92                }93                context.drawImage(frame, 0, 0, 512, 512);94                context.drawImage(descriptionImage, 130, 340, descriptionImageWidth, descriptionImageHeight);95                drawScaledImage(context, mana, 1, 65, 10);96                context.strokeStyle = "black";97                context.fillStyle = "white";98                context.lineWidth = 3;99                context.font = "80px belwe";100                context.fillText(minionCard.manaCost, 95, 80);101                context.strokeText(minionCard.manaCost, 95, 80);102                context.font = "70px belwe";103                drawScaledImage(context, attack, 0.3, -150, 230);104                context.fillText(minionCard.attack, 92, 510);105                context.strokeText(minionCard.attack, 92, 510);106                drawScaledImage(context, health, 0.3, 150, 228);107                context.fillText(minionCard.health, 388, 510);108                context.strokeText(minionCard.health, 388, 510);109                callback(canvas);110            });111        });112    }113    function getHero(hero, callback) {114        assetLoader.loadImages(["image/hero/jaina.png", "image/HeroFrame.png", "image/attack.png", "image/health.png"], function (portrait, frame, attack, health) {115            const canvas = document.createElement("canvas");116            canvas.width = 512;117            canvas.height = 550;118            const context = canvas.getContext("2d");119            if (portrait) {120                context.save();121                context.beginPath();122                context.moveTo(290, 60);123                context.lineTo(410, 160);124                context.lineTo(430, 460);125                context.lineTo(80, 460);126                context.lineTo(100, 160);127                context.lineTo(230, 60);128                context.closePath();129                context.clip();130                drawScaledImage(context, portrait, 0.75, 0, 0);131                context.restore();132            }133            context.drawImage(frame, 0, 0, 512, 512);134            context.font = "70px belwe";135            context.lineWidth = 2;136            if (hero.attack) {137                drawScaledImage(context, attack, 0.3, -150, 230);138                context.fillText(hero.attack, 92, 510);139                context.strokeText(hero.attack, 92, 510);140            }141            drawScaledImage(context, health, 0.4, 175, 200);142            if (hero.health === hero.maxHealth) {143                context.fillStyle = "white";144            } else {145                context.fillStyle = "red";146            }147            context.fillText(hero.health, 390, 485);148            context.strokeText(hero.health, 390, 485);149            callback(canvas);150        });151    }152    function getManaStone(text, callback) {153        assetLoader.loadImages(["image/mana.png"], function (mana) {154            const canvas = document.createElement("canvas");155            canvas.width = 120;156            canvas.height = 120;157            const context = canvas.getContext("2d");158            drawScaledImage(context, mana, 1, 0, 0);159            var fontSize = 30;160            context.font = fontSize + "px belwe";161            while (context.measureText(text).width < 60) {162                fontSize += 2;163                context.font = fontSize + "px belwe";164            }165            context.fillStyle = "white";166            context.lineWidth = 2;167            const size = context.measureText(text);168            context.fillText(text, 50 - size.width / 2, 50 + fontSize / 4);169            context.strokeText(text, 50 - size.width / 2, 50 + fontSize / 4);170            callback(canvas);171        });172    }173    function getSpellCard(spellCard, callback) {174        assetLoader.loadImages([getPortraitUrl(spellCard), "image/card/Card_Frame.png", "image/mana.png", "image/card/attack.png", "image/card/health.png"], function (portrait, frame, mana, attack, health) {175            const descriptionImageWidth = 250;176            const descriptionImageHeight = 130;177            const descriptionImageFontSize = 28;178            convertHtmlToImage(spellCard.description, descriptionImageWidth, descriptionImageHeight, descriptionImageFontSize, function (descriptionImage) {179                const canvas = document.createElement("canvas");180                canvas.width = 512;181                canvas.height = 550;182                const context = canvas.getContext("2d");183                if (portrait) {184                    context.save();185                    context.beginPath();186                    context.ellipse(260, 240, 160, 220, 0, 0, Math.PI*2);187                    context.clip();188                    drawScaledImage(context, portrait, 0.6, 0, -115);189                    context.restore();190                }191                context.drawImage(frame, 0, 0, 512, 512);192                context.drawImage(descriptionImage, 130, 340, descriptionImageWidth, descriptionImageHeight);193                context.font = "80px belwe";194                context.fillStyle = "white";195                drawScaledImage(context, mana, 1, 65, 10);196                context.fillText(spellCard.manaCost, 93, 80);197                callback(canvas);198            });199        });200    }201    function convertHtmlToImage(html, width, height, fontSize, callback) {202        const data =  "<svg xmlns='http://www.w3.org/2000/svg' width='" + width + "' height='" + height + "'>" +203                    "<foreignObject width='100%' height='100%'>" +204                    "<div xmlns='http://www.w3.org/1999/xhtml' style='font-size:" + fontSize + "px; text-align: center;'>" +205                        html +206                    "</div>" +207                    "</foreignObject>" +208                    "</svg>";209        const img = new Image();210        const url = "data:image/svg+xml," + data;211        img.src = url;212        img.onload = function () {213            callback(img);214        }215    }...

Full Screen

Full Screen

corporate_eTraffic_Reports-impl.js

Source:corporate_eTraffic_Reports-impl.js Github

copy

Full Screen

1var EXTERNAL_USERNAME = 'Omnix_user';2//var EXTERNAL_PASSWORD = 'test12345';3var EXTERNAL_PASSWORD = '555M55MM';4var tibcoUsername = MFP.Server.getPropertyValue("tokens.tipcoService.username")  ;5var tibocPwd = MFP.Server.getPropertyValue("tokens.tipcoService.password")  ;6//var TMP_PATH 	= "D:/workspace/RTA/RTACorporateMobile/server/conf/corporates/";7//var TMP_PATH 	= "/home/proxym-it/RTA_Workspace/2014_omnix_rta/server/conf/corporates/";8var TMP_PATH 	= "D:/smartgov/cms/corpsrvc/servers_res/";9function getReports(transactionId, trafficFileNo){10	try {11		trafficFileNo = (MFP.Server.getAuthenticatedUser('masterAuthRealm') != undefined && MFP.Server.getAuthenticatedUser('masterAuthRealm') != null) ? MFP.Server.getAuthenticatedUser('masterAuthRealm').corporatesAttributes.trafficNo12				: trafficFileNo;13	} catch (e) {14		// TODO: handle exception15	}16	var soapActionHeader = '"getReportsOperation"';17	var transactionString = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:sch="http://www.rta.ae/ActiveMatrix/ESB/schemas/GetReports/XMLSchema/Schema.xsd" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">\18		   <soapenv:Header>\19	   <wsse:Security>\20	         <wsse:UsernameToken>\21				<wsse:Username>'+tibcoUsername+'</wsse:Username>\22				<wsse:Password>'+tibocPwd+'</wsse:Password>\23	         </wsse:UsernameToken>\24	      </wsse:Security>\25	      <sch:ExternalUser>\26	         <sch:externalUsername>'+EXTERNAL_USERNAME+'</sch:externalUsername>\27	         <sch:externalUserPassword>'+EXTERNAL_PASSWORD+'</sch:externalUserPassword>\28	      </sch:ExternalUser>\29	   </soapenv:Header>\30	   <soapenv:Body>\31	      <sch:getReports>\32	         <sch:transactoinId>'+transactionId+'</sch:transactoinId>\33	      </sch:getReports>\34	   </soapenv:Body>\35	</soapenv:Envelope>';36	MFP.Logger.info(transactionString);37//	var path = 'getReportService';38	var path = '/getReportService';39	var input = {40		method : 'POST',41		returnedContentType : 'xml',42		 headers : {'SOAPAction' : soapActionHeader},43		path : path,44		body : {45			content : transactionString.toString(),46			contentType : 'text/xml; charset=utf-8'47		}48	};49	var response = MFP.Server.invokeHttp(input);50	MFP.Logger.warn(response);51	// return response;52	// Analyzing response for errors53	if (typeof (response.Envelope.Body.getReportsReturn) == 'undefined') {54		MFP.Logger.warn("Error getting reports");55		return {56			isSuccessful : false,57			errorCode : 301,58			message : "An error has been occured in the server. Kindly try again"59		// 301 means error creating transaction60		};61	}62	response = response.Envelope.Body.getReportsReturn;63	if(typeof response.attachment.attachedFile !== "undefined" && response.attachment.attachedFile !== "" && response.attachment.attachedFile){64		return _convertPDFToImage(response.attachment.attachedFile);65	}else{66		//return generateECertificateForRenewPermit(trafficFileNo);67		return {68			isSuccessful : false,69			data : null ,70			extension : "png"71		};72	}73//	return {74//		isSuccessful : true,75//		data : response.attachment.attachedFile,76//		extension : "pdf"77//	};78}79/****80 * This function is used to load the MNOC after paying the transaction.81 * Get Reports now returns reports for the folwing cases : 82 * - MLetter83 * - MNOC if delivery type is mnoc only.84 * 85 * It applyes for the following services : cancel,renew, issue, modify permit, issue approved letter and reprint 86 * @param transactionId87 * @param trafficFileNumber88 * @param deliveryType89 * @param serviceCode90 */91function getMNoc(transactionId, trafficFileNumber, deliveryType, serviceCode, appTypeDesc){92	try {93		trafficFileNumber = (MFP.Server.getAuthenticatedUser('masterAuthRealm') != undefined && MFP.Server.getAuthenticatedUser('masterAuthRealm') != null) ? MFP.Server.getAuthenticatedUser('masterAuthRealm').corporatesAttributes.trafficNo94				: trafficFileNumber;95	} catch (e) {96		// TODO: handle exception97	}98	//	if(serviceCode == "-1" || serviceCode == "263"){99//		return generateCtaCertificate(trafficFileNumber, appTypeDesc);100//	}else if(serviceCode == '1070'){101//		return generateECertificateForRenewPermit(trafficFileNumber) ;102//	}else{103//		return getReports(transactionId) ;104//	}105	//We will always return the report106	return getReports(transactionId,trafficFileNumber) ;107}108function _convertPDFToImage(inputData) {109	var base64ImageString =  com.proxymit.pdf.utils.PDFToImage.convertPDFToImage(inputData);110	MFP.Logger.warn(base64ImageString);111	return {112		isSuccessful : true,113		data : base64ImageString ,114		extension : "png"115	};116}117//Will check the GetApplicationsService and seeks for the matching entry. It will extract the letterRefNo from that row.118function getLetterReferenceNumber(trafficFileNumber, letterExpiryDate){119	try {120		trafficFileNumber = (MFP.Server.getAuthenticatedUser('masterAuthRealm') != undefined && MFP.Server.getAuthenticatedUser('masterAuthRealm') != null) ? MFP.Server.getAuthenticatedUser('masterAuthRealm').corporatesAttributes.trafficNo121				: trafficFileNumber;122		//TODO : to be implemented123	} catch (e) {124		// TODO: handle exception125	}126	return '12409235';127}128function generateECertificateForRenewPermit(trafficFileNo){129	var nocExpiryDate = new Date(new Date().getTime() + 24 * 60 * 60 * 90* 1000) ; // Default expiry Date is 90 days from date of issing130//	var letterRefNo = getLetterReferenceNumber(trafficFileNo, nocExpiryDate) ;131	var now = new Date() ;132	var letterTime = now.getHours()+' : '+ now.getMinutes(); 133	var html = com.proxymit.wl.utils.ResourceLoader.loadResource('conf/corporates/eCertificate.html');134//	var html = com.proxymit.wl.utils.ResourceLoader.loadResource('servers_res/eCertificate.html');135	html = html.replace('##date##', now);136	html = html.replace('##refNo##', letterRefNo);137	html = html.replace('##time##', letterTime);138	html = html.replace('##trafficNo##', trafficFileNo);139	html = html.replace('##expiryDate##', nocExpiryDate);140	html = html.replace('##date##', now);141	html = html.replace('##refNo##', letterRefNo);142	html = html.replace('##time##', letterTime);143	html = html.replace('##trafficNo##', trafficFileNo);144	html = html.replace('##expiryDate##', nocExpiryDate);145//	var base64ImageString =  com.proxymit.pdf.utils.HTMLToImage.convertHTMLToImage(html);146	var base64ImageString =  com.proxymit.pdf.utils.HtmlToPDF.convertWithImg(html, TMP_PATH);147//	var base64ImageString =  com.proxymit.pdf.utils.HtmlToPDF.convertWithImg(html, "D:/smartgov/cms/corpsrvc/servers_res/");148	base64ImageString =  com.proxymit.pdf.utils.PDFToImage.convertPDFToImage(base64ImageString);149	MFP.Logger.warn(base64ImageString);150	return {151		isSuccessful : true,152		data : base64ImageString ,153		extension : "png"154	};155}156function generateCtaCertificate(trafficFileNo, appTypeDesc){157	try {158		trafficFileNo = (MFP.Server.getAuthenticatedUser('masterAuthRealm') != undefined && MFP.Server.getAuthenticatedUser('masterAuthRealm') != null) ? MFP.Server.getAuthenticatedUser('masterAuthRealm').corporatesAttributes.trafficNo159				: trafficFileNo;160	} catch (e) {161		// TODO: handle exception162	}163	var html = com.proxymit.wl.utils.ResourceLoader.loadResource('conf/corporates/LicensingAgency.html');164	var permitType = "";165	var permitTypeEn = "";166	var nocExpiryDate = new Date(new Date().getTime() + 24 * 60 * 60 * 90* 1000) ; // Default expiry Date is 90 days from date of issing167//	var letterRefNo = getLetterReferenceNumber(trafficFileNo, nocExpiryDate) ;168	if(appTypeDesc == "5"){169		permitType = "ﺔﻴﻧﻭﺮﺘﻜﻟﺍ ﺓﺩﺎﻬﺷ  -"+"ﺢﻳﺮﺼﺘﻟﺍ ﺪﻳﺪﺠﺗ"+"ﻰﻠﻋ ﺔﻘﻓﺍﻮﻣ";170		permitTypeEn = "renew permit";171	}else if(appTypeDesc == "4") {172		permitType = "ﺔﻴﻧﻭﺮﺘﻜﻟﺍ ﺓﺩﺎﻬﺷ  -"+"ﺢﻳﺮﺼﺘﻟﺍ ﺮﻴﻐﺗ"+"ﻰﻠﻋ ﺔﻘﻓﺍﻮﻣ";173		permitTypeEn = "modify permit";174	}else if(appTypeDesc == "3"){175		permitType = "ﺔﻴﻧﻭﺮﺘﻜﻟﺍ ﺓﺩﺎﻬﺷ  -"+"ﺢﻳﺮﺼﺘﻟﺍ ءﺎﻐﻟﺇ"+"ﻰﻠﻋ ﺔﻘﻓﺍﻮﻣ";176		permitTypeEn = "cancel permit";177	}else{178		permitType = "ﺔﻴﻧﻭﺮﺘﻜﻟﺍ ﺓﺩﺎﻬﺷ  -"+"XXXXX"+"ﻰﻠﻋ ﺔﻘﻓﺍﻮﻣ";179		permitTypeEn = "XXXXX";180	}181	var now = new Date() ;182	var letterTime = now.getHours()+' : '+ now.getMinutes();183	html = html.replace('##beginDate##', now);184	html = html.replace('##time##', letterTime);185	html = html.replace('##trafficNo##', trafficFileNo);186	html = html.replace('##expiryDate##', nocExpiryDate);187	html = html.replace('##time##', letterTime);188	html = html.replace('##trafficNo##', trafficFileNo);189	html = html.replace('##expiryDate##', nocExpiryDate);190	html = html.replace('##permitTypeEn##', permitTypeEn);191	html = html.replace('##permitTypeEn##', permitTypeEn);192	html = html.replace('##permitType##', permitType);193var base64ImageString =  com.proxymit.pdf.utils.HtmlToPDF.convertWithImg(html, TMP_PATH);194	base64ImageString =  com.proxymit.pdf.utils.PDFToImage.convertPDFToImage(base64ImageString);195	MFP.Logger.warn(base64ImageString);196	return {197		isSuccessful : true,198		data : base64ImageString,199		extension : "png"200	};...

Full Screen

Full Screen

http-server.js

Source:http-server.js Github

copy

Full Screen

1let http = require('http');2let convertHtmlToImage = require('./convert-html-to-image');3const port = 8080;4http.createServer(function(req, res) {5  const headers = {6    'Access-Control-Allow-Origin': '*',7    'Access-Control-Allow-Headers': 'Content-Type',8    // 'Content-Type': 'text/html',9    'Access-Control-Allow-Methods': 'OPTIONS, POST, GET',10    'Access-Control-Max-Age': 2592000, // 30 days11    /** add other headers as per requirement */12  };13  if (req.method === 'OPTIONS') {14    res.writeHead(204, headers);15    res.end();16    return;17  }18  if (['GET', 'POST'].indexOf(req.method) > -1) {19    if (req.url == '/submitForm') {20      parseRequestBody(req, res, headers);21      return;22    }23    else {24      res.writeHead(200, headers);25      res.end('Request Parsed');26      return;27    }28  }29  res.writeHead(405, headers);30  res.end(`${req.method} is not allowed for the request.`);31}).listen(port);32function convertToImage(data) {33  let date = new Date();34  return convertHtmlToImage.convertToPng(data, `output-image-${date.getTime()}`);35}36function parseRequestBody(req, res, headers) {37    // parsing request body38    // At this point, we have the headers, method, url and body, and can now39    // do whatever we need to in order to respond to this request.40    const { reqHeaders, reqMethod, reqURL } = req;41    let body = [];42    req.on('error', (err) => {43      console.error(err);44    }).on('data', (chunk) => {45      body.push(chunk);46    }).on('end', () => {47      body = Buffer.concat(body).toString(); // at this point, `body` has the entire request body stored in it as a string48      convertToImage(JSON.parse(body).data).then(response => {49        headers['Content-Type'] = 'application/json'50        if (response.success) {51          res.writeHead(200, headers);52        }53        else {54          res.writeHead(500, headers);55        }56        res.on('error', error => {57          console.error('Error: ', error)58        })59        res.end(JSON.stringify(response));60      });61    });...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1import html2canvas from 'html2canvas';2import jsPDF from 'jspdf';3const convertHTMLToPDF = async (html, y) => {4    const canvas = await html2canvas(html, { useCORS: true, y: y || html.offsetTop });5    const imgData = canvas.toDataURL(6        'image/png');7    const pdf = new jsPDF('p', 'mm', 'a4');8    const imgProps = pdf.getImageProperties(imgData);9    const pdfWidth = pdf.internal.pageSize.getWidth();10    const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;11    let pageNumber = 0;12    const pageheight = pdf.internal.pageSize.height;13    while (pdfHeight > (pageheight * pageNumber)) {14        if (pageNumber !== 0) {15            pdf.addPage();16        }17        const pos = 0 - (pageheight * pageNumber);18        pdf.addImage(imgData, 'PNG', 0, pos, pdfWidth, pdfHeight);19        pageNumber++;20    }21    return pdf;22}23const convertHTMLToImage = async (html) => {24    const canvas = await html2canvas(html, { useCORS: true, y: html.offsetTop });25    return canvas.toDataURL(26        'image/jpg');27}28export const downloadHelper = {29    convertHTMLToPDF,30    convertHTMLToImage31}...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1import { convertHtmlToImage } from 'cypress-html-to-image';2describe('My First Test', () => {3  it('Visits the Kitchen Sink', () => {4    convertHtmlToImage({ capture: 'viewport' });5  })6})

Full Screen

Using AI Code Generation

copy

Full Screen

1const convertHtmlToImage = require('cypress-visual-regression/dist/commands/convertHtmlToImage');2convertHtmlToImage(html, options);3const compareImages = require('cypress-visual-regression/dist/commands/compareImages');4compareImages(image1, image2, options);5const compareImages = require('cypress-visual-regression/dist/commands/compareImages');6compareImages(image1, image2, options);7const convertHtmlToImage = require('cypress-visual-regression/dist/commands/convertHtmlToImage');8convertHtmlToImage(html, options);9const compareImages = require('cypress-visual-regression/dist/commands/compareImages');10compareImages(image1, image2, options);11const compareImages = require('cypress-visual-regression/dist/commands/compareImages');12compareImages(image1, image2, options);13const convertHtmlToImage = require('cypress-visual-regression/dist/commands/convertHtmlToImage');14convertHtmlToImage(html, options);15const compareImages = require('cypress-visual-regression/dist/commands/compareImages');16compareImages(image1, image2, options);17const compareImages = require('cypress-visual-regression/dist/commands/compareImages');18compareImages(image1, image2, options);19const convertHtmlToImage = require('cypress-visual-regression/dist/commands/convertHtmlToImage');20convertHtmlToImage(html, options);21const compareImages = require('cypress-visual-regression/dist/commands/compareImages');22compareImages(image1, image2, options);23const compareImages = require('cypress-visual-regression/dist/commands/

Full Screen

Using AI Code Generation

copy

Full Screen

1import {convertHtmlToImage} from 'cypress-visual-regression/dist/command';2convertHtmlToImage();3import {compareSnapshotCommand} from 'cypress-visual-regression/dist/command';4compareSnapshotCommand();5import {compareSnapshotCommand} from 'cypress-visual-regression/dist/command';6compareSnapshotCommand();7import {addMatchImageSnapshotCommand} from 'cypress-visual-regression/dist/command';8addMatchImageSnapshotCommand();9import {addMatchImageSnapshotCommand} from 'cypress-visual-regression/dist/command';10addMatchImageSnapshotCommand();11import {convertHtmlToImage} from 'cypress-visual-regression/dist/command';12convertHtmlToImage();13import {compareSnapshotCommand} from 'cypress-visual-regression/dist/command';14compareSnapshotCommand();15import {compareSnapshotCommand} from 'cypress-visual-regression/dist/command';16compareSnapshotCommand();17import {addMatchImageSnapshotCommand} from 'cypress-visual-regression/dist/command';18addMatchImageSnapshotCommand();19import {addMatchImageSnapshotCommand} from 'cypress-visual-regression/dist/command';20addMatchImageSnapshotCommand();21import {convertHtmlToImage} from 'cypress-visual-regression/dist/command';22convertHtmlToImage();23import {compareSnapshotCommand} from 'cypress-visual-regression/dist/command';24compareSnapshotCommand();25import {compareSnapshotCommand} from 'cypress-visual-regression/dist/command';26compareSnapshotCommand();27import {addMatchImageSnapshotCommand} from 'cypress-visual-regression/dist/command';28addMatchImageSnapshotCommand();

Full Screen

Using AI Code Generation

copy

Full Screen

1cy.convertHtmlToImage('elementId')2cy.convertHtmlToImage('elementId', 'fileName')3cy.convertHtmlToImage('elementId', 'fileName', 'filePath')4cy.convertHtmlToImage('elementId', 'fileName', 'filePath', 'backgroundColor')5cy.convertHtmlToImage('elementId', 'fileName', 'filePath', 'backgroundColor', 'imageType')6cy.convertHtmlToImage('elementId', 'fileName', 'filePath', 'backgroundColor', 'imageType', 'imageQuality')7cy.convertHtmlToImage('elementId', 'fileName', 'filePath', 'backgroundColor', 'imageType', 'imageQuality', 'imageWidth')8cy.convertHtmlToImage('elementId', 'fileName', 'filePath', 'backgroundColor', 'imageType', 'imageQuality', 'imageWidth', 'imageHeight')9cy.convertHtmlToImage('elementId', 'fileName', 'filePath', 'backgroundColor', 'imageType', 'imageQuality', 'imageWidth', 'imageHeight', 'imageScale')10cy.convertHtmlToImage('elementId', 'fileName', 'filePath', 'backgroundColor', 'imageType', 'imageQuality', 'imageWidth', 'imageHeight', 'imageScale', 'imageCrop')11cy.convertHtmlToImage('elementId', 'fileName', 'filePath', 'backgroundColor', 'imageType', 'imageQuality', 'imageWidth', 'imageHeight', 'imageScale', 'imageCrop', 'imagePadding')12cy.convertHtmlToImage('elementId',

Full Screen

Using AI Code Generation

copy

Full Screen

1cy.convertHtmlToImage(html, 'test.png')2cy.convertHtmlToImage(html, 'test.png')3cy.convertHtmlToImage(html, 'test.png')4cy.convertHtmlToImage(html, 'test.png')5cy.convertHtmlToImage(html, 'test.png')6cy.convertHtmlToImage(html, 'test.png')7cy.convertHtmlToImage(html, 'test.png')8cy.convertHtmlToImage(html, 'test.png')9cy.convertHtmlToImage(html, 'test.png')10cy.convertHtmlToImage(html, 'test.png')11cy.convertHtmlToImage(html, 'test.png')12cy.convertHtmlToImage(html, 'test.png')13cy.convertHtmlToImage(html, 'test.png')14cy.convertHtmlToImage(html, 'test.png')

Full Screen

Using AI Code Generation

copy

Full Screen

1Cypress.Commands.add('convertHtmlToImage', (html) => {2  const canvas = document.createElement('canvas');3  canvas.width = 1200;4  canvas.height = 800;5  const ctx = canvas.getContext('2d');6  ctx.fillStyle = 'white';7  ctx.fillRect(0, 0, canvas.width, canvas.height);8    .document()9    .then((doc) => {10      svg.setAttribute('width', '100%');11      svg.setAttribute('height', '100%');12      const foreignObject = doc.createElementNS(13      );14      foreignObject.setAttribute('width', '100%');15      foreignObject.setAttribute('height', '100%');16      body.innerHTML = html;17      foreignObject.appendChild(body);18      svg.appendChild(foreignObject);19      const img = new Image();20      img.src = 'data:image/svg+xml;base64,' + btoa(svg.outerHTML);21      return new Promise((resolve, reject) => {22        img.onload = () => {23          ctx.drawImage(img, 0, 0);24          resolve(canvas.toDataURL());25        };26        img.onerror = reject;27      });28    })29    .then((dataUrl) => {30        .fixture(dataUrl.split(',')[1], 'base64')31        .then(Cypress.Blob.binaryStringToBlob)32        .then((blob) => {33          return Cypress.Blob.blobToArrayBuffer(blob);34        });35    });36});37Cypress.Commands.add('convertHtmlToImage', (html) => {38  const canvas = document.createElement('canvas');39  canvas.width = 1200;40  canvas.height = 800;41  const ctx = canvas.getContext('2d');

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('Take screenshot of a web page', function() {2    it('Take screenshot of a web page', function() {3        cy.wait(1000)4        cy.get('#hplogo').convertHtmlToImage('google-logo')5    })6})7Cypress.Commands.add('convertHtmlToImage', (fileName) => {8    cy.get('body').then(($body) => {9        html2canvas($body.get(0)).then(canvas => {10            const dataUrl = canvas.toDataURL('image/png')11            const blob = Cypress.Blob.base64StringToBlob(dataUrl, 'image/png')12            const file = new File([blob], fileName + '.png', { type: 'image/png' })13            const fileList = new DataTransfer()14            fileList.items.add(file)15            cy.get('input[type="file"]').then(el => {16                el[0].dispatchEvent(new Event('change', { bubbles: true }))17            })18        })19    })20})21const html2canvas = require('html2canvas')22module.exports = (on) => {23    on('task', {24    })25}26{27}28const dataUrl = canvas.toDataURL('image/png')29const blob = Cypress.Blob.base64StringToBlob(dataUrl, 'image/png')30const file = new File([blob], fileName + '.png', { type: 'image/png' })31const fileList = new DataTransfer()32fileList.items.add(file)33cy.get('input[type="file"]').then(el => {

Full Screen

Using AI Code Generation

copy

Full Screen

1import { convertHtmlToImage } from 'cypress-image-snapshot/command';2convertHtmlToImage({ fileName: 'my-image' });3const image = fs.readFileSync('cypress/screenshots/my-image.png', 'base64');4const html = `<img src="data:image/png;base64,${image}" />`;5fs.writeFileSync('cypress/reports/my-report.html', html);6{7  "reporterOptions": {8  }9}10{11  "mochawesomeReporterOptions": {12  }13}

Full Screen

Cypress Tutorial

Cypress is a renowned Javascript-based open-source, easy-to-use end-to-end testing framework primarily used for testing web applications. Cypress is a relatively new player in the automation testing space and has been gaining much traction lately, as evidenced by the number of Forks (2.7K) and Stars (42.1K) for the project. LambdaTest’s Cypress Tutorial covers step-by-step guides that will help you learn from the basics till you run automation tests on LambdaTest.

Chapters:

  1. What is Cypress? -
  2. Why Cypress? - Learn why Cypress might be a good choice for testing your web applications.
  3. Features of Cypress Testing - Learn about features that make Cypress a powerful and flexible tool for testing web applications.
  4. Cypress Drawbacks - Although Cypress has many strengths, it has a few limitations that you should be aware of.
  5. Cypress Architecture - Learn more about Cypress architecture and how it is designed to be run directly in the browser, i.e., it does not have any additional servers.
  6. Browsers Supported by Cypress - Cypress is built on top of the Electron browser, supporting all modern web browsers. Learn browsers that support Cypress.
  7. Selenium vs Cypress: A Detailed Comparison - Compare and explore some key differences in terms of their design and features.
  8. Cypress Learning: Best Practices - Take a deep dive into some of the best practices you should use to avoid anti-patterns in your automation tests.
  9. How To Run Cypress Tests on LambdaTest? - Set up a LambdaTest account, and now you are all set to learn how to run Cypress tests.

Certification

You can elevate your expertise with end-to-end testing using the Cypress automation framework and stay one step ahead in your career by earning a Cypress certification. Check out our Cypress 101 Certification.

YouTube

Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.

Run Cypress automation tests on LambdaTest cloud grid

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful