How to use wheel.type method in Appium Xcuitest Driver

Best JavaScript code snippet using appium-xcuitest-driver

backupparkingApp.js

Source:backupparkingApp.js Github

copy

Full Screen

1/*2 Copyright 2012 by Johnson Controls3 __________________________________________________________________________4 Filename: backupparkingApp.js5 __________________________________________________________________________6 Project: JCI-IHU7 Language: EN8 Author: aalangs9 Date: 25 Sep 201210 __________________________________________________________________________11 Description: IHU GUI Backupparking App12 13 Revisions:14 v0.1 (25-September-2012) Developed App for phase 1 scope with workarounds15                          - aalangs16 v0.2 (12-October-2012)   Initial Version with new controls - aalangs17 v0.3 (15-October-2012)   Added BUC surface display suggested by Chris for 18                          all contexts to display transparent image on 19                          target - aalangs20 v0.4 (16-October-2012)   Merged all the helper functions using 21                          "setSliderValue" - aalangs22 v0.5 (17-October-2012)   Removed status bar for NoctrlTmplt - aalangs23 v0.6 (23-October-2012)   Added NativeGUI surface to be shown up - aalangs24                          Fixed flickering issues mentioned by Petar & 25                          closed review comments - aalangs26 v0.7 (14-December-2012)  Added PSM Toggle button support and updated27                          Control properties - aalangs28 v0.8 (20-December-2012)  Updated as per latest event manager and control29                          updates - aalangs30 v0.9 (10-January-2013)   Updated to handle surface management changes in gui 31                          framework - aalangs32 v1.0 (28-January-2013)   Updated to correct "properties" in ParkingSensorDisplay33                          & Added message to handle MiniView Status - aalangs34 v1.1 (20-February-2013)  Added AtSpeed behavior to enable/disable Adjust 35                          button - aalangs36 v1.2 (26-February-2013)  Removed logic of - disabling "close" button - aalangs37 v1.3 (26-February-2013)  Hide the Home button icon for multiple context(s) - aalangs38 v1.4 (19-March-2013)     Removed Manual Override of Log Level - debug - aalangs39 v1.5 (19-April-3013)     Filtering Interval of sending slider events to MMUI needs 40                          to be updated to 250ms instead of 2s - aalangs41 v1.6 (22-April-2013)     In No Video Signal Context if PSM mode is off, use 42                          ScreenSetting2Ctrl interfaces to hide PSM Button - aalangs43 v1.7 (23-April-2013)     Remove labelIds of Adjust and PSM button from the 44                          icons as per 3.90 UI spec - aalangs45 v1.8 (17-June-2013)      Used common dictionary for tab names - aalangs46 v1.9 (10-September-2013) Updated VideoSettings for AtSpeed - aalangs47__________________________________________________________________________48 */49 50log.addSrcFile("backupparkingApp.js", "backupparking");51function backupparkingApp(uiaId)52{53    log.debug("Constructor called.");54    55    // Base application functionality is provided in a common location via this call to baseApp.init().56    // See framework/js/BaseApp.js for details.57    baseApp.init(this, uiaId);58}59/**************************60 * App Init is standard function called by framework *61 **************************/62/*63 * Called just after the app is instantiated by framework.64 * All variables local to this app should be declared in this function65 */66backupparkingApp.prototype.appInit = function()67{68    log.debug("backupparkingApp appInit  called...");69    if (framework.debugMode)70    {71        utility.loadScript("apps/backupparking/test/backupparkingAppTest.js");72    }73    74    //set flag so that animation is done only on press PSM button75    this._miniViewHideRequested = false;76    77    // cache Mini View PSD status78    this._miniViewPSDStatus = "MiniViewOn";79    80    // Store PSM hidden status81    this._PSMHidden = false;82    83    //cache values, default is 0, if no response from MMUI84    this._cachedBrightnessValue = 0;85    this._cachedContrastValue = 0;86    this._cachedTintValue = 0;87    this._cachedColorValue = 0;88    89    // cache vehicle speed90    this._cachedSpeed = null;91    92    // Video Settings tab value93    this.videoSettingsTab = true;94    //Tabs Config95    this._tabsConfig = [96        {97            "labelId" : "common.BrightnessTab",98            "itemConfig" :99            {100                style: "pivot",101                minChangeInterval: 250,102                settleTime: 1000,103                min: -5,104                max: 5,105                increment: 1,106                value: 0,107                appData: {eventName : "SetBrightnessValue", params : "brightnessValue"},108                hasActiveState: false109            }110        },111        {112            "labelId" : "common.ContrastTab",113            "itemConfig" :114            {115                style: "pivot",116                minChangeInterval: 250,117                settleTime: 1000,118                min: -5,119                max: 5,120                increment: 1,121                value: 0,122                appData: {eventName : "SetContrastValue", params : "contrastValue"},123                hasActiveState: false124            }125        },126        {127            "labelId" : "common.TintTab",128            "itemConfig" :129            {130                style: "pivot",131                minChangeInterval: 250,132                settleTime: 1000,133                min: -5,134                max: 5,135                increment: 1,136                value: 0,137                appData: {eventName : "SetTintValue", params : "tintValue"},138                hasActiveState: false139            }140        },141        {142            "labelId" : "common.ColorTab",143            "itemConfig" :144            {145                style: "pivot",146                minChangeInterval: 250,147                settleTime: 1000,148                min: -5,149                max: 5,150                increment: 1,151                value: 0,152                appData: {eventName : "SetColorValue", params : "colorValue"},153                hasActiveState: false154            }155        },156        {157            "labelId"       : "common.ResetTab",158            "itemConfig"    : { appData : "ResetAll", style : "oneButton", buttonId : "ResetSettings" }159        }160    ];161    162    //Context table163    //@formatter:off164    this._contextTable = {165       166        /**167         * This context shows only camera surface.168         * has PS:                 no169         * has camera:             yes170         * has video signal:     yes171         * show video surface:    no172         * show natgui surface:    yes173         */174        // BackupCameraDisplay 175        "BackupCameraDisplay" : {176            "hideHomeBtn" : true,177            "template" : "ScreenSettings2Tmplt",178            "properties": {179                "keybrdInputSurface" : "JCI_OPERA_PRIMARY", 180                "visibleSurfaces" :  ["NATGUI_SURFACE"]    // Do not include JCI_OPERA_PRIMARY in this list                181            },182            "controlProperties": {183                "ScreenSettings2Ctrl" : {184                    adjustButtonConfig : {"enabled": true, "adjustLabelId": "", "closeLabelId": "", "selectCallback": this._adjustBtnHandler.bind(this)},185                    tabsButtonConfig : {"visible": false, "currentlySelectedTab": 0, "tabsConfig": this._tabsConfig},186                    secondaryButtonConfig : null,   //These parameters are null (or omitted)187                    secondaryButtonCallback : null, //to not include a secondary button in this context188                    slideCallback : this._slideHandler.bind(this), // called when an item is dragged189                    selectCallback : this._selectHandler.bind(this), // called when a button is pressed190                    secondaryButtonAniTime : 0.5,191                } // end of properties for "ScreenSettings2Ctrl" 192            },193            "readyFunction" : this._BackupCameraDisplayReadyToDisplay.bind(this),194            "displayedFunction": this._BackupCameraDisplayCtxtTmpltDisplayed.bind(this)195        }, // end of "BackupCameraDisplay"196       197       /**198         * This context shows only camera surface.199         * has PS:                 no200         * has back button :      yes201         * has camera:             yes202         * has video signal:     yes203         * show video surface:    no204         * show natgui surface:    yes205         */206       "Calibration" : {207            "hideHomeBtn" : true,208            "template" : "ScreenSettings2Tmplt",209            "properties": {210                "keybrdInputSurface" : "JCI_OPERA_PRIMARY",211                "visibleSurfaces" :  ["NATGUI_SURFACE"]    // Do not include JCI_OPERA_PRIMARY in this list212            },213            "controlProperties": {214                "ScreenSettings2Ctrl" : {215                    adjustButtonConfig : {"enabled": false, visible:false, "adjustLabelId": "", "closeLabelId": "", "selectCallback": this._adjustBtnHandler.bind(this)},216                    backButtonConfig : {"enabled": true, appData: "SelectExitCalibration","selectCallback": this._backBtnHandler.bind(this)},217                    tabsButtonConfig : {"visible": false, "currentlySelectedTab": 0, "tabsConfig": this._tabsConfig},218                } // end of properties for "ScreenSettings2Ctrl" 219            },220            "readyFunction" : this._CalibrationReadyToDisplay.bind(this),221            "displayedFunction": this._CalibrationCtxtTmpltDisplayed.bind(this)222        }, // end of "BackupCameraDisplay"223       /**224        * This contexts shows only the PSD225        * has PS:                 yes226        * has camera:             no227        * has video signal:       n/a228        * show video surface:     no229        * show natgui surface:    yes230        */231       // ParkingSensorDisplay 232        "ParkingSensorDisplay" : {233            "hideHomeBtn" : true,234            "template" : "NoCtrlTmplt",235            // set custom properties for this template236            "properties" : {237                "statusBarVisible" : false,238                "customBgImage" : "common/images/FullTransparent.png",239                "keybrdInputSurface" : "JCI_OPERA_PRIMARY", 240                "visibleSurfaces" :  ["NATGUI_SURFACE"]    // Do not include JCI_OPERA_PRIMARY in this list            241            },// end of list of controlProperties242            "displayedFunction" : this._ParkingSensorDisplayCtxtTmpltDisplayed.bind(this)243        }, // end of "ParkingSensorDisplay" 244        245        /**246         * This context shows PSD and camera247         * has PS:                 yes248         * has camera:             yes249         * has video signal:       yes250         * show video surface:     yes251         * show natgui surface:    yes252         */253        // BUCAndPSMDisplay 254        "BUCAndPSMDisplay" : {255            "hideHomeBtn" : true,256            "template" : "ScreenSettings2Tmplt",257            "properties": {258                "keybrdInputSurface" : "JCI_OPERA_PRIMARY", 259                "visibleSurfaces" :  ["NATGUI_SURFACE"]    // Do not include JCI_OPERA_PRIMARY in this list                260            },261            "controlProperties": {262                "ScreenSettings2Ctrl" : {263                    adjustButtonConfig : {"enabled": true, "adjustLabelId": "", "closeLabelId": "", "selectCallback": this._adjustBtnHandler.bind(this)},264                    tabsButtonConfig : {"visible": false, "currentlySelectedTab": 0, "tabsConfig": this._tabsConfig},265                    secondaryButtonConfig : {"openLabelId": "", "closeLabelId": "", "startOpened": true, appData: "secondaryBtn"},266                    secondaryButtonAniTime : 0.5,267                    secondaryButtonCallback : this._secondaryButtonHandler.bind(this), // called when the secondary button is pressed268                    slideCallback : this._slideHandler.bind(this), // this is called when an item is dragged269                    selectCallback : this._selectHandler.bind(this), // this is called when a button is pressed270                } // end of properties for "ScreenSettings2Ctrl"                           271            }, // end of list of controlProperties272            "readyFunction" : this._BUCAndPSMDisplayReadyToDisplay.bind(this),273            "displayedFunction": this._BUCAndPSMDisplayCtxtTmpltDisplayed.bind(this)274        }, // end of "BUCAndPSMDisplay"275        276        /**277         * This context displays no video signal278         * has PS:                 no279         * has camera:             yes280         * has video signal:     no281         * show video surface:    yes282         * show natgui surface:    yes283         */284        // NoVideoSignalNotification 285        "NoVideoSignalNotification" : {286            "hideHomeBtn" : true,287            "template" : "ScreenSettings2Tmplt",288            "properties": {289                "keybrdInputSurface" : "JCI_OPERA_PRIMARY", 290                "visibleSurfaces" :  ["NATGUI_SURFACE"]    // Do not include JCI_OPERA_PRIMARY in this list                291            },292            "controlProperties": {293                "ScreenSettings2Ctrl" : {294                    adjustButtonConfig : {"enabled": false, "adjustLabelId": "", "closeLabelId": "", "selectCallback": this._adjustBtnHandler.bind(this)},295                    tabsButtonConfig : {"visible": false, "currentlySelectedTab": 0, "tabsConfig": this._tabsConfig},296                    secondaryButtonConfig : {"openLabelId": "", "closeLabelId": "", "startOpened": true, appData: "secondaryBtn"},297                    secondaryButtonAniTime : 0.5,298                    secondaryButtonCallback : this._secondaryButtonHandler.bind(this), // called when the secondary button is pressed299                    slideCallback : this._slideHandler.bind(this), // called when an item is dragged300                    selectCallback : this._selectHandler.bind(this), // called when a button is pressed301                } // end of properties for "ScreenSettings2Ctrl" 302            },303            "readyFunction" : this._NoVideoSignalNotificationReadyToDisplay.bind(this),304            "displayedFunction": this._NoVideoSignalNotificationCtxtTmpltDisplayed.bind(this)305        }, // end of "NoVideoSignalNotification"306        307        // VideoSettings 308        "VideoSettings" : {309            "hideHomeBtn" : true,310            "template" : "ScreenSettings2Tmplt",311            "properties": {312                "keybrdInputSurface" : "JCI_OPERA_PRIMARY", 313                "visibleSurfaces" :  ["NATGUI_SURFACE"]    // Do not include JCI_OPERA_PRIMARY in this list                314            },315            "controlProperties": {316                "ScreenSettings2Ctrl" : {317                    adjustButtonConfig : {"enabled": true, "adjustLabelId": "", "closeLabelId": "", "selectCallback": this._adjustBtnHandler.bind(this)},318                    tabsButtonConfig : {"visible": true, "currentlySelectedTab": 0, "tabsConfig": this._tabsConfig},319                    secondaryButtonAniTime : 0.5,320                    secondaryButtonConfig : null,   //These parameters are null (or omitted),321                    secondaryButtonCallback : null, //to not include a secondary button in this context322                    slideCallback : this._slideHandler.bind(this),323                    selectCallback : this._selectHandler.bind(this), // called when a button is pressed324                } // end of properties for "ScreenSettings2Ctrl"                           325            }, // end of list of controlProperties326            "readyFunction" : this._VideoSettingsCtxtTmpltReadyToDisplay.bind(this),327        }, // end of "VideoSettings"328        // TVMCameraDisplay - Included CI 3339329        "TVMCameraDisplay" : {330            "hideHomeBtn" : true,331            "template" : "ScreenSettings2Tmplt",332            "properties": {333                "keybrdInputSurface" : "JCI_OPERA_PRIMARY", 334                "visibleSurfaces" :  ["NATGUI_SURFACE"]    // Do not include JCI_OPERA_PRIMARY in this list                335            },336            "controlProperties": {337                "ScreenSettings2Ctrl" : {338                    style : "none",339                    adjustButtonConfig : {"enabled": true, "adjustLabelId": "", "closeLabelId": "", "selectCallback": this._adjustBtnHandler.bind(this)},340                    cvcButtonConfig : {"enabled": true, appData: "SelectCVC","selectCallback": this._cvcBtnHandler.bind(this)},341                    tabsButtonConfig : {"visible": false, "currentlySelectedTab": 0, "tabsConfig": this._tabsConfig},342                    secondaryButtonConfig : null,   //These parameters are null (or omitted)343                    secondaryButtonCallback : null, //to not include a secondary button in this context344                    slideCallback : this._slideHandler.bind(this), // called when an item is dragged345                    selectCallback : this._selectHandler.bind(this), // called when a button is pressed346                    secondaryButtonAniTime : 0.5,347                } // end of properties for "ScreenSettings2Ctrl" 348            },349           "contextInFunction" : this._TVMCameraDisplayContextIn.bind(this),350           "readyFunction" : this._BackupCameraDisplayReadyToDisplay.bind(this),351           "displayedFunction": this._BackupCameraDisplayCtxtTmpltDisplayed.bind(this)352        }, // end of "TVMCameraDisplay"353         // TVMCameraInhibit 354        "TVMCameraInhibit" : {355            "hideHomeBtn" : true,356            "template" : "ScreenSettings2Tmplt",357            "properties": {358                "keybrdInputSurface" : "JCI_OPERA_PRIMARY", 359                "visibleSurfaces" :  ["NATGUI_SURFACE"]    // Do not include JCI_OPERA_PRIMARY in this list                360            },361            "controlProperties": {362                "ScreenSettings2Ctrl" : {363                    style : "none",364                    adjustButtonConfig : {"enabled": true, "adjustLabelId": "", "closeLabelId": "", "selectCallback": this._adjustBtnHandler.bind(this)},365                    tabsButtonConfig : {"visible": false, "currentlySelectedTab": 0, "tabsConfig": this._tabsConfig},366                    secondaryButtonConfig : null,   //These parameters are null (or omitted)367                    secondaryButtonCallback : null, //to not include a secondary button in this context368                    slideCallback : this._slideHandler.bind(this), // called when an item is dragged369                    selectCallback : this._selectHandler.bind(this), // called when a button is pressed370                    secondaryButtonAniTime : 0.5,371                } // end of properties for "ScreenSettings2Ctrl" 372            },373            "contextInFunction" : this._TVMCameraInhibitContextIn.bind(this),374            "readyFunction" : this._BackupCameraDisplayReadyToDisplay.bind(this),375            "displayedFunction": this._BackupCameraDisplayCtxtTmpltDisplayed.bind(this)376        }, // end of "TVMCameraInhibit"377	       378        // TVMNoVideoSignalNotification _ Updated for CI 3339379        "TVMNoVideoSignalNotification" : {380            "hideHomeBtn" : true,381            "template" : "ScreenSettings2Tmplt",382            "properties": {383                "keybrdInputSurface" : "JCI_OPERA_PRIMARY", 384                "visibleSurfaces" :  ["NATGUI_SURFACE"]    // Do not include JCI_OPERA_PRIMARY in this list                385            },386            "controlProperties": {387                "ScreenSettings2Ctrl" : {388                    style : "none",389                    adjustButtonConfig : {"enabled": false, "adjustLabelId": "", "closeLabelId": "", "selectCallback": this._adjustBtnHandler.bind(this)},390                    cvcButtonConfig : {"enabled": false, appData: "SelectCVC","selectCallback": this._cvcBtnHandler.bind(this)},391                    tabsButtonConfig : {"visible": false, "currentlySelectedTab": 0, "tabsConfig": this._tabsConfig},392                    secondaryButtonConfig : null, //These parameters are null (or omitted)393                    secondaryButtonAniTime : null,394                    secondaryButtonCallback : null, //to not include a secondary button in this context395                    selectCallback : this._selectHandler.bind(this), // called when a button is pressed396                } // end of properties for "ScreenSettings2Ctrl" 397            },398            "contextInFunction" : this._TVMNoVideoSignalNotificationContextIn.bind(this),399            "displayedFunction": this._NoVideoSignalNotificationCtxtTmpltDisplayed.bind(this)400        }, // end of TVMNoVideoSignalNotification401         // TVMNoVideoSignalInhibit 402        "TVMNoVideoSignalInhibit" : {403            "hideHomeBtn" : true,404            "template" : "ScreenSettings2Tmplt",405            "properties": {406                "keybrdInputSurface" : "JCI_OPERA_PRIMARY", 407                "visibleSurfaces" :  ["NATGUI_SURFACE"]    // Do not include JCI_OPERA_PRIMARY in this list                408            },409            "controlProperties": {410                "ScreenSettings2Ctrl" : {411                    style : "none",412                    adjustButtonConfig : {"enabled": false, "adjustLabelId": "", "closeLabelId": "", "selectCallback": this._adjustBtnHandler.bind(this)},413                    tabsButtonConfig : {"visible": false, "currentlySelectedTab": 0, "tabsConfig": this._tabsConfig},                414                    secondaryButtonConfig : null,   //These parameters are null (or omitted)415                    secondaryButtonAniTime : null,416                    secondaryButtonCallback : null, //to not include a secondary button in this context417                    slideCallback : this._slideHandler.bind(this), // called when an item is dragged418                    selectCallback : this._selectHandler.bind(this), // called when a button is pressed419                } // end of properties for "ScreenSettings2Ctrl" 420            },421            "contextInFunction" : this._TVMNoVideoSignalInhibitContextIn.bind(this),422            "displayedFunction": this._NoVideoSignalNotificationCtxtTmpltDisplayed.bind(this)423        }, // end of TVMNoVideoSignalInhibit424        // TVMVideoSettings 425        "TVMVideoSettings" : {426            "hideHomeBtn" : true,427            "template" : "ScreenSettings2Tmplt",428            "properties": {429                "keybrdInputSurface" : "JCI_OPERA_PRIMARY", 430                "visibleSurfaces" :  ["NATGUI_SURFACE"]    // Do not include JCI_OPERA_PRIMARY in this list                431            },432            "controlProperties": {433                "ScreenSettings2Ctrl" : {434                    style : "bottom",435                    adjustButtonConfig : {"enabled": true, "adjustLabelId": "", "closeLabelId": "", "selectCallback": this._adjustBtnHandler.bind(this)},436                    tabsButtonConfig : {"visible": true, "currentlySelectedTab": 0, "tabsConfig": this._tabsConfig},437                    secondaryButtonAniTime : 0.5,438                    secondaryButtonConfig : null,   //These parameters are null (or omitted),439                    secondaryButtonCallback : null, //to not include a secondary button in this context440                    slideCallback : this._slideHandler.bind(this),441                    selectCallback : this._selectHandler.bind(this), // called when a button is pressed442                } // end of properties for "ScreenSettings2Ctrl"                           443            }, // end of list of controlProperties444            "readyFunction" : this._VideoSettingsCtxtTmpltReadyToDisplay.bind(this),445        }, // end of "TVMVideoSettings"446        // TVMVideoSettingsInhibit447        "TVMVideoSettingsInhibit" : {448            "hideHomeBtn" : true,449            "template" : "ScreenSettings2Tmplt",450            "properties": {451                "keybrdInputSurface" : "JCI_OPERA_PRIMARY", 452                "visibleSurfaces" :  ["NATGUI_SURFACE"]    // Do not include JCI_OPERA_PRIMARY in this list                453            },454            "controlProperties": {455                "ScreenSettings2Ctrl" : {456                    style : "bottom",457                    adjustButtonConfig : {"enabled": true, "adjustLabelId": "", "closeLabelId": "", "selectCallback": this._adjustBtnHandler.bind(this)},458                    tabsButtonConfig : {"visible": true, "currentlySelectedTab": 0, "tabsConfig": this._tabsConfig},459                    secondaryButtonAniTime : 0.5,460                    secondaryButtonConfig : null,   //These parameters are null (or omitted),461                    secondaryButtonCallback : null, //to not include a secondary button in this context462                    slideCallback : this._slideHandler.bind(this),463                    selectCallback : this._selectHandler.bind(this), // called when a button is pressed464                } // end of properties for "ScreenSettings2Ctrl"                           465            }, // end of list of controlProperties466            "readyFunction" : this._VideoSettingsCtxtTmpltReadyToDisplay.bind(this),467        }, // end of "TVMVideoSettingsInhibit"468    }; //EOF context table469    //@formatter:on470    471    //@formatter:off472    //message table473    this._messageTable =474    {475        "BrightnessSetting" : this._BrightnessSettingsMsgHandler.bind(this),476        "ColorSetting" : this._ColorSettingsMsgHandler.bind(this),477        "ContrastSetting" : this._ContrastSettingsMsgHandler.bind(this),478        "TintSetting" : this._TintSettingsMsgHandler.bind(this),479        //MiniView Status Msg480        "MiniViewStatus" : this._MiniViewStatusMsgHandler.bind(this),481        //Speed Handlers482        "Global.AtSpeed" : this._AtSpeedMsgHandler.bind(this),483        "Global.NoSpeed" : this._NoSpeedMsgHandler.bind(this)484    }; // EOF message table485}486/**********************487 * Context Handlers *488 **********************/489// TVMCameraDisplay ctxt490 backupparkingApp.prototype._TVMCameraDisplayContextIn = function()491{492    var steeringWheelType = framework.getSharedData("vehsettings","SteeringWheelLoc");493    log.info("Inside TVMCameraDisplayContextIn, wheelType ="+steeringWheelType);494    if( steeringWheelType === "LHD" || steeringWheelType ==="RHD")495	{496        this._contextTable["TVMCameraDisplay"].controlProperties.ScreenSettings2Ctrl.style = "bottom_"+steeringWheelType;497    }498}499// TVMCameraInhibit ctxt500backupparkingApp.prototype._TVMCameraInhibitContextIn = function()501{502    var steeringWheelType = framework.getSharedData("vehsettings","SteeringWheelLoc");503    log.info("Inside TVMCameraInhibitContextIn, wheelType ="+steeringWheelType);504    if( steeringWheelType === "LHD" || steeringWheelType ==="RHD")505	{506        this._contextTable["TVMCameraInhibit"].controlProperties.ScreenSettings2Ctrl.style = "bottom_"+steeringWheelType;507    }508}509// TVMNoVideoSignalNotification ctxt510backupparkingApp.prototype._TVMNoVideoSignalNotificationContextIn = function()511{512    var steeringWheelType = framework.getSharedData("vehsettings","SteeringWheelLoc");513    log.info("Inside TVMNoVideoSignalNotificationContextIn, wheelType = "+steeringWheelType);514    if( steeringWheelType === "LHD" || steeringWheelType ==="RHD")515	{516        this._contextTable["TVMNoVideoSignalNotification"].controlProperties.ScreenSettings2Ctrl.style = "bottom_"+steeringWheelType;517    }   518}519//TVMNoVideoSignalInhibit ctxt520backupparkingApp.prototype._TVMNoVideoSignalInhibitContextIn = function()521{522    var steeringWheelType = framework.getSharedData("vehsettings","SteeringWheelLoc");523    log.info("Inside TVMNoVideoSignalInhibitContextIn, wheelType = "+steeringWheelType);524    if( steeringWheelType === "LHD" || steeringWheelType ==="RHD")525	{526        this._contextTable["TVMNoVideoSignalInhibit"].controlProperties.ScreenSettings2Ctrl.style = "bottom_"+steeringWheelType;527    }528}529//BackupCameraDisplay ctxt530backupparkingApp.prototype._BackupCameraDisplayReadyToDisplay = function()531{532    if (this._currentContext && this._currentContextTemplate && 533        (this._currentContext.ctxtId == "BackupCameraDisplay" || this._currentContext.ctxtId == "TVMCameraDisplay" || this._currentContext.ctxtId == "TVMCameraInhibit"))534    {535        this._cachedSpeed = framework.common.getAtSpeedValue();536        537        if(this._cachedSpeed != null)538        {539            this._updateAtSpeed();540        }541    }542}543 544// Send an event to MMUI to notify that Adjust button is now available in displayed function545backupparkingApp.prototype._BackupCameraDisplayCtxtTmpltDisplayed = function()546{547    // Send an event to MMUI to notify that Adjust button is enabled now548    framework.sendEventToMmui(this.uiaId, "AdjustAvailable", {"payload": {"adjustButtonStatus": 1}});549}550//Calibration ctxt551backupparkingApp.prototype._CalibrationReadyToDisplay = function()552{553    if (this._currentContext && this._currentContextTemplate && this._currentContext.ctxtId == "Calibration")554    {555        this._cachedSpeed = framework.common.getAtSpeedValue();556        557        if(this._cachedSpeed != null)558        {559            this._updateAtSpeed();560        }561    }562}563// Send an event to MMUI to notify that Adjust button is now available in displayed function564backupparkingApp.prototype._CalibrationCtxtTmpltDisplayed = function()565{566    // Send an event to MMUI to notify that Adjust button is enabled now567    framework.sendEventToMmui(this.uiaId, "AdjustAvailable", {"payload": {"adjustButtonStatus": 1}});568}569// Send an event to MMUI to notify that Adjust button is now disabled570backupparkingApp.prototype._ParkingSensorDisplayCtxtTmpltDisplayed = function()571{572    // Send an event to MMUI to notify that Adjust button is disabled now573    framework.sendEventToMmui(this.uiaId, "AdjustAvailable", {"payload": {"adjustButtonStatus": 0}});574}575// BUCAndPSMDisplay context576backupparkingApp.prototype._BUCAndPSMDisplayReadyToDisplay = function()577{578    if (this._currentContext && this._currentContextTemplate && this._currentContext.ctxtId == "BUCAndPSMDisplay")579    {580        // get speed value from fwk581        this._cachedSpeed = framework.common.getAtSpeedValue();582        if(this._cachedSpeed != null)583        {584            // Update the adjust button585            this._updateAtSpeed();586        }587        this._updateMiniViewStatus();588    }589}590// Send an event to MMUI to notify that Adjust button is now disabled591backupparkingApp.prototype._BUCAndPSMDisplayCtxtTmpltDisplayed = function()592{593    // Send an event to MMUI to notify that Adjust button is enabled now594    framework.sendEventToMmui(this.uiaId, "AdjustAvailable", {"payload": {"adjustButtonStatus": 1}});595}596// NoVideoSignalNotification context597backupparkingApp.prototype._NoVideoSignalNotificationReadyToDisplay = function()598{599    if (this._currentContext && this._currentContextTemplate && this._currentContext.ctxtId == "NoVideoSignalNotification")600    {601        this._updateMiniViewStatus();602    }603}604// Send an event to MMUI to notify that Adjust button is now disabled605backupparkingApp.prototype._NoVideoSignalNotificationCtxtTmpltDisplayed = function()606{607    // Send an event to MMUI to notify that Adjust button is disabled now608    framework.sendEventToMmui(this.uiaId, "AdjustAvailable", {"payload": {"adjustButtonStatus": 0}});609}610// VideoSettings context611backupparkingApp.prototype._VideoSettingsCtxtTmpltReadyToDisplay = function()612{613    // Update the current slider value before display614    if(this._currentContext && this._currentContext.ctxtId && 615        (this._currentContext.ctxtId === "VideoSettings" || this._currentContext.ctxtId === "TVMVideoSettings" || this._currentContext.ctxtId === "TVMVideoSettingsInhibit"))616    {617        var currTabValue = null;618        619        // get speed value from fwk620        this._cachedSpeed = framework.common.getAtSpeedValue();621        622        if(this._cachedSpeed != null)623        {624            // Update the adjust button625            this._updateAtSpeed();626        }627        if(this.videoSettingsTab)628        {629            for(var i = 0 ; i < 4; i++)630            {631                var currTabValue = this._tabsConfig[i].itemConfig.appData;632                // Check what is the value of selected tab and update it with cached slider value 633                switch(currTabValue)634                {635                    case "SetBrightnessValue" : 636                        this._updateSliderValue(0, this._cachedBrightnessValue);637                        break;638                    case "SetContrastValue" :639                        this._updateSliderValue(1, this._cachedContrastValue);640                        break;641                    case "SetTintValue" :642                        this._updateSliderValue(2, this._cachedTintValue);643                        break;644                    case "SetColorValue" :645                        this._updateSliderValue(3, this._cachedColorValue);646                        break;647                    default : 648                        log.info("No slider update is required...");649                        break;650                }651            }652        }653        else654        {655            log.warn("Video Settings can not be displayed as speed exceeded the limit");656        }657    }658}659/**************************660 * Message handlers661 **************************/662//BrightnessTab Message Handler663backupparkingApp.prototype._BrightnessSettingsMsgHandler = function(msg)664{665    if (msg && msg.params && msg.params.payload && msg.params.payload.videoBrightness != null)666    {667        // cache the value sent by MMUI for later use668        this._cachedBrightnessValue = msg.params.payload.videoBrightness;669        this._tabsConfig[0].itemConfig.value = this._cachedBrightnessValue;670        // Update the slider value if context matches671        if (this._currentContext && this._currentContextTemplate && 672            (this._currentContext.ctxtId === "VideoSettings" || this._currentContext.ctxtId === "TVMVideoSettings" || this._currentContext.ctxtId === "TVMVideoSettingsInhibit"))673        {674            if(this._tabsConfig[0].itemConfig.appData.eventName === "SetBrightnessValue")675            {676                this._updateSliderValue(0, this._cachedBrightnessValue);677            }678        }679    }680}681//ContrastTab Message Handler682backupparkingApp.prototype._ContrastSettingsMsgHandler = function(msg)683{684    if (msg && msg.params && msg.params.payload && msg.params.payload.videoContrast != null)685    {686        // cache the value sent by MMUI for later use687        this._cachedContrastValue = msg.params.payload.videoContrast;688        this._tabsConfig[1].itemConfig.value = this._cachedContrastValue;689        // Update the slider value if context matches690        if (this._currentContext && this._currentContextTemplate && 691            (this._currentContext.ctxtId === "VideoSettings" || this._currentContext.ctxtId === "TVMVideoSettings" || this._currentContext.ctxtId === "TVMVideoSettingsInhibit"))692        {693            if(this._tabsConfig[1].itemConfig.appData.eventName === "SetContrastValue")694            {695                this._updateSliderValue(1, this._cachedContrastValue);696            }697        }698    }699}700//TintTab Message Handler701backupparkingApp.prototype._TintSettingsMsgHandler = function(msg)702{703    if (msg && msg.params && msg.params.payload && msg.params.payload.videoTint != null)704    {705        // cache the value sent by MMUI for later use706        this._cachedTintValue = msg.params.payload.videoTint;707        this._tabsConfig[2].itemConfig.value = this._cachedTintValue;708        // Update the slider value if context matches709        if (this._currentContext && this._currentContextTemplate &&710            (this._currentContext.ctxtId === "VideoSettings" || this._currentContext.ctxtId === "TVMVideoSettings" || this._currentContext.ctxtId === "TVMVideoSettingsInhibit"))711        {712            if(this._tabsConfig[2].itemConfig.appData.eventName === "SetTintValue")713            {714                this._updateSliderValue(2, this._cachedTintValue);715            }716        }717    }718}719//Color Tab Message Handler720backupparkingApp.prototype._ColorSettingsMsgHandler = function(msg)721{722    if (msg && msg.params && msg.params.payload && msg.params.payload.videoColor != null)723    {724        // cache the value sent by MMUI for later use725        this._cachedColorValue = msg.params.payload.videoColor;726        this._tabsConfig[3].itemConfig.value = this._cachedColorValue;727        // Update the slider value if context matches728        if (this._currentContext && this._currentContextTemplate && 729            (this._currentContext.ctxtId === "VideoSettings" || this._currentContext.ctxtId === "TVMVideoSettings" || this._currentContext.ctxtId === "TVMVideoSettingsInhibit"))730        {731            if(this._tabsConfig[3].itemConfig.appData.eventName === "SetColorValue")732            {733                this._updateSliderValue(3, this._cachedColorValue);734            }735        }736    }737}738//MiniView Status Message Handler739backupparkingApp.prototype._MiniViewStatusMsgHandler = function(msg)740{741    if (msg && msg.params && msg.params.payload && msg.params.payload.miniViewPSD)742    {743        // cache the value sent by MMUI for later use744        this._miniViewPSDStatus = msg.params.payload.miniViewPSD;745        746        // Update the Mini View value if context matches747        if (this._currentContext && this._currentContextTemplate && 748                this._currentContext.ctxtId === "BUCAndPSMDisplay" || this._currentContext.ctxtId === "NoVideoSignalNotification")749        {750            this._updateMiniViewStatus();751        }752    }753}754// At Speed - true755backupparkingApp.prototype._AtSpeedMsgHandler = function(msg)756{757    if (msg)758    {759        // cache the value sent by GUI common for later use760        this._cachedSpeed = true;761        // Update the context if matches762        if (this._currentContext && this._currentContextTemplate && this._currentContext.ctxtId)763        {764            switch(this._currentContext.ctxtId)765            {766                case "BackupCameraDisplay" :767                case "TVMCameraDisplay" :768                case "TVMCameraInhibit" :769                case "BUCAndPSMDisplay" :770                case "VideoSettings" : 771                case "TVMVideoSettings" :772                case "TVMVideoSettingsInhibit" :   773                    this._updateAtSpeed();774                    break;775                default :776                    log.warn("No action in this ctxt..." + this._currentContext.ctxtId);777                    break;778            }779        }780    }781}782// At Speed - false783backupparkingApp.prototype._NoSpeedMsgHandler = function(msg)784{785    if (msg)786    {787        // cache the value sent by GUI common for later use788        this._cachedSpeed = false;789        // Update the context if matches790        if (this._currentContext && this._currentContextTemplate && this._currentContext.ctxtId)791        {792            switch(this._currentContext.ctxtId)793            {794                case "BackupCameraDisplay" :795                case "TVMCameraDisplay" :796                case "TVMCameraInhibit" :797                case "BUCAndPSMDisplay" :798                case "VideoSettings" : 799                case "TVMVideoSettings" :800                case "TVMVideoSettingsInhibit" :   801                    this._updateAtSpeed();802                    break;803                default :804                    log.warn("No action in this ctxt..." + this._currentContext.ctxtId);805                    break;806            }807        }808    }809}810/**************************811 * CONTROL HANDLERS *812 **************************/813/*814 * Callback for sliders within the tabs815 */816backupparkingApp.prototype._slideHandler = function(ctrlObj, appData, params)817{818    var eventName = appData.eventName;819    switch(eventName)820    {821        case "SetBrightnessValue" : 822            framework.sendEventToMmui(this.uiaId, eventName, {"payload": {"brightnessValue" : params.value, "final": params.finalAdjustment}});823            break;824        case "SetContrastValue" : 825            framework.sendEventToMmui(this.uiaId, eventName, {"payload": {"contrastValue" : params.value, "final": params.finalAdjustment}});826            break;827        case "SetTintValue" : 828            framework.sendEventToMmui(this.uiaId, eventName, {"payload": {"tintValue" : params.value, "final": params.finalAdjustment}});829            break;830        case "SetColorValue" : 831            framework.sendEventToMmui(this.uiaId, eventName, {"payload": {"colorValue" : params.value, "final": params.finalAdjustment}});832            break;833        default : 834            log.warn("No event has been defined");835            break;836    }837}838/*839 * Callback for items within the tabs (e.g. Reset All Button)840 */841backupparkingApp.prototype._selectHandler = function(ctrlObj, appData, params)842{843    framework.sendEventToMmui(this.uiaId, appData, {});844}845/*846 * Callback for the adjust button847 */848backupparkingApp.prototype._adjustBtnHandler = function(ctrlObj, appData, params)849{850    if(params.opened == false)851    {852        framework.sendEventToMmui(this.uiaId, "SelectVideoSettings", params);853    }854    else if(params.opened == true)855    {856        framework.sendEventToMmui(this.uiaId, "SelectClose", params);857    }858}859/*860 * Callback for the secondary button861 */862backupparkingApp.prototype._secondaryButtonHandler = function(ctrlObj, appData, params)863{864    log.debug("backupparkingApp _secondaryButtonHandler called: " + params.opened);865    // Check validity of ctxt to avoid GUI State Time Out Err866    if(this._currentContextTemplate)867    {868        if (params.opened == false)869        {870            // Send an event to MMUI to notify MiniViewOn871            this._currentContextTemplate.screenSettings2Ctrl.startAnimation("open", this._secondaryBtnAnimationComplete.bind(this));872        }873        else874        {875            // Send an event to MMUI to notify MiniViewOff876            this._miniViewHideRequested = true;877            framework.sendEventToMmui(this.uiaId, "MiniViewOff");878        }879    }880}881/*882 * Callback for the back button883 */884backupparkingApp.prototype._backBtnHandler = function(ctrlObj, appData, params)885{886    if(params.backBtn == "backBtn")887    {888        framework.sendEventToMmui(this.uiaId, appData);889    }890};891/*892 * Callback for the cvc button - CI 3339893 */894backupparkingApp.prototype._cvcBtnHandler = function(ctrlObj, appData, params)895{896    if(params.cvcBtn == "cvcBtn")897    {898        framework.sendEventToMmui(this.uiaId, appData);899    }900};901/*902 * Callback for the secondary button animation complete903 */904backupparkingApp.prototype._secondaryBtnAnimationComplete = function(ctrlObj, appData, params)905{906    log.debug("_secondaryBtnAnimationComplete called..");907    // check if current context is - BUCAndPSMDisplay908    if(this._currentContext && this._currentContext.ctxtId && 909       (this._currentContext.ctxtId === "BUCAndPSMDisplay" || this._currentContext.ctxtId === "NoVideoSignalNotification" ))910    {911        if (params.opened == true)912        {913            // Send an event to MMUI to notify MiniViewOn914            framework.sendEventToMmui(this.uiaId, "MiniViewOn");915        }916    }917}918/**************************919 * Helper functions920 **************************/921//Helper function for setting slider value for tabs922backupparkingApp.prototype._updateSliderValue = function(index, sliderValue)923{924    // Check validity of ctxt to avoid GUI State Time Out Err925    if(this._currentContextTemplate)926    {927        var tmplt = this._currentContextTemplate;928        // Call public API of screenSettings2Ctrl and update the slider value            929        tmplt.screenSettings2Ctrl.update(index, sliderValue);930    }931}932//Helper function for setting MiniView button status - PSM - show or hide933backupparkingApp.prototype._updateMiniViewStatus = function()934{935    // Check validity of ctxt to avoid GUI State Time Out Err936    if(this._currentContextTemplate)937    {938        var tmplt = this._currentContextTemplate;939        switch(this._miniViewPSDStatus)940        {941            case "miniViewOn" :942                if(this._PSMHidden)943                {944                    tmplt.screenSettings2Ctrl.hideSecondaryBtn(false);945                }946                // Call public API of screenSettings2Ctrl and update MiniView Button status value947                tmplt.screenSettings2Ctrl.setSecondaryBtnOpened(true);948                break;949            case "miniViewOff" :950                if(this._PSMHidden)951                {952                    tmplt.screenSettings2Ctrl.hideSecondaryBtn(false);953                }954                // Call public API of screenSettings2Ctrl and update MiniView Button status value955                tmplt.screenSettings2Ctrl.setSecondaryBtnOpened(false);956                if(this._miniViewHideRequested === true)957                {958                    this._miniViewHideRequested = false;959                    // Animation part960                    tmplt.screenSettings2Ctrl.startAnimation("close",this._secondaryBtnAnimationComplete.bind(this));961                }962                break;963            case "noPS" : 964                tmplt.screenSettings2Ctrl.hideSecondaryBtn(true);965                this._PSMHidden = true;966                break;967            default : 968                log.warn("Invalid State...");969                break;970        }971    }972}973// Update the adjust button - enable / disable based on status974backupparkingApp.prototype._updateAtSpeed = function()975{976    if(this._currentContextTemplate)977    {978        var tmplt = this._currentContextTemplate;979        if(!this._cachedSpeed)980        {981            // Call public API of screenSettings2Ctrl and update Adjust Button status value982            tmplt.screenSettings2Ctrl.setAtSpeed(false);983            this.videoSettingsTab = true;984        }985        else986        {987            // Call public API of screenSettings2Ctrl and update Adjust Button status value988            tmplt.screenSettings2Ctrl.setAtSpeed(true);989            this.videoSettingsTab = false;990        }991    }992}993//Tell framework this .js file has finished loading, it has no controls to load, and it has no dictionaries...

Full Screen

Full Screen

wheel-helpers.js

Source:wheel-helpers.js Github

copy

Full Screen

1/* Wheel Helpers */2/* Reusable functions related to the wheel */3// -----------------------------------------------------------------4// Variables5// -----------------------------------------------------------------6_timeAtLoad = GetTimeStampNow();7_rawData = [];                  // global parent of all raw data8_currentWheelType = "taccom";   // name of the wheel to load ( can be a Go Global Variable :: ASE )9_currentWheel = null;           // clone the wheel data, once parsed. this is the object we work with, and what is sent to the server10_currentWheelBackup = null;     // redundancy, if anything goes wrong11_arrayOfPrizes = [];            // names of the prizes12_arrayOfPrizeOdds = [];         // odds for each prize (same order as the names)13_arrayOfPrizeIndex = [];        // shorthand, to calculate wheel position >> used most frequently14_indexOfLosingTile = null;      // the "main" losing tile. if prizes go out of stock, this tile will have its odds increased 15_surplusPrizeOdds = 0;          // if a prize is out of stock, add its probability to "NO WIN" (or another losing tile)16_spinsLeft = null;              // number of spins a user has left, in the current game  17_stopAngle = null;              // angle for the wheel to stop at ( using weighted probability )18_selectedPrizeIndex = null;     // index array, corresponds to `segments`19_currentUser = CreateNewUser(); // generates a "clean" user object 20_isFormRequired = false;21_isFormComplete = false;22var userFormId = "user-form";23// let audio = new Audio('../assets/audio/tick.mp3');  // Create audio object and load tick.mp3 file.24let sfx = {25    'boing' : new Audio('../assets/audio/boing.mp3'),26    'laugh' : new Audio('../assets/audio/laugh-track.mp3'),27    'drumroll' : new Audio('../assets/audio/drumroll.mp3'),28    'ta-da' : new Audio('../assets/audio/ta-da.wav'),29    'tick' : new Audio('../assets/audio/tick.mp3'),30    'tick-old' : new Audio('../assets/audio/tick-old.mp3')31}32let _wheelOptions = {};         // wheel options are empty by default33let wheelSpinning = false;34let theWheel = new Winwheel( _wheelOptions ); // Actual Wheel35// -----------------------------------------------------------------36// Wheel + User/Player Data :: Set up the wheel from page variables37// -----------------------------------------------------------------38function CreateNewUser()39{40    return { 41        name: "unset",42        email: "unset",43        phone: "unset",44        wheelId: "default-wheel-id",45        prizeWon: null,46        numSpins: 0,47        "timestamp" : GetTimeStampNow()48    }49};50function SetupWheelData()51{52    // create a **duplicate**, non-pointer copy, of the _rawData["wheelName"] object53    _currentWheel = jQuery.extend( true , {} , _rawData[ _currentWheelType ] );54    _currentWheelBackup = jQuery.extend( true , {} , _rawData[ _currentWheelType ] );55    // verify 56        // console.log( "_currentWheel :: " + PrettyPrint( _currentWheel ) );57}58function UpdateUIFromWheelData()59{60    _isFormRequired = _currentWheel["_meta"]["requireFormToSpin"]; 61}62function RestoreWheelDataFromBackup()63{64    const swalWithBootstrapButtons = Swal.mixin({65        customClass: {66            confirmButton: 'btn btn-success',67            cancelButton: 'btn btn-danger'68        },69        buttonsStyling: false70    })71    72    swalWithBootstrapButtons.fire({73        title: 'Are you sure?',74        text: "This will revert your wheel to a previous version. You will <em>not</em> be able to revert this!",75        type: 'warning',76        showCancelButton: true,77        confirmButtonText: 'Yes, delete it!',78        cancelButtonText: 'No, cancel!',79        reverseButtons: true80    }).then((result) => {81        if (result.value) {82            // console.log( "reset ");83            _currentWheel = jQuery.extend( true , {} , _currentWheelBackup );84            UpdateStatDisplays();85            swalWithBootstrapButtons.fire(86                'Restored!',87                'We have restored your <strong>_currentWheel</strong> from <strong>_currentWheelBackup</strong>.',88                'success'89            )90        } else if (91            /* Read more about handling dismissals below */92            result.dismiss === Swal.DismissReason.cancel93        ) {94            swalWithBootstrapButtons.fire(95                'Never Mind!',96                'Your <strong>_currentWheel</strong> data remains unchanged :)',97                'info'98            )99        }100    })101}102// -----------------------------------------------------------------103// Draw / create the wheel104// -----------------------------------------------------------------105function SetWheelBackground()106{107    // pull a background from the input screen, or default if no value is provided108    var userUrl = document.getElementById("wheel-background-input").value;109    var bgUrl = userUrl ? userUrl : "../assets/img/wheel_back.png";110    document.getElementsByClassName("wheel-background")[0].style.backgroundImage = 'url("' + bgUrl + '")';111}112function UpdateWheelTypeFromInput()113{114    // Determine the type of wheel to load 115    var wheelType = document.getElementById("raw-data-input").value;116    if ( wheelType == "" ){117        console.log( 'Gotta set a name! Setting to Default :: "taccom" ::' );118        wheelType = "taccom";119    }120    // Update the global variable 121    _currentWheelType = wheelType;122    SetupWheelData(); 123    UpdateWheelFromRawData(); 124    UpdateStatDisplays();125}126function UpdateWheelFromRawData()127{128    // Prepare for incoming data 129    resetWheel();130    UpdateUIFromWheelData(); 131    // Pull data from the current wheel type132    console.log( "wheelData : " + _currentWheel );133    console.log( "Pull Content from Data: " + _currentWheel.segments[ 3 ].text );134    // Create a new wheel135    theWheel = new Winwheel( _currentWheel ); // targets "let theWheel" below136    // Try using image, after the wheel has been initialized 137    UseImageOnWheel();138    UpdatePageAfterResize(); // scale down, in case wheel is too large for the screen139        // NOTE :: this is not working too well. Will have to investigate, later 140}141function UseImageOnWheel()142{143    let loadedImg = new Image();    // Create new image object in memory.144    // Create callback to execute once the image has finished loading.145    loadedImg.onload = function()146    {147        theWheel.wheelImage = loadedImg;    // Make wheelImage equal the loaded image object.148        theWheel.draw();                    // Also call draw function to render the wheel.149    }150    // Set the image source, once complete this will trigger the onLoad callback (above).151    loadedImg.src = "../assets/img/taccom/wheel.png";152}153function UpdatePageAfterResize()154{155	var canvas = document.getElementById('canvas');156    var canvasWidth = canvas.width;157        // console.log( "canvasWidth :: " + canvasWidth );158    canvas.height = canvasWidth;159    // OPTIONAL :: Re-Center the Wheel160    // In order to keep the wheel in the center of the canvas the centerX and161    // centerY need to be set to the middle point of the canvas.162        // theWheel.centerX = (canvas.width / 2);163        // theWheel.centerY = (canvas.height / 2);164}165// -------------------------------------------------------166// Random Number Generation167// -------------------------------------------------------168function GetWeightedRandom( items , chances )169{170    // https://stackoverflow.com/a/55671924171    var sum = chances.reduce((acc, el) => acc + el, 0);172    var acc = 0;173    chances = chances.map(el => (acc = el + acc));174    var rand = Math.random() * sum;175    return items[chances.filter(el => el <= rand).length];176}177function ParsePrizes()178{179    var segments = _currentWheel["segments"];     // TODO :: Make this the "_currentWheel"180        // console.log( "Segments Data :: " , segments );181    // reset prize arrays182    _arrayOfPrizes.length = 0;183    _arrayOfPrizeOdds.length = 0;184    _arrayOfPrizeIndex.length = 0;185    // reset odds186    _indexOfLosingTile = null;187    _surplusPrizeOdds = 0;188    // populate the array of prizes, and prize odds ( used by GetWeightedRandom() )189    var numberOfSegments = segments.length;190    for( var i = 0 ; i < numberOfSegments ; i++ )191    {192        // create an entry for each prize listed193        _arrayOfPrizes.push( segments[i]["text"] );194        _arrayOfPrizeIndex.push( i );195        196        // fast access 197        var odds = parseInt( segments[i]["odds"] );198        // THEORY :: 199        // If a prize quantity reaches 0, set the odds of winning it to 0, and add its odds to _surplusPrizeOdds200        // If a tile is a LOSING TILE, add _surplusPrizeOdds to its odds 201        if( segments[i]["lose"] === true )202        {203            _arrayOfPrizeOdds.push( odds + _surplusPrizeOdds ); 204            _indexOfLosingTile = i;         // Update the new losing tile 205            _surplusPrizeOdds = 0;          // Reset surplus odds 206        }207        else if( segments[i]["quantity"] > parseInt( 0 ) ) 208        {209            _arrayOfPrizeOdds.push( odds ); // The prize is in stock. Assign default odds. 210        } 211        else {212            _arrayOfPrizeOdds.push( 0 );    // Set the odds of winning this prize to 0213            _surplusPrizeOdds += odds;      // Increase the odds of losing, proportionate to the prize 214            // Edge Case215            // The last item in the array is NOT a losing tile, and is ALSO out of stock216            if( i + 1 === numberOfSegments ) {217                if( _indexOfLosingTile !== null ){218                    _arrayOfPrizeOdds[ _indexOfLosingTile ] += _surplusPrizeOdds; 219                    console.log( "The final prize in the array is out of stock. Adding its value to the last known losing tile." );220                } else {221                    console.log( "The final prize in the array is out of stock, and no tiles have been designated as 'losing tiles'. Odds for other prizes will increase uniformly." );222                }223            }224            console.log( _arrayOfPrizes );225            console.log( _arrayOfPrizeOdds );226        }227    }228    // testing229        // console.log( "_arrayOfPrizes :: " + _arrayOfPrizes );230        // console.log( "_arrayOfPrizeOdds :: " + _arrayOfPrizeOdds );231}232function DeterminePrize()233{234    // get updated values from the data array ( in case a prize was won in the meantime )235    ParsePrizes();236    // Determine a prize ( weighted probability )237    _selectedPrizeIndex = GetWeightedRandom( _arrayOfPrizeIndex , _arrayOfPrizeOdds )238        // var selectedPrize = GetWeightedRandom( _arrayOfPrizes , _arrayOfPrizeOdds )239        console.log( "Selected Prize Index :: " + _selectedPrizeIndex );240        console.log( "Selected Prize :: " + _currentWheel["segments"][_selectedPrizeIndex].text );241    // update the user object with the prize242    _currentUser.prizeWon = _arrayOfPrizes[ _selectedPrizeIndex ];243    // get the segment range for the selected prize244    var angleRange = GetAngleForSegment( _selectedPrizeIndex );245        // console.log( "angleRange :: " + angleRange.minAngle + " to " + angleRange.maxAngle );246    // use the segment range to calculate a random angle within the prize range247    _stopAngle = ( Math.floor(Math.random() * angleRange.safeRange ) + angleRange.minAngle )248    // Important thing is to set the stopAngle of the animation before stating the spin.249    theWheel.animation.stopAngle = _stopAngle;250    // Test the spin251        // startSpin();252}253function ResetPrize()254{255    _selectedPrizeIndex = null;256}257function GetAngleForSegment( selectedIndex )258{259    var numSegments = _currentWheel["segments"].length;260    var degreesPerSegment = 360 / numSegments;261        // console.log( "segments : " + numSegments + " || degrees per : " + degreesPerSegment );262    return {263        "safeRange" : degreesPerSegment -2,264        "minAngle" : ( selectedIndex * degreesPerSegment ) + 1,   // avoid segment seams :: http://dougtesting.net/winwheel/docs/tut14_setting_the_prize265        "maxAngle" : ( selectedIndex * degreesPerSegment ) + degreesPerSegment - 1    // upper range of a segment266    }267}268// -----------------------------------------------------------------269// Stat Management ( Prize + Winner )270// -----------------------------------------------------------------271function ParsePrizePool()272{273    // get prize array274    // count through each one275}276function UpdatePrizePool()277{278    var obj = _currentWheel["segments"];279    // Testing 280        // console.log( obj );281        // console.log( _selectedPrizeIndex );282        // console.log( obj[_selectedPrizeIndex] );283    // Quantity should not matter for losing tiles.  284    if( obj[_selectedPrizeIndex]["lose"] === true ){ return; }285    // Remove the prize from the pool (presumably, it has been given out)286    // IMPORTANT :: if "quantity" hits 0, that prize will no longer be served 287    // The probability of winning is added to the nearest "lose tile" - refer to : ParsePrizes()288    obj[_selectedPrizeIndex]["quantity"]--;289    obj[_selectedPrizeIndex]["timesWon"]++;290    291    // Testing292        // console.log( "Removing prize from pool" );293        // var str = JSON.stringify(obj);294        // str = JSON.stringify(obj, null, 4); // (Optional) beautiful indented output.295        // console.log(str); // Logs output to dev tools console.296}297function UpdateWinners()298{299    _currentWheel["_meta"]["arrayOfWinners"].push( GetUserFormData() );300}301function CanSpinAgain()302{303    if( _currentUser.numSpins < _currentWheel._meta.maxSpinsPerUser ){304        return true;305    }306}307// -----------------------------------------------------------------308// Data Presentation309// -----------------------------------------------------------------310function PrettyPrint( input )311{312    var str = JSON.stringify( input );313    str = JSON.stringify( input , null , 4 ); // (Optional) beautiful indented output.314        // VERIFY :: console.log( str ); 315    return str;316}317function UpdateStatDisplays()318{319    // check that all statistics are up-to-date320        // TODO - call relevant update functions321    // display them inside the right fields322        // TODO - merge from form-helpers :: starting to get lots of overlap // common variables323    $('#stat-prizes').text( PrettyPrint( _currentWheel["segments"] ) );324    $('#stat-winners').text( PrettyPrint( _currentWheel["_meta"]["arrayOfWinners"] ) );325}326// -----------------------------------------------------------------327// Animations + Sounds + Effects328// -----------------------------------------------------------------329function AnimateTicker()330{331    TweenMax.to( "#ticker" , 0.3 , { rotation: -25 } );332    TweenMax.to( "#ticker" , 0.6 , { rotation:0, delay: 0.5 } );333}334function PlaySfx( fx ) // only works on mouse DOWN events335{336    sfx[fx].pause();337    sfx[fx].currentTime = 0;338    sfx[fx].play();339}340function playSound()341{342    // This function is called when the segment under the prize pointer changes343    PlaySfx( "tick" );      // play a sound with every tick 344    AnimateTicker();        // tick the ticker345}346function EffectScrambleTitle( data )347{348    // There seems to be a bug with this garbage. If the revealDelay is greater than 1 second, it just shows XXOOXOXOXO 349    // 100 bucks not well spent. Fucking clown. 350    351    setTimeout(function()352    { 353        TweenLite.to( "#scramble-title" , 1, { 354            scrambleText: {355                text: data , 356                chars: "PYFGCRLAOEUIDHTNSQJKXBMWVZ" , 357                revealDelay:0.5, 358                speed:0.3359                // newClass:"myClass"360            }361        });362        363    }, 2200);364}365// -------------------------------------------------------366// User Interaction367// -------------------------------------------------------368function startSpin()369{370    TriggerKeptPlaying(); // Increase the amount of time before the game resets from inactivity. 371    if( !CheckFormValidity() ){ return; } // go no further if data is incomplete372    // Ensure that spinning can't be clicked again while already running.373    if (wheelSpinning == false)374    {375        _currentUser.numSpins++; // the user has "officially" spun the wheel 376        DeterminePrize(); // determine the prize (using weighted probability)377        // Play Sounds 378        PlaySfx( "boing" ); // fun stuff on button press379        setTimeout( function(){380            PlaySfx( "drumroll" )381        }, 1250 );382        383        // Set wheelSpinning to true so that power can't be changed and spin button re-enabled during the current animation.384        // IMPORTANT :: The user will have to reset before spinning again.385        theWheel.startAnimation();386        wheelSpinning = true;387    }388}389function resetWheel()390{391    console.log( "resetting the wheel"); 392    theWheel.stopAnimation(false);  // Stop the animation, false as param so does not call callback function.393    theWheel.rotationAngle = 0;     // Re-set the wheel angle to 0 degrees.394    theWheel.draw();                // Call draw to render changes to the wheel.395    wheelSpinning = false;          // Reset to false to power buttons and spin can be clicked again.396}397function ToggleConfetti()398{399    confetti.toggle();400}401function RestartGame()402{403    // Get the wheel and data ready for a new user. 404    405    ClearGameTicker();                  // Stop checking to see if the player walked away 406    resetWheel();                       // Return the wheel to its upright position 407    _currentUser = CreateNewUser();     // Clear the player object 408    ResetForm();                        // Return the form elements to their original state409    $('#layer-input').show();           // Display the form layer 410    ResumeGame();                       // Restore to original state 411    ClearFocusedInput();                // keyboard-helpers.js 412    // IMPORTANT :: Do -NOT- reset the wheel DATA, as it contains the winners list!   413}414function ClaimPrize() 415{416    // Once the user CLAIMS their prize, the result is final 417    UpdateWinners();        // Adds the current user to the array of winners 418    UpdatePrizePool();      // Remove chosen prize from the prize pool (if applicable). 419    UpdateStatDisplays();   // Populate arrays in the admin panel ( IMPORTANT - do this AFTER updating winners and prizes! )420    SubmitForm();           // Send a message te the server.421    ResetPrize();           // We no longer need the _selectedPrizeIndex variable. Reset it. // marcus 422    RestartGame();          // On to the next! 423}424// -----------------------------------------------------------------425// UX Event Handlers426// -----------------------------------------------------------------427function alertPrize( indicatedSegment )428{429    // Called when the spin animation has finished by the callback feature of the wheel because I specified callback in the parameters430    // note the indicated segment is passed in as a parmeter as 99% of the time you will want to know this to inform the user of their prize.431    432    PauseGame();            // Pause game while reading this modal 433    _spinsLeft = _currentWheel._meta.maxSpinsPerUser - _currentUser.numSpins;434    var prizeTitle = "";    // Title that is initially shown at the top of the alert modal435    var revealTitle = "";   // Title that is revealed after it is unscrambled 436    var prizeIcon = "";     // e.g. success, error, info - see SweetAlert2 for more options 437    var htmlContent = "";   // The meat of the alert message  438    // Determine the post-spin message 439    if( indicatedSegment.lose === true ) 440    {    441        PlaySfx( "laugh" ); 442        443        prizeTitle = "<strong><span id='scramble-title'>OH NO!</span></strong>"; 444        revealTitle = "BETTER LUCK NEXT TIME!";445        prizeIcon = "error";446        447        if( CanSpinAgain() ){ 448            htmlContent = 449                '<img src="../assets/img/taccom/logo.png"/>' + 450                '<br>You landed on <b>' + indicatedSegment.text + '</b>.' + 451                '<div class="spacer_10"></div>' + 452                '<br>Do you want to <b class="uppercase">try again</b>?' +453                '<div class="spacer_10"></div>' + 454                '<br><h3 class="giant-faded-data">Spins Left: <span id="spins-left">' + _spinsLeft + '</span></h3>' + 455                '<br><strong>You have <timer></timer> seconds to choose!</strong>';456            } else {457                htmlContent = 458                '<img src="../assets/img/taccom/logo.png"/>' + 459                '<br>Looks like you ran out of spins...' +460                '<div class="spacer_10"></div>' + 461                '<br><b>Keep your chin up!</b>' +462                '<br>There\'s always next year!' + 463                '<div class="spacer_10"></div>' + 464                '<br><strong>This message will self-destruct in <timer></timer> seconds!</strong>';465        }466    } 467    else 468    {469        confetti.start();470        PlaySfx( "ta-da" ); 471        472        prizeTitle = "<strong><span id='scramble-title'>YOU WIN!</span></strong>"; 473        revealTitle = "CONGRATULATIONS!";474        prizeIcon = "success";475        if( CanSpinAgain() ){ 476            htmlContent = 477                '<img src="../assets/img/taccom/logo.png"/>' + 478                '<br>You scored the <b>' + indicatedSegment.text + '</b>!' + 479                '<div class="spacer_10"></div>' + 480                '<br><b class="uppercase">Claim your prize</b> or risk it to <b class="uppercase">spin again</b>?' +481                '<div class="spacer_10"></div>' + 482                '<br><h3 class="giant-faded-data">Spins Left: <span id="spins-left">' + _spinsLeft + '</span></h3>' + 483                '<br><strong>You have <timer></timer> seconds to choose!</strong>';484            } else {485                htmlContent = 486                '<img src="../assets/img/taccom/logo.png"/>' + 487                '<br>Looks like you ran out of spins...' +488                '<div class="spacer_10"></div>' + 489                '<br>Your final prize is the <b>' + indicatedSegment.text + '</b>!' + 490                '<div class="spacer_10"></div>' + 491                '<br><strong>This message will self-destruct in <timer></timer> seconds!</strong>';492        }493    }494    495    // Sweet Alert Modal 496    Swal.fire({497        // Animation Effects498        animation: false,499        customClass: {500            popup: 'animated tada'501        },502        // Content503        title: prizeTitle, // '<strong>CONGRATULATIONS!</strong>504        type: prizeIcon, // 'success'505        html: htmlContent,506        // Interaction507        showCloseButton: true,508        showCancelButton: CanSpinAgain(), // true,509        focusConfirm: false,510        confirmButtonText:511            '<i class="fa fa-thumbs-up"></i> Claim Prize!',512        confirmButtonAriaLabel: 'Thumbs up, great!',513        cancelButtonText:514            '<i class="fa fa-thumbs-down"></i> Spin Again',515        cancelButtonAriaLabel: 'Thumbs down',516        timer: parseInt( _currentWheel._meta.prizeCountdownTimer ),517        onBeforeOpen: () => {518            // Swal.showLoading()519            timerInterval = setInterval(() => {520                Swal.getContent().querySelector('timer')521                .textContent = parseInt( Swal.getTimerLeft() / 1000 )522            }, 100)523        },524        onOpen: () => {525            EffectScrambleTitle( revealTitle );526        },527        onClose: () => {528            clearInterval( timerInterval );529            confetti.stop();530            if ( _spinsLeft > 0 ) 531            {532                TriggerKeptPlaying(); // Increase the amount of time before the game resets from inactivity. 533                resetWheel(); // Return the wheel to its default position, ready to spin. 534                ResumeGame(); // Un-pause the game 535            }536            else {537                console.log( 'Closed the window with the X button, with no spins left!' );538                Swal.fire(539                    'DEFAULT!',540                    '<strong>Nice try!</strong> You ended up with: ' + indicatedSegment.text + '.',541                    'info'542                )543                ClaimPrize();  544            }545        }546        }).then((result) => {547            if (result.value) 548            {549                console.log( "You have CLAIMED the prize!" );550                Swal.fire(551                    'Hurray!',552                    'Please head over to the counter, and <strong>claim your prize!</strong>',553                    'success'554                )555                ClaimPrize(); 556            }557            558            else if ( result.dismiss === Swal.DismissReason.cancel ) 559            {560                console.log( "The player was able (and has chosen) to spin again." )561                resetWheel(); 562            }563            else if ( result.dismiss === Swal.DismissReason.timer) 564            {565                console.log( 'Win alert was closed by the timer. Auto-choice was made!' );566                Swal.fire(567                    'DEFAULT!',568                    '<strong>Too slow!</strong> You ended up with: ' + indicatedSegment.text + '.',569                    'info'570                )571                ClaimPrize();  572            }573    }); // Ends Swal.fire574}575// -----------------------------------------------------------------576// Layer Control577// -----------------------------------------------------------------578function InitLayers()579{580    if( _isFormRequired === false ){581        document.getElementById( 'layer-input' ).style.display = 'none'; // https://stackoverflow.com/a/13688269582    }583}584function ToggleAdmin()585{586    var $adminLayer = $('#layer-admin');587    588    if( $adminLayer.is(":visible") )589    {590        $adminLayer.hide();591        ResumeGame();592    } 593    else {594        $adminLayer.show();595        PauseGame();596    }597}598// -----------------------------------------------------------------599// User Registration Form600// -----------------------------------------------------------------601function ResetForm()602{603    // Wipe form Inputs 604    $('#user-name').val("");605    $('#user-phone').val("");606    $('#user-email').val("");607    608    // Hide form elements 609    HideKeyboardOnGameRestart(); // keyboard-helper.js 610    $('#register-user').hide(); // hide the mega-button (until the form is re-validated)611}612function CheckFormCompletion()613{614    // Both Completion() and Validity() are required 615    // Validity() uses native HTML form validation; completion doesn't require submit616    // If we use Validity() to check the form on keyup events, the form cannot be completed617    // Because a fake Submit() action will remove the input element from focus 618    // SOURCE :: https://stackoverflow.com/a/11867013619    if( _isFormRequired === false ){ return true; }620    if( $('#user-name').val() === "" ||621    $('#user-phone').val() === "" ||622    $('#user-email').val() === "" ) {623        return false;624    }625    return true;626}627function CheckFormValidity()628{629    // SOURCE :: https://stackoverflow.com/a/11867013630    // If the form is invalid, submit it. The form won't actually submit;631    // this will just cause the browser to display the native HTML5 error messages.632        // NOTE :: This will ONLY work if there is a submit button somewhere on the form ( even if its CSS is "display: none;" )633    634    var $myForm = $('#user-form'); // TODO - bump this to an external variable 635    636    if( ! $myForm[0].checkValidity() ) {637        $myForm.find(':submit').click(); 638        return false;639    } else {640        return true; 641    }642}643function UpdateRegisterButtonStyle()644{645    // Use CheckFormCompletion() because it doesn't require the form to be submitted646        // Submitting the form causes the focus() to shift from the input element, causing trouble 647    if( CheckFormCompletion() === true ){648        $('#register-user').delay(2200).fadeIn(2200);649            // console.log( "FORM COMPLETION is TRUE");650    } else {651        $('#register-user').hide(); 652            // console.log( "FORM COMPLETION is FALSE");653    }654}655function RegisterUser()656{657    if( !CheckFormValidity() ){ return; } // go no further form is not valid 658    // create an entry for the current user659    _currentUser.name = $('#user-name').val();660    _currentUser.phone = $('#user-phone').val();661    _currentUser.email = $('#user-email').val();662    // display the wheel663    $('#layer-input').hide();664}665function GetUserFormData()666{667    return _currentUser;668}669function SubmitForm()670{671    if( _isFormRequired === false ){672        console.log( "Form is NOT required. NOT submitting anything to the server." );673        return;674    }675    676    if( !CheckFormValidity() ){ return; } // go no further if data is incomplete :: safety check 677    var userData = GetUserFormData();678        console.log( "collecting form data : " , userData );679    // Simulate server680    StoreOnServer();681    // call the server to save the data682    AsePostWheelData();683        console.log( "Submitting the form" );684}685// -----------------------------------------------------------------686// Timer Functions687// -----------------------------------------------------------------688// When the player touches the screen, a timer starts. Each time the player touches the screen, the timer continues to reset. 689// If the player has not touched the screen in X seconds, the game will reset, and present an alert message. 690// TODO :: Move these into the wheel data.js file 691_isGamePaused = false;      // Obvious variable is obvious 692_gameTicker = null;         // Handle for the timer that starts when the user touches the form 693_tickInterval = 1000;       // One tick is 1000 ms ( 1 second )694_ticksUntilReset = 0;       // Amount of ticks a player starts with (usually measured in seconds). 695_maximumTicks = 60;         // We don't want to give the player *too* much time 696_tickTouchBoost = 5;        // How many ticks does each touch of the screen add? 697// Each "tick" is a cycle in the game loop 698function StartGameTicker()699{700    if( !_gameTicker ){701        _ticksUntilReset += _tickTouchBoost * 2;            // Initial amount of time 702        _gameTicker = setInterval( Tick , _tickInterval );   // Start the timer 703        console.log( "Assigning setInterval to _gameTicker" ); 704    } else {705        console.log( "_gameTicker already exists!" ); 706    }707}708function ClearGameTicker()709{710    clearInterval( _gameTicker ); 711    _ticksUntilReset = 0;712    _gameTicker = null; 713}714function Tick()715{716    if( _isGamePaused ){ return; } // don't do anything if the game is paused. 717    // Every 1000 ms, remove 1 tick 718    _ticksUntilReset --; 719    if( _ticksUntilReset < 1 ){720        TriggerPlayerWalkedAway(); 721    }722    console.log( "_ticksUntilReset :: " + _ticksUntilReset );723}724function PauseGame() { 725    _isGamePaused = true;726}727function ResumeGame() {728    _isGamePaused = false; 729}730// These functions are trigger responses to a user action 731function TriggerKeptPlaying()732{733    // Each time the player touches the screen, add to the ticker 734    _ticksUntilReset += _tickTouchBoost;735    // ensure we never get too high a number 736    if( _ticksUntilReset > _maximumTicks ){737        _ticksUntilReset = _maximumTicks;738    }739}740function TriggerPlayerWalkedAway()741{742    console.log( 'Player walked away from the game!' );743    PauseGame(); // only want the alert to fire once 744    Swal.fire({745        // Content746        title: 'TIME-OUT RESET' , 747        type: 'info' , 748        html: 'The player took too long to fill the form, or waited too long between spins. The game has reset.' ,749        // Interaction750        showCloseButton: true,751        onClose: () => {752            console.log( "called RestartGame() from the info box! it SHOULD restart" );753            RestartGame();  754        }755    });756}757// -----------------------------------------------------------------758// Server Functions759// -----------------------------------------------------------------760function GetTimeStampNow()761{762    return Math.floor(Date.now() / 1000);763}764function SendMessageToServer( message )765{766    // will have jquery form submit767}768// -----------------------------------------------------------------769// Mock Server Functions770// -----------------------------------------------------------------771function StoreOnServer()772{773    const person = {774        name: "Obaseki Nosa",775        location: "Lagos",776    }777    window.localStorage.setItem('user', JSON.stringify( _currentUser ));778}779function ReadFromServer()780{781    console.log( JSON.parse(window.localStorage.getItem('user')) );782}783// -----------------------------------------------------------------784// Ase area785// -----------------------------------------------------------------786function AsePostWheelData()787{788    // Ase789    // Have a look here ::790    // https://api.jquery.com/jQuery.post/791    console.log( "Calling :: AsePostWheelData()" );792    // return;793    let url = "/api/save-prize-winners"794    console.log(_currentWheel)795    $.ajax({796        type: "POST",797        url: url,798        data: {799            winners: JSON.stringify(_currentWheel._meta.arrayOfWinners)800        },801        success: function( data )802        {803            console.log(data);804            Swal.fire({805                title: 'You got a response!',806                type: 'success',807                html: '<p>' + PrettyPrint( data ) + '</p>', // 'success'808            });809        },810        error: function(data){811            console.log(data)  812            let msg = "An Error Occured. Please, try again or contact management if it persist."813            if(data.responseText != undefined){814                msg = "Error:- " + data.responseText815            }816            Swal.fire({817                title: 'You got a response!',818                type: 'error',819                html: '<p>' + PrettyPrint( msg ) + '</p>', // 'success'820            });               821        }822        // dataType: dataType823    });824}825function AseGetWinners()826{827    console.log( "Calling :: AseGetWinners()" );828    // return;829    let url = "/api/download-winners"830    window.open(url, '_blank');831    // $.ajax({832    //     type: "GET",833    //     url: url,834    //     data: {},835    //     success: function( data )836    //     {837    //         console.log( data );838    //         Swal.fire({839    //             title: 'You got a response!',840    //             type: 'success',841    //             html: '<p>' + PrettyPrint( data ) + '</p>', // 'success'842    //         });843    //     },844    //     // dataType: dataType845    // });846}847function AseGetPrizes()848{849    console.log( "Calling :: AseGetPrizes()" );850    let url = "/api/download-prizes"851    window.open(url, '_blank');852    // $.ajax({853    //     type: "GET",854    //     url: url,855    //     data: {},856    //     success: function( data )857    //     {858    //         console.log( data );859    //         Swal.fire({860    //             title: 'You got a response!',861    //             type: 'success',862    //             html: '<p>' + PrettyPrint( data ) + '</p>', // 'success'863    //         });864    //     },865    // });866}867//Change to the selected wheel type868function AseChangeWheelType(wheelType){869    console.log(wheelType)870    if ( wheelType == "" || _rawData[wheelType] == ""){871        console.log( 'Gotta set a name! Setting to Default :: "taccom" ::' );872        wheelType = "taccom";873    }874    // Update the global variable 875    _currentWheelType = wheelType;876    877    UpdateWheelFromRawData(); 878    UpdateStatDisplays();879    880    console.log( 'Wheel Type changed to :: '+ wheelType );881}882// -----------------------------------------------------------------883// Initialization - Set Everything Up884// -----------------------------------------------------------------885$(document).ready(function()886{887    // Wheel Data888    SetupWheelData(); // This must be done ONCE, the first time the page loads. Afterward, UpdateWheelTypeFromInput() takes over. 889    UpdateWheelFromRawData();890    ParsePrizes();891    // DOM Event Handlers 892    $('#click-to-test-sound').mousedown(function(){893        PlaySfx( "boing" );894    });895    // UI / UX 896    confetti.stop(); // pause confetti by default!897    InitLayers();...

Full Screen

Full Screen

DockWheel.js

Source:DockWheel.js Github

copy

Full Screen

1/**2 * Manages the dock overlay buttons that are displayed over the dock manager3 */4dockspawn.DockWheel = function(dockManager)5{6    this.dockManager = dockManager;7    this.elementMainWheel = document.createElement("div");    // Contains the main wheel's 5 dock buttons8    this.elementSideWheel = document.createElement("div");    // Contains the 4 buttons on the side9    this.wheelItems = {};10    var wheelTypes = [11        "left", "right", "top", "down", "fill",     // Main dock wheel buttons12        "left-s", "right-s", "top-s", "down-s"      // Buttons on the extreme 4 sides13    ];14    var self = this;15    wheelTypes.forEach(function(wheelType)16    {17        self.wheelItems[wheelType] = new DockWheelItem(self, wheelType);18        if (wheelType.substr(-2, 2) == "-s")19            // Side button20            self.elementSideWheel.appendChild(self.wheelItems[wheelType].element);21        else22            // Main dock wheel button23            self.elementMainWheel.appendChild(self.wheelItems[wheelType].element);24    });25    var zIndex = 100000;26    this.elementMainWheel.classList.add("dock-wheel-base");27    this.elementSideWheel.classList.add("dock-wheel-base");28    this.elementMainWheel.style.zIndex = zIndex + 1;29    this.elementSideWheel.style.zIndex = zIndex;30    this.elementPanelPreview = document.createElement("div");  // Used for showing the preview of where the panel would be docked31    this.elementPanelPreview.classList.add("dock-wheel-panel-preview");32    this.elementPanelPreview.style.zIndex = zIndex - 1;33    this.activeDialog = undefined;  // The dialog being dragged, when the wheel is visible34    this._activeNode = undefined;35    this._visible = false;36};37/** The node over which the dock wheel is being displayed on */38Object.defineProperty(dockspawn.DockWheel.prototype, "activeNode", {39    get: function() { return this._activeNode; },40    set: function(value)41    {42        var previousValue = this._activeNode;43        this._activeNode = value;44        if (previousValue !== this._activeNode)45        {46            // The active node has been changed.47            // Reattach the wheel to the new node's element and show it again48            if (this._visible)49                this.showWheel();50        }51    }52});53dockspawn.DockWheel.prototype.showWheel = function()54{55    this._visible = true;56    if (!this.activeNode)57    {58        // No active node selected. make sure the wheel is invisible59        removeNode(this.elementMainWheel);60        removeNode(this.elementSideWheel);61        return;62    }63    var element = this.activeNode.container.containerElement;64    var containerWidth = element.clientWidth;65    var containerHeight = element.clientHeight;66    var baseX = Math.floor(containerWidth / 2) + element.offsetLeft;67    var baseY = Math.floor(containerHeight / 2) + element.offsetTop;68    this.elementMainWheel.style.left = baseX + "px";69    this.elementMainWheel.style.top = baseY + "px";70    // The positioning of the main dock wheel buttons is done automatically through CSS71    // Dynamically calculate the positions of the buttons on the extreme sides of the dock manager72    var sideMargin = 20;73    var dockManagerWidth = this.dockManager.element.clientWidth;74    var dockManagerHeight = this.dockManager.element.clientHeight;75    var dockManagerOffsetX = this.dockManager.element.offsetLeft;76    var dockManagerOffsetY = this.dockManager.element.offsetTop;77    removeNode(this.elementMainWheel);78    removeNode(this.elementSideWheel);79    element.appendChild(this.elementMainWheel);80    this.dockManager.element.appendChild(this.elementSideWheel);81    this._setWheelButtonPosition("left-s",   sideMargin, -dockManagerHeight / 2);82    this._setWheelButtonPosition("right-s",  dockManagerWidth - sideMargin * 2, -dockManagerHeight / 2);83    this._setWheelButtonPosition("top-s",    dockManagerWidth / 2, -dockManagerHeight + sideMargin);84    this._setWheelButtonPosition("down-s",   dockManagerWidth / 2, -sideMargin);85};86dockspawn.DockWheel.prototype._setWheelButtonPosition = function(wheelId, left, top)87{88    var item = this.wheelItems[wheelId];89    var itemHalfWidth = item.element.clientWidth / 2;90    var itemHalfHeight = item.element.clientHeight / 2;91    var x = Math.floor(left - itemHalfWidth);92    var y = Math.floor(top - itemHalfHeight);93//    item.element.style.left = "${x}px";94//    item.element.style.top = "${y}px";95    item.element.style.marginLeft = x + "px";96    item.element.style.marginTop = y + "px";97};98dockspawn.DockWheel.prototype.hideWheel = function()99{100    this._visible = false;101    this.activeNode = undefined;102    removeNode(this.elementMainWheel);103    removeNode(this.elementSideWheel);104    removeNode(this.elementPanelPreview);105    // deactivate all wheels106    for (var wheelType in this.wheelItems)107        this.wheelItems[wheelType].active = false;108};109dockspawn.DockWheel.prototype.onMouseOver = function(wheelItem, e)110{111    if (!this.activeDialog)112        return;113    // Display the preview panel to show where the panel would be docked114    var rootNode = this.dockManager.context.model.rootNode;115    var bounds;116    if (wheelItem.id == "top") {117        bounds = this.dockManager.layoutEngine.getDockBounds(this.activeNode, this.activeDialog.panel, "vertical", true);118    } else if (wheelItem.id == "down") {119        bounds = this.dockManager.layoutEngine.getDockBounds(this.activeNode, this.activeDialog.panel, "vertical", false);120    } else if (wheelItem.id == "left") {121        bounds = this.dockManager.layoutEngine.getDockBounds(this.activeNode, this.activeDialog.panel, "horizontal", true);122    } else if (wheelItem.id == "right") {123        bounds = this.dockManager.layoutEngine.getDockBounds(this.activeNode, this.activeDialog.panel, "horizontal", false);124    } else if (wheelItem.id == "fill") {125        bounds = this.dockManager.layoutEngine.getDockBounds(this.activeNode, this.activeDialog.panel, "fill", false);126    } else if (wheelItem.id == "top-s") {127        bounds = this.dockManager.layoutEngine.getDockBounds(rootNode, this.activeDialog.panel, "vertical", true);128    } else if (wheelItem.id == "down-s") {129        bounds = this.dockManager.layoutEngine.getDockBounds(rootNode, this.activeDialog.panel, "vertical", false);130    } else if (wheelItem.id == "left-s") {131        bounds = this.dockManager.layoutEngine.getDockBounds(rootNode, this.activeDialog.panel, "horizontal", true);132    } else if (wheelItem.id == "right-s") {133        bounds = this.dockManager.layoutEngine.getDockBounds(rootNode, this.activeDialog.panel, "horizontal", false);134    }135    if (bounds)136    {137        this.dockManager.element.appendChild(this.elementPanelPreview);138        this.elementPanelPreview.style.left = Math.round(bounds.x) + "px";139        this.elementPanelPreview.style.top = Math.round(bounds.y) + "px";140        this.elementPanelPreview.style.width = Math.round(bounds.width) + "px";141        this.elementPanelPreview.style.height = Math.round(bounds.height) + "px";142    }143};144dockspawn.DockWheel.prototype.onMouseOut = function(wheelItem, e)145{146    removeNode(this.elementPanelPreview);147};148/**149 * Called if the dialog is dropped in a dock panel.150 * The dialog might not necessarily be dropped in one of the dock wheel buttons,151 * in which case the request will be ignored152 */153dockspawn.DockWheel.prototype.onDialogDropped = function(dialog)154{155    // Check if the dialog was dropped in one of the wheel items156    var wheelItem = this._getActiveWheelItem();157    if (wheelItem)158        this._handleDockRequest(wheelItem, dialog);159};160/**161 * Returns the wheel item which has the mouse cursor on top of it162 */163dockspawn.DockWheel.prototype._getActiveWheelItem = function()164{165    for (var wheelType in this.wheelItems)166    {167        var wheelItem = this.wheelItems[wheelType];168        if (wheelItem.active)169            return wheelItem;170    }171    return undefined;172};173dockspawn.DockWheel.prototype._handleDockRequest = function(wheelItem, dialog)174{175    if (!this.activeNode)176        return;177    if (wheelItem.id == "left") {178        this.dockManager.dockDialogLeft(this.activeNode, dialog);179    } else if (wheelItem.id == "right") {180        this.dockManager.dockDialogRight(this.activeNode, dialog);181    } else if (wheelItem.id == "top") {182        this.dockManager.dockDialogUp(this.activeNode, dialog);183    } else if (wheelItem.id == "down") {184        this.dockManager.dockDialogDown(this.activeNode, dialog);185    } else if (wheelItem.id == "fill") {186        this.dockManager.dockDialogFill(this.activeNode, dialog);187    } else if (wheelItem.id == "left-s") {188        this.dockManager.dockDialogLeft(this.dockManager.context.model.rootNode, dialog);189    } else if (wheelItem.id == "right-s") {190        this.dockManager.dockDialogRight(this.dockManager.context.model.rootNode, dialog);191    } else if (wheelItem.id == "top-s") {192        this.dockManager.dockDialogUp(this.dockManager.context.model.rootNode, dialog);193    } else if (wheelItem.id == "down-s") {194        this.dockManager.dockDialogDown(this.dockManager.context.model.rootNode, dialog);195    }196};197function DockWheelItem(wheel, id)198{199    this.wheel = wheel;200    this.id = id;201    var wheelType = id.replace("-s", "");202    this.element = document.createElement("div");203    this.element.classList.add("dock-wheel-item");204    this.element.classList.add("disable-selection");205    this.element.classList.add("dock-wheel-" + wheelType);206    this.element.classList.add("dock-wheel-" + wheelType + "-icon");207    this.hoverIconClass = "dock-wheel-" + wheelType + "-icon-hover";208    this.mouseOverHandler = new dockspawn.EventHandler(this.element, 'mouseover', this.onMouseMoved.bind(this));209    this.mouseOutHandler = new dockspawn.EventHandler(this.element, 'mouseout', this.onMouseOut.bind(this));210    this.active = false;    // Becomes active when the mouse is hovered over it211};212DockWheelItem.prototype.onMouseMoved = function(e)213{214    this.active = true;215    this.element.classList.add(this.hoverIconClass);216    this.wheel.onMouseOver(this, e);217};218DockWheelItem.prototype.onMouseOut = function(e)219{220    this.active = false;221    this.element.classList.remove(this.hoverIconClass);222    this.wheel.onMouseOut(this, e);...

Full Screen

Full Screen

events.js

Source:events.js Github

copy

Full Screen

1// Copyright (c) %%year%% by Code Computerlove (http://www.codecomputerlove.com)2// Licensed under the MIT license3// version: %%version%%4(function (window, Util) {5	6	Util.extend(Util, {7		8		Events: {9			10			11			/*12			 * Function: add13			 * Add an event handler14			 */15			add: function(obj, type, handler){16				17				this._checkHandlersProperty(obj);18				19				if (type === 'mousewheel'){20					type = this._normaliseMouseWheelType();21				}22				23				if (typeof obj.__eventHandlers[type] === 'undefined'){24					obj.__eventHandlers[type] = [];25				}26				obj.__eventHandlers[type].push(handler);27				28				// DOM element 29				if (this._isBrowserObject(obj)){30					obj.addEventListener(type, handler, false);31				}32				33			},34			35			36			37			/*38			 * Function: remove39			 * Removes a handler or all handlers associated with a type40			 */41			remove: function(obj, type, handler){42				43				this._checkHandlersProperty(obj);44				45				if (type === 'mousewheel'){46					type = this._normaliseMouseWheelType();47				}48				49				if (obj.__eventHandlers[type] instanceof Array){50					51					var52						i, j,53						handlers = obj.__eventHandlers[type];54					55					// Removing all handlers for a type56					if (Util.isNothing(handler)){57						58						if (this._isBrowserObject(obj)){59							for (i=0, j=handlers.length; i<j; i++){60								obj.removeEventListener(type, handlers[i], false);61							}62						}63						64						obj.__eventHandlers[type] = [];65						return;66					}67					68					// Removing a specific handler69					for (i=0, j=handlers.length; i<j; i++){70						if (handlers[i] === handler){71							handlers.splice(i, 1);72							break;73						}74					}75					76					// DOM element 77					if (this._isBrowserObject(obj)){78						obj.removeEventListener(type, handler, false);79						return;80					}81				82				}83			84			},85			86			87			/*88			 * Function: fire89			 * Fire an event90			 */91			fire: function(obj, type){92				93				var 94					i, j,95					event,96					listeners,97					listener,98					args = Array.prototype.slice.call(arguments).splice(2),99					isNative;100				101				102				if (type === 'mousewheel'){103					type = this._normaliseMouseWheelType();104				}105				106				107				// DOM element 108				if (this._isBrowserObject(obj)){109				110					if (typeof type !== "string"){111						throw 'type must be a string for DOM elements';112					}113					114					isNative = this._NATIVE_EVENTS[type];115					event = document.createEvent(isNative ? "HTMLEvents" : "UIEvents"); 116					event[isNative ? 'initEvent' : 'initUIEvent'](type, true, true, window, 1);117					118					// Fire an event on an element that has no extra arguments119					if (args.length < 1){120						obj.dispatchEvent(event);121						return;122					}123				124				}125				126				this._checkHandlersProperty(obj);127				128				if (typeof type === "string"){129					event = { type: type };130				}131				else{132					event = type;133				}134				if (!event.target){135					event.target = obj;136				}137				if (!event.type){ 138					throw new Error("Event object missing 'type' property.");139				}140				if (obj.__eventHandlers[event.type] instanceof Array){141					listeners = obj.__eventHandlers[event.type];142					args.unshift(event);143					for (i=0, j=listeners.length; i<j; i++){144						listener = listeners[i];145						if (!Util.isNothing(listener)){146							listener.apply(obj, args);147						}148					}149				}150				151			},152			153			154			/*155			 * Function: getMousePosition156			 */157			getMousePosition: function(event){158				159				var retval = {160					x: 0,161					y: 0162				};163				164				if (event.pageX) {165					retval.x = event.pageX;166				}167				else if (event.clientX) {168					retval.x = event.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft);169				}170			171				if (event.pageY) {172					retval.y = event.pageY;173				}174				else if (event.clientY) {175					retval.y = event.clientY + ( document.documentElement.scrollTop || document.body.scrollTop);176				}177				178				return retval;179			},180			181			182			/*183			 * Function: getTouchEvent184			 */185			getTouchEvent: function(event){186				187				return event;188			189			},190			191			192			193			/*194			 * Function: getWheelDelta195			 */196			getWheelDelta: function(event){197				198				var delta = 0;199				200				if (!Util.isNothing(event.wheelDelta)){201					delta = event.wheelDelta / 120;202				}203				else if (!Util.isNothing(event.detail)){204					delta = -event.detail / 3;205				}206				207				return delta;208				209			},210			211			212			/*213			 * Function: domReady214			 */215			domReady: function(handler){216				217				document.addEventListener('DOMContentLoaded', handler, false);218			219			},220			221			222			_checkHandlersProperty: function(obj){223				224				if (Util.isNothing(obj.__eventHandlers)){225					Util.extend(obj, {226						__eventHandlers: { }227					});228				}229			230			},231			232			233			_isBrowserObject: function(obj){234				if (obj === window || obj === window.document){235					return true;236				}237				return this._isElement(obj) || this._isNode(obj);238			},239			240			241			_isElement: function(obj){242				return (243					typeof window.HTMLElement === "object" ? obj instanceof window.HTMLElement : //DOM2244					typeof obj === "object" && obj.nodeType === 1 && typeof obj.nodeName==="string"245				);246			},247			248			249			250			_isNode: function(obj){251				return (252					typeof window.Node === "object" ? obj instanceof window.Node : 253					typeof obj === "object" && typeof obj.nodeType === "number" && typeof obj.nodeName==="string"254				);255			},256			257			258			259			_normaliseMouseWheelType: function(){260				261				if (Util.Browser.isEventSupported('mousewheel')){262					return 'mousewheel';263				}264				return 'DOMMouseScroll';265				266			},267			268			269			270			_NATIVE_EVENTS: { 271				click: 1, dblclick: 1, mouseup: 1, mousedown: 1, contextmenu: 1, //mouse buttons272				mousewheel: 1, DOMMouseScroll: 1, //mouse wheel273				mouseover: 1, mouseout: 1, mousemove: 1, selectstart: 1, selectend: 1, //mouse movement274				keydown: 1, keypress: 1, keyup: 1, //keyboard275				orientationchange: 1, // mobile276				touchstart: 1, touchmove: 1, touchend: 1, touchcancel: 1, // touch277				gesturestart: 1, gesturechange: 1, gestureend: 1, // gesture278				focus: 1, blur: 1, change: 1, reset: 1, select: 1, submit: 1, //form elements279				load: 1, unload: 1, beforeunload: 1, resize: 1, move: 1, DOMContentLoaded: 1, readystatechange: 1, //window280				error: 1, abort: 1, scroll: 1 281			}282			283		}284	285		286	});287	288	289}290(291	window,292	window.Code.Util...

Full Screen

Full Screen

WheelScriptPC.js

Source:WheelScriptPC.js Github

copy

Full Screen

1@script AddComponentMenu ("CarPhys/Scripts/Wheel Script")2#pragma strict3enum wheelType { Steer , SteerAndMotor , Motor , JustAWheel}; //types of wheel4var typeOfWheel : wheelType;	//Object of wheelType5var handBreakable : boolean = false;	//can apply handbrakes6var invertSteer : boolean = false;	//invert the steer control7var wheelTransform : Transform;		//Mesh of the wheel8private var speedFactor : float;	//switch between steer angles9private var wheelCollider : WheelCollider;		//wheel collider attached to the same game object10private var carScript : CarControleScript;		//Scripts attached on the car object at the top11private var mySidewayFriction : float;	//default value12private var myForwardFriction : float;	//default value13private var slipSidewayFriction : float;	//Custom value14private var slipForwardFriction : float;	//Custom value15//Start16function Start () {17wheelCollider = gameObject.GetComponent(WheelCollider);18carScript = transform.root.gameObject.GetComponent("CarControleScript");19SetValues();20}21//Assign values22function SetValues(){23myForwardFriction  = wheelCollider.forwardFriction.stiffness;24mySidewayFriction  = wheelCollider.sidewaysFriction.stiffness;25slipForwardFriction = 0.05;26slipSidewayFriction = 0.085;27}28function Update () {29WheelPosition();30ReverseSlip();31//Rotation Control32wheelTransform.Rotate(wheelCollider.rpm/60*360*Time.deltaTime,0,0);33if (typeOfWheel == wheelType.Steer || typeOfWheel == wheelType.SteerAndMotor)34wheelTransform.localEulerAngles.y = wheelCollider.steerAngle - wheelTransform.localEulerAngles.z;35}36//Triggers to different types of wheels and for handbrake37function FixedUpdate (){38if (typeOfWheel == wheelType.Motor || typeOfWheel == wheelType.SteerAndMotor){39TorqueControle ();40}41if (typeOfWheel == wheelType.Steer || typeOfWheel == wheelType.SteerAndMotor){42SteerControle ();43}44if(handBreakable){45HandBrake();46}47if(!carScript.braked){48Decellaration();49}50}51//Position the wheel52function WheelPosition(){53var hit : RaycastHit;54var wheelPos : Vector3;55if (Physics.Raycast(transform.position, -transform.up,hit,wheelCollider.radius+wheelCollider.suspensionDistance) ){56wheelPos = hit.point+transform.up * wheelCollider.radius;57}58else {59wheelPos = transform.position -transform.up* wheelCollider.suspensionDistance; 60}61wheelTransform.position = wheelPos;62}63//Decellaration64function Decellaration(){65if (Input.GetButton("Vertical")==false){66wheelCollider.brakeTorque = carScript.decellarationSpeed;67}68else{69wheelCollider.brakeTorque = 0;70}71}72//Steer Control73function SteerControle (){74speedFactor = transform.parent.root.GetComponent.<Rigidbody>().velocity.magnitude/carScript.lowestSteerAtSpeed;75var currentSteerAngel = Mathf.Lerp(carScript.lowSpeedSteerAngel,carScript.highSpeedSteerAngel,speedFactor);76if (invertSteer)77currentSteerAngel *= -Input.GetAxis("Horizontal");78else 79currentSteerAngel *= Input.GetAxis("Horizontal");80wheelCollider.steerAngle = currentSteerAngel;81}82//Torque Control83function TorqueControle (){84if (carScript.currentSpeed < carScript.topSpeed && carScript.currentSpeed > -carScript.maxReverseSpeed && !carScript.braked){85wheelCollider.motorTorque = carScript.maxTorque * Input.GetAxis("Vertical");86}87else {88wheelCollider.motorTorque =0;89}90}91//Hand Brake92function HandBrake(){93if(carScript.braked){94if(carScript.currentSpeed > 1){95SetRearSlip(slipForwardFriction ,slipSidewayFriction); 96}97else if (carScript.currentSpeed < 0){98SetRearSlip(1 ,1); 99}100wheelCollider.sidewaysFriction.extremumValue = 300;101wheelCollider.brakeTorque = carScript.maxBrakeTorque;102wheelCollider.motorTorque =0;103if (carScript.currentSpeed < 1 && carScript.currentSpeed > -1){104carScript.backLightObject.GetComponent.<Renderer>().material = carScript.idleLightMaterial;105}106else {107carScript.backLightObject.GetComponent.<Renderer>().material = carScript.brakeLightMaterial;108}109}110else {111wheelCollider.sidewaysFriction.extremumValue = 10000;112wheelCollider.brakeTorque = 0;113SetRearSlip(myForwardFriction ,mySidewayFriction); 114}115}116//Reverse Slip117function ReverseSlip(){118if (carScript.currentSpeed <0){119SetFrontSlip(slipForwardFriction ,slipSidewayFriction); 120}121else {122SetFrontSlip(myForwardFriction ,mySidewayFriction);123}124}125//Slip Settings126function SetRearSlip (currentForwardFriction : float,currentSidewayFriction : float){127if (typeOfWheel == wheelType.Motor || typeOfWheel == wheelType.SteerAndMotor && !carScript.braked){128wheelCollider.forwardFriction.stiffness = currentForwardFriction;129wheelCollider.sidewaysFriction.stiffness = currentSidewayFriction;130}131}132function SetFrontSlip (currentForwardFriction : float,currentSidewayFriction : float){133if (typeOfWheel == wheelType.Steer || typeOfWheel == wheelType.SteerAndMotor && !carScript.braked){134wheelCollider.forwardFriction.stiffness = currentForwardFriction;135wheelCollider.sidewaysFriction.stiffness = currentSidewayFriction;136}...

Full Screen

Full Screen

controls-specs.js

Source:controls-specs.js Github

copy

Full Screen

...20        return wheel21          .getAttribute("value")22            .should.eventually.contain("65")23          .then(function () {24            return wheel.type("70")25              .getAttribute("value")26                .should.eventually.contain("70");27          });28      })29      .elementByXPath("//UIAPickerWheel[@name = 'Green color component value']")30      .then(function (wheel) {31        return wheel32            .type("70")33            .getAttribute("value")34              .should.eventually.contain("70");35      })36      .elementByXPath("//UIAPickerWheel[@name = 'Blue color component value']")37      .then(function (wheel) {38        return wheel...

Full Screen

Full Screen

test3.js

Source:test3.js Github

copy

Full Screen

1/*jshint expr:true */2define(['squire'], function(Squire) {3  describe('squire', function() {4    describe('require', function() { 5      it('should require my specified dependencies', function(done) {6        var squire = new Squire();7        squire.require(['bike'], function(Bike) {8          Bike.should.exist;9          t = new Bike()10          t.wheelType().should.equal('real wheel')11          done();12        });13      });14      it('should require my mock', function(done) {15        var squire = new Squire();16        squire17         .mock('wheel', function(){ return function() { return {type: function() {return "kdjfkdjf"}} }} )18         .require(['bike'], function(Bike) {19            t = new Bike()20            t.wheelType().should.equal('kdjfkdjf')21            done();22         });23      });24    })25  })...

Full Screen

Full Screen

jin_dom_event_onWheel.env=web.jam.js

Source:jin_dom_event_onWheel.env=web.jam.js Github

copy

Full Screen

1/**2 * @name $jin.dom.event.onWheel3 * @class $jin.dom.event.onWheel4 * @returns $jin.dom.event.onWheel5 * @mixins $jin.klass6 * @mixins $jin.dom.event7 */8$jin.klass({ '$jin.dom.event.onWheel': [ '$jin.dom.event' ] })9/**10 * @name $jin.dom.event.onWheel.type11 * @method type12 * @static13 * @member $jin.dom.event.onWheel14 */15$jin.method({ '$jin.dom.event.onWheel.type': function( ){16    this['$jin.event.type']17    return 'wheel'...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const wd = require('wd');2const chai = require('chai');3const chaiAsPromised = require('chai-as-promised');4chai.use(chaiAsPromised);5chai.should();6chaiAsPromised.transferPromiseness = wd.transferPromiseness;7const desired = {8};9const driver = wd.promiseChainRemote('localhost', 4723);10driver.init(desired)11  .then(() => driver.execute('mobile: scroll', {direction: 'down'}))12  .then(() => driver.execute('mobile: scroll', {direction: 'up'}))13  .then(() => driver.execute('mobile: scroll', {direction: 'left'}))14  .then(() => driver.execute('mobile: scroll', {direction: 'right'}))15  .then(() => driver.execute('mobile: scroll', {direction: 'down', element: 'some xpath'}))16  .then(() => driver.execute('mobile: scroll', {direction: 'up', element: 'some xpath'}))17  .then(() => driver.execute('mobile: scroll', {direction: 'left', element: 'some xpath'}))18  .then(() => driver.execute('mobile: scroll', {direction: 'right', element: 'some xpath'}))19  .then(() => driver.execute('mobile: scroll', {direction: 'down', element: 'some xpath', toVisible: true}))20  .then(() => driver.execute('mobile: scroll', {direction: 'up', element: 'some xpath', toVisible: true}))21  .then(() => driver.execute('mobile: scroll', {direction: 'left', element: 'some xpath', toVisible: true}))22  .then(() => driver.execute('mobile: scroll', {direction: 'right', element: 'some xpath', toVisible: true}))23  .then(() => driver.quit());24const wd = require('wd');25const chai = require('chai');26const chaiAsPromised = require('chai-as-promised');27chai.use(chaiAsPromised);28chai.should();29chaiAsPromiseness = wd.transferPromiseness;30const desired = {

Full Screen

Using AI Code Generation

copy

Full Screen

1var wd = require('wd');2var assert = require('assert');3var desired = {4};5    .init(desired)6    .then(() => browser.elementById('lst-ib'))7    .then((el) => browser.type(el, 'Hello World'))8    .then(() => browser.quit());

Full Screen

Using AI Code Generation

copy

Full Screen

1const wd = require('wd');2const assert = require('assert');3const opts = {4};5driver.init(opts)6  .then(() => driver.execute('mobile: scroll', {direction: 'down'}))7  .then(() => driver.execute('mobile: scroll', {direction: 'up'}))8  .then(() => driver.execute('mobile: scroll', {direction: 'left'}))9  .then(() => driver.execute('mobile: scroll', {direction: 'right'}))10  .then(() => driver.execute('mobile: scroll', {direction: 'down', element: 'element-id'}))11  .then(() => driver.execute('mobile: scroll', {direction: 'up', element: 'element-id'}))12  .then(() => driver.execute('mobile: scroll', {direction: 'left', element: 'element-id'}))13  .then(() => driver.execute('mobile: scroll', {direction: 'right', element: 'element-id'}))14  .then(() => driver.execute('mobile: scroll', {direction: 'down', element: 'element-id', toVisible: true}))15  .then(() => driver.execute('mobile: scroll', {direction: 'up', element: 'element-id', toVisible: true}))16  .then(() => driver.execute('mobile: scroll', {direction: 'left', element: 'element-id', toVisible: true}))17  .then(() => driver.execute('mobile: scroll', {direction: 'right', element: 'element-id', toVisible: true}))18  .then(() => driver.execute('mobile: scroll', {direction: 'down', element: 'element-id', predicateString: 'label == "label-name"'}))19  .then(() => driver.execute('mobile: scroll', {direction: 'up', element: 'element-id', predicateString: 'label == "label-name"'}))20  .then(() => driver.execute('mobile: scroll', {direction: 'left', element: 'element-id', predicateString: 'label == "label-name"'}))

Full Screen

Using AI Code Generation

copy

Full Screen

1var wd = require('wd');2var serverConfig = {3};4var desiredCaps = {5};6var driver = wd.promiseChainRemote(serverConfig);7driver.init(desiredCaps)8    .then(function () {9        return driver.elementByAccessibilityId('test-Label');10    })11    .then(function (element) {12        return element.text();13    })14    .then(function (text) {15        console.log(text);16    })17    .then(function () {18        return driver.elementByAccessibilityId('test-Button');19    })20    .then(function (element) {21        return element.click();22    })23    .then(function () {24        return driver.elementByAccessibilityId('test-Label');25    })26    .then(function (element) {27        return element.text();28    })29    .then(function (text) {30        console.log(text);31    })32    .then(function () {33        return driver.elementByAccessibilityId('test-Wheel');34    })35    .then(function (element) {36        return element.type('Hello World');37    })38    .then(function () {39        return driver.elementByAccessibilityId('test-Label');40    })41    .then(function (element) {42        return element.text();43    })44    .then(function (text) {45        console.log(text);46    })47    .fin(function () {48        return driver.quit();49    })50    .done();

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('wheel.type', function() {2  it('should type in a wheel', async function() {3    await driver.wheel.type('Hello World');4  });5});6describe('wheel.type', function() {7  it('should type in a wheel', async function() {8    await driver.wheel.type('Hello World');9  });10});11describe('wheel.type', function() {12  it('should type in a wheel', async function() {13    await driver.wheel.type('Hello World');14  });15});16describe('wheel.type', function() {17  it('should type in a wheel', async function() {18    await driver.wheel.type('Hello World');19  });20});21describe('wheel.type', function() {22  it('should type in a wheel', async function() {23    await driver.wheel.type('Hello World');24  });25});26describe('wheel.type', function() {27  it('should type in a wheel', async function() {28    await driver.wheel.type('Hello World');29  });30});31describe('wheel.type', function() {32  it('should type in a wheel', async function() {33    await driver.wheel.type('Hello World');34  });35});36describe('wheel.type', function() {37  it('should type in a wheel', async function() {38    await driver.wheel.type('Hello World');39  });40});41describe('wheel.type', function() {42  it('should type in a wheel', async function() {43    await driver.wheel.type('Hello World');44  });45});46describe('wheel.type', function() {47  it('should type in a wheel', async function() {48    await driver.wheel.type('Hello World');49  });50});

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('Test', function() {2    it('should get the value of the element', function () {3        browser.url('/');4        var wheel = browser.element('.XCUIElementTypePickerWheel');5        var value = wheel.getAttribute('value');6        console.log(value);7    });8});9describe('Test', function() {10    it('should get the value of the element', function () {11        browser.url('/');12        var wheel = browser.element('.XCUIElementTypePickerWheel');13        var value = wheel.getAttribute('value');14        console.log(value);15    });16});17describe('Test', function() {18    it('should get the value of the element', function () {19        browser.url('/');20        var wheel = browser.element('.XCUIElementTypePickerWheel');21        var value = wheel.getAttribute('value');22        console.log(value);23    });24});25describe('Test', function() {26    it('should get the value of the element', function () {27        browser.url('/');28        var wheel = browser.element('.XCUIElementTypePickerWheel');29        var value = wheel.getAttribute('value');30        console.log(value);31    });32});33describe('Test', function() {34    it('should get the value of the element', function () {35        browser.url('/');36        var wheel = browser.element('.XCUIElementTypePickerWheel');

Full Screen

Using AI Code Generation

copy

Full Screen

1var type = element.type;2console.log("The type of the element is " + type);3var type = element.type;4console.log("The type of the element is " + type);5var type = element.type;6console.log("The type of the element is " + type);7var type = element.type;8console.log("The type of the element is " + type);9var type = element.type;10console.log("The type of the element is " + type);

Full Screen

Using AI Code Generation

copy

Full Screen

1var wheel = require('wd').io.appium.xcuitest.wheel;2wheel.type('Hello World');3var wheel = require('wd').io.appium.xcuitest.wheel;4wheel.pinch();5var wheel = require('wd').io.appium.xcuitest.wheel;6wheel.zoom();7var wheel = require('wd').io.appium.xcuitest.wheel;8wheel.scroll();9var wheel = require('wd').io.appium.xcuitest.wheel;10wheel.drag();11var wheel = require('wd').io.appium.xcuitest.wheel;12wheel.flick();13var wheel = require('wd').io.appium.xcuitest.wheel;14wheel.pinch();15var wheel = require('wd').io.appium.xcuitest.wheel;16wheel.zoom();17var wheel = require('

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

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

Run Appium Xcuitest Driver automation tests on LambdaTest cloud grid

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

Sign up Free
_

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful