Best JavaScript code snippet using appium
html-upload.js
Source:html-upload.js  
1/**2 * Copyright (C) 2005-2010 Alfresco Software Limited.3 *4 * This file is part of Alfresco5 *6 * Alfresco is free software: you can redistribute it and/or modify7 * it under the terms of the GNU Lesser General Public License as published by8 * the Free Software Foundation, either version 3 of the License, or9 * (at your option) any later version.10 *11 * Alfresco is distributed in the hope that it will be useful,12 * but WITHOUT ANY WARRANTY; without even the implied warranty of13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the14 * GNU Lesser General Public License for more details.15 *16 * You should have received a copy of the GNU Lesser General Public License17 * along with Alfresco. If not, see <http://www.gnu.org/licenses/>.18 */1920/**21 * HtmlUpload component.22 *23 * Popups a YUI panel and displays a filelist and buttons to browse for files24 * and upload them. Files can be removed and uploads can be cancelled.25 * For single file uploads version input can be submitted.26 *27 * A multi file upload scenario could look like:28 *29 * var htmlUpload = Alfresco.getHtmlUploadInstance();30 * var multiUploadConfig =31 * {32 *    siteId: siteId,33 *    containerId: doclibContainerId,34 *    path: docLibUploadPath,35 *    filter: [],36 *    mode: htmlUpload.MODE_MULTI_UPLOAD,37 * }38 * this.htmlUpload.show(multiUploadConfig);39 *40 * @namespace Alfresco41 * @class Alfresco.HtmlUpload42 * @extends Alfresco.component.Base43 */44(function()45{46   /**47    * YUI Library aliases48    */49   var Dom = YAHOO.util.Dom,50      KeyListener = YAHOO.util.KeyListener;5152   /**53    * Alfresco Slingshot aliases54    */55   var $html = Alfresco.util.encodeHTML;5657   /**58    * HtmlUpload constructor.59    *60    * HtmlUpload is considered a singleton so constructor should be treated as private,61    * please use Alfresco.getHtmlUploadInstance() instead.62    *63    * @param htmlId {String} The HTML id of the parent element64    * @return {Alfresco.HtmlUpload} The new HtmlUpload instance65    * @constructor66    * @private67    */68   Alfresco.HtmlUpload = function(htmlId)69   {70      Alfresco.HtmlUpload.superclass.constructor.call(this, "Alfresco.HtmlUpload", htmlId, ["button", "container"]); 7172      this.defaultShowConfig =73      {74         siteId: null,75         containerId: null,76         destination: null,77         uploadDirectory: null,78         updateNodeRef: null,79         updateFilename: null,80         updateVersion: "1.0",81         mode: this.MODE_SINGLE_UPLOAD,82         onFileUploadComplete: null,83         overwrite: false,84         thumbnails: null,85         uploadURL: null,86         username: null,87         suppressRefreshEvent: false,88         adobeFlashEnabled: true,89         maximumFileSize: 090      };91      this.showConfig = {};9293      return this;94   };9596   YAHOO.extend(Alfresco.HtmlUpload, Alfresco.component.Base,97   {98      /**99       * Shows uploader in single upload mode.100       *101       * @property MODE_SINGLE_UPLOAD102       * @static103       * @type int104       */105      MODE_SINGLE_UPLOAD: 1,106107      /**108       * Shows uploader in single update mode.109       *110       * @property MODE_SINGLE_UPDATE111       * @static112       * @type int113       */114      MODE_SINGLE_UPDATE: 2,115116      /**117       * The default config for the gui state for the uploader.118       * The user can override these properties in the show() method to use the119       * uploader for both single & multi uploads and single updates.120       *121       * @property defaultShowConfig122       * @type object123       */124      defaultShowConfig: null,125126      /**127       * The merged result of the defaultShowConfig and the config passed in128       * to the show method.129       *130       * @property defaultShowConfig131       * @type object132       */133      showConfig: null,134135      /**136       * HTMLElement of type div that displays the version input form.137       *138       * @property versionSection139       * @type HTMLElement140       */141      versionSection: null,142143      /**144       * The name of the currently selected file (not including its full path).145       *  146       * @property _fileName147       * @type String148       */149      _fileName: null,150151      /**152       * The size of the currently selected file. This will be null if a file has not been selected.153       *154       * @property _fileSize155       * @type number156       */157      _fileSize: null,158159      /**160       * Restricts the allowed maximum file size for a single file (in bytes).161       * 0 means there is no restriction.162       *163       * @property _maximumFileSizeLimit164       * @private165       * @type int166       * @default 0167       */168      _maximumFileSizeLimit: 0,169170      /**171       * Sets te maximum allowed size for one file.172       *173       * @method setMaximumFileSizeLimit174       * @param maximumFileSizeLimit175       */176      setMaximumFileSizeLimit: function DNDUpload_setMaximumFileSizeLimit(maximumFileSizeLimit)177      {178         this._maximumFileSizeLimit = maximumFileSizeLimit;179      },180181      /**182       * Returns the maximum allowed size for one file183       *184       * @method getMaximumFileSizeLimit185       */186      getMaximumFileSizeLimit: function DNDUpload_getInMemoryLimit()187      {188         return this._maximumFileSizeLimit;189      },190191      /**192       * Fired by YUI when parent element is available for scripting.193       * Initial History Manager event registration194       *195       * @method onReady196       */197      onReady: function HtmlUpload_onReady()198      {199         var _this = this;200         201         Dom.removeClass(this.id + "-dialog", "hidden");202203         // Create the panel204         this.widgets.panel = Alfresco.util.createYUIPanel(this.id + "-dialog");205206         // Save a reference to the HTMLElement displaying texts so we can alter the texts later207         this.widgets.titleText = Dom.get(this.id + "-title-span");208         this.widgets.singleUploadTip = Dom.get(this.id + "-singleUploadTip-span");209         this.widgets.singleUpdateTip = Dom.get(this.id + "-singleUpdateTip-span");210211         // Save references to hidden fields so we can set them later212         this.widgets.filedata = Dom.get(this.id + "-filedata-file");213         this.widgets.filedata.contentEditable = false;214         this.widgets.siteId = Dom.get(this.id + "-siteId-hidden");215         this.widgets.containerId = Dom.get(this.id + "-containerId-hidden");216         this.widgets.destination = Dom.get(this.id + "-destination-hidden");217         this.widgets.username = Dom.get(this.id + "-username-hidden");218         this.widgets.updateNodeRef = Dom.get(this.id + "-updateNodeRef-hidden");219         this.widgets.uploadDirectory = Dom.get(this.id + "-uploadDirectory-hidden");220         this.widgets.overwrite = Dom.get(this.id + "-overwrite-hidden");221         this.widgets.thumbnails = Dom.get(this.id + "-thumbnails-hidden");222223         // Save reference to version section elements so we can set its values later224         this.widgets.description = Dom.get(this.id + "-description-textarea");225         this.widgets.minorVersion = Dom.get(this.id + "-minorVersion-radioButton");226         this.widgets.versionSection = Dom.get(this.id + "-versionSection-div");227228         // Create and save a reference to the buttons so we can alter them later229         this.widgets.uploadButton = Alfresco.util.createYUIButton(this, "upload-button", null,230         {231            type: "submit"232         });233         this.widgets.cancelButton = Alfresco.util.createYUIButton(this, "cancel-button", this.onCancelButtonClick);234         235         // Configure the forms runtime236         var form = new Alfresco.forms.Form(this.id + "-htmlupload-form");237         this.widgets.form = form;238239         // Make sure we listen to the change event so we can store details about the file (name & size) and use it in validations below240         YAHOO.util.Event.addListener(this.id + "-filedata-file", "change", function()241         {242            if (this.files && this.files.length > 0)243            {244               _this._fileName = this.files[0].name;245               _this._fileSize = this.files[0].size;246            }247         });248249         // Title is mandatory (will look for the inout elements value)250         form.addValidation(this.id + "-filedata-file", Alfresco.forms.validation.mandatory, null, "change", this.msg("Alfresco.forms.validation.mandatory.message"));251252         // Internet Explorer does not support the "files" attribute for the input type file253         // so there is no point in adding validations254         if (YAHOO.env.ua.ie == 0)255         {256            // File name must work on all OS:s257            form.addValidation(this.id + "-filedata-file", function HtmlUpload_validateFileName(field, args)258            {259               return !YAHOO.lang.isString(_this._fileName) || Alfresco.forms.validation.nodeName({ id: field.id, value: _this._fileName }, args);260            }, null, "change", this.msg("message.illegalCharacters"));261262            // Make sure file doesn't exceed maximum file size263            form.addValidation(this.id + "-filedata-file", function HtmlUpload_validateMaximumFileSize(field, args)264            {265               return args.maximumFileSizeLimit == 0 || !YAHOO.lang.isNumber(_this._fileSize) || _this._fileSize <= args.maximumFileSizeLimit;266            }, { maximumFileSizeLimit: this._maximumFileSizeLimit }, "change", this.msg("message.maxFileFileSizeExceeded"));267268            // Make sure file isn't empty269            form.addValidation(this.id + "-filedata-file", function HtmlUpload_validateSize(field, args)270            {271               return !YAHOO.lang.isNumber(_this._fileSize) || _this._fileSize > 0;272            }, null, "change", this.msg("message.zeroByteFileSelected"));273         }274275         // The ok button is the submit button, and it should be enabled when the form is ready276         form.setSubmitElements(this.widgets.uploadButton);277         form.doBeforeFormSubmit =278         {279            fn: function()280            {281               this.widgets.cancelButton.set("disabled", true);282               this.widgets.panel.hide();283               this.widgets.feedbackMessage = Alfresco.util.PopupManager.displayMessage(284               {285                  text: Alfresco.util.message("message.uploading", this.name),286                  spanClass: "wait",287                  displayTime: 0,288                  effect: null289               });290            },291            obj: null,292            scope: this293         };294295         // Submit as an ajax submit (not leave the page), in json format296         form.setAJAXSubmit(true, {});297298         // We're in a popup, so need the tabbing fix299         form.applyTabFix();300         form.init();301302         // Register the ESC key to close the dialog303         this.widgets.escapeListener = new KeyListener(document,304         {305            keys: KeyListener.KEY.ESCAPE306         },307         {308            fn: this.onCancelButtonClick,309            scope: this,310            correctScope: true311         });312313         this.widgets.enterListener = new KeyListener(this.widgets.filedata,314         {315            keys: KeyListener.KEY.ENTER316         },317         {318            fn: function enter_key_pressed(obj)319            {320               this.widgets.filedata.click();321            },322            scope: this,323            correctScope: true324         });325         this.widgets.enterListener.enable();326      },327328      /**329       * Show can be called multiple times and will display the uploader dialog330       * in different ways depending on the config parameter.331       *332       * @method show333       * @param config {object} describes how the upload dialog should be displayed334       * The config object is in the form of:335       * {336       *    siteId: {string},        // site to upload file(s) to337       *    containerId: {string},   // container to upload file(s) to (i.e. a doclib id)338       *    destination: {string},   // destination nodeRef to upload to if not using site & container339       *    uploadPath: {string},    // directory path inside the component to where the uploaded file(s) should be save340       *    updateNodeRef: {string}, // nodeRef to the document that should be updated341       *    updateFilename: {string},// The name of the file that should be updated, used to display the tip342       *    mode: {int},             // MODE_SINGLE_UPLOAD or MODE_SINGLE_UPDATE343       *    filter: {array},         // limits what kind of files the user can select in the OS file selector344       *    onFileUploadComplete: null, // Callback after upload345       *    overwrite: false         // If true and in mode MODE_XXX_UPLOAD it tells346       *                             // the backend to overwrite a versionable file with the existing name347       *                             // If false and in mode MODE_XXX_UPLOAD it tells348       *                             // the backend to append a number to the versionable filename to avoid349       *                             // an overwrite and a new version350       * }351       */352      show: function HtmlUpload_show(config)353      {354         // Merge the supplied config with default config and check mandatory properties355         this.showConfig = YAHOO.lang.merge(this.defaultShowConfig, config);356         if (this.showConfig.uploadDirectory === undefined && this.showConfig.updateNodeRef === undefined)357         {358             throw new Error("An updateNodeRef OR uploadDirectory must be provided");359         }360         if (this.showConfig.uploadDirectory !== null && this.showConfig.uploadDirectory.length === 0)361         {362            this.showConfig.uploadDirectory = "/";363         }364         365         // Enable the Esc key listener366         this.widgets.escapeListener.enable();367368         this._showPanel();369      },370      371      /**372       * Hides the panel373       * 374       * @method hide375       */376      hide: function HtmlUpload_hide()377      {378         this.onCancelButtonClick();379      },380      381      /**382       * Called when a file has been successfully uploaded383       * Informs the user and reloads the doclib.384       *385       * @method onUploadSuccess386       */387      onUploadSuccess: function HtmlUpload_onUploadSuccess(response)388      {389         // Hide the current message display390         this.widgets.feedbackMessage.hide();391392         // Tell the document list to refresh itself if present393         var fileName = response.fileName ? response.fileName : this.widgets.filedata.value;394         if (!this.showConfig.suppressRefreshEvent)395         {396            YAHOO.Bubbling.fire("metadataRefresh",397            {398               currentPath: this.showConfig.path,399               highlightFile: fileName400            });401         }402              403         // Todo see if the nodeRef can be added to the list404         var objComplete =405         {406            successful: [407            {408               nodeRef: response.nodeRef,409               fileName: fileName,410               response: response  // Added for CSV upload411            }]412         };413414         var callback = this.showConfig.onFileUploadComplete;415         if (callback && typeof callback.fn == "function")416         {417            // Call the onFileUploadComplete callback in the correct scope418            callback.fn.call((typeof callback.scope == "object" ? callback.scope : this), objComplete, callback.obj);419         }420      },421422      /**423       * Called when a file failed to be uploaded424       * Informs the user.425       *426       * @method onUploadFailure427       */428      onUploadFailure: function HtmlUpload_onUploadFailure(e)429      {430         // Hide the current message display431         this.widgets.feedbackMessage.hide();432433         // Inform user that the upload failed434         var key = "message.failure." + e.status.code,435            text = Alfresco.util.message(key, this.name);436         if (text == key)437         {438            text = e.status.code ? e.status.code : Alfresco.util.message("message.failure", this.name);439         }440         Alfresco.util.PopupManager.displayPrompt(441         {442            title: Alfresco.util.message("message.failure", this.name),443            text: text444         });445      },446447      /**448       * Fired when the user clicks the cancel button.449       * Closes the panel.450       *451       * @method onCancelButtonClick452       * @param event {object} a Button "click" event453       */454      onCancelButtonClick: function HtmlUpload_onCancelButtonClick()455      {456         // Disable the Esc key listener457         this.widgets.escapeListener.disable();458459         // Hide the panel460         this.widgets.panel.hide();461      },462463      /**464       * Adjust the gui according to the config passed into the show method.465       *466       * @method _applyConfig467       * @private468       */469      _applyConfig: function HtmlUpload__applyConfig()470      {471         // Set the panel title472         var title;473         if (this.showConfig.mode === this.MODE_SINGLE_UPLOAD)474         {475            title = Alfresco.util.message("header.singleUpload", this.name);476         }477         else if (this.showConfig.mode === this.MODE_SINGLE_UPDATE)478         {479            title = Alfresco.util.message("header.singleUpdate", this.name);480         }481         this.widgets.titleText.innerHTML = title;482483         if (this.showConfig.mode === this.MODE_SINGLE_UPDATE)484         {485            var tip = Alfresco.util.message("label.singleUpdateTip", this.name,486            {487               "0": this.showConfig.updateFilename488            });489            this.widgets.singleUpdateTip.innerHTML = tip;490491            // Display the version input form492            Dom.removeClass(this.widgets.versionSection, "hidden");493            var versions = (this.showConfig.updateVersion || "1.0").split("."),494               majorVersion = parseInt(versions[0], 10),495               minorVersion = parseInt(versions[1], 10);496            Dom.get(this.id + "-minorVersion").innerHTML = this.msg("label.minorVersion.more", majorVersion + "." + (1 + minorVersion));497            Dom.get(this.id + "-majorVersion").innerHTML = this.msg("label.majorVersion.more", (1 + majorVersion) + ".0");498         }499         else500         {501            // Hide the version input form502            Dom.addClass(this.widgets.versionSection, "hidden");503         }504505         // Show the help label for single updates506         if (this.showConfig.mode === this.MODE_SINGLE_UPDATE)507         {508            // Show the help label for single updates509            Dom.removeClass(this.widgets.singleUpdateTip, "hidden");510            Dom.addClass(this.widgets.singleUploadTip, "hidden");511         }512         else513         {514            // Only show the "Install Flash" message if Flash is enabled via config515            Dom.addClass(this.widgets.singleUploadTip, "hidden");516            if (this.showConfig.adobeFlashEnabled)517            {518               // Show the help label for single uploads519               Dom.removeClass(this.widgets.singleUploadTip, "hidden");520            }521            Dom.addClass(this.widgets.singleUpdateTip, "hidden");522         }523524         this.widgets.cancelButton.set("disabled", false);525         this.widgets.filedata.value = null;526527         // Set the forms action url528         var formEl = Dom.get(this.id + "-htmlupload-form");529         if (this.showConfig.uploadURL === null)530         {531            // The .html suffix is required - it is not possible to do a multipart post using an ajax call.532            // So it has to be a FORM submit, to make it feel like an ajax call a a hidden iframe is used.533            // Since the component still needs to be called when the upload is finished, the script returns534            // an html template with SCRIPT tags inside that which calls the component that triggered it.535            formEl.action = Alfresco.constants.PROXY_URI + "api/upload.html";536         }537         else538         {539            formEl.action = Alfresco.constants.PROXY_URI + this.showConfig.uploadURL;540         }541542         // Set the hidden parameters543         this.widgets.siteId.value = this.showConfig.siteId;544         this.widgets.containerId.value = this.showConfig.containerId;545         this.widgets.destination.value = this.showConfig.destination;546         this.widgets.username.value = this.showConfig.username;547         if (this.showConfig.mode === this.MODE_SINGLE_UPDATE)548         {549            this.widgets.updateNodeRef.value = this.showConfig.updateNodeRef;550            this.widgets.uploadDirectory.value = "";551            this.widgets.overwrite.value = "";552            this.widgets.thumbnails.value = "";553         }554         else555         {556            this.widgets.updateNodeRef.value = "";557            this.widgets.uploadDirectory.value = this.showConfig.uploadDirectory;558            this.widgets.overwrite.value = this.showConfig.overwrite;559            this.widgets.thumbnails.value = this.showConfig.thumbnails;560         }561      },562563      /**564       * Prepares the gui and shows the panel.565       *566       * @method _showPanel567       * @private568       */569      _showPanel: function HtmlUpload__showPanel()570      {571         // Reset references and the gui before showing it572         this.widgets.description.value = "";573         this.widgets.minorVersion.checked = true;574575         // Apply the config before it is showed576         this._applyConfig();577578         // Show the upload panel579         this.widgets.panel.show();580      }581   });
...historic-properties-viewer.js
Source:historic-properties-viewer.js  
1/**2 * Copyright (C) 2005-2011 Alfresco Software Limited.3 *4 * This file is part of Alfresco5 *6 * Alfresco is free software: you can redistribute it and/or modify7 * it under the terms of the GNU Lesser General Public License as published by8 * the Free Software Foundation, either version 3 of the License, or9 * (at your option) any later version.10 *11 * Alfresco is distributed in the hope that it will be useful,12 * but WITHOUT ANY WARRANTY; without even the implied warranty of13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the14 * GNU Lesser General Public License for more details.15 *16 * You should have received a copy of the GNU Lesser General Public License17 * along with Alfresco. If not, see <http://www.gnu.org/licenses/>.18 */19 /**20 * HistoricPropertiesViewer component.21 *22 * Popups a YUI panel and lets the user view the properties (metadata) from previous versions of a document23 *24 * @namespace Alfresco.module25 * @class Alfresco.module.HistoricPropertiesViewer26 */27(function()28{29   /**30    * YUI Library aliases31    */32   var Dom = YAHOO.util.Dom,33         Event = YAHOO.util.Event,34         KeyListener = YAHOO.util.KeyListener;35   /**36    * HistoricPropertiesViewer constructor.37    *38    * HistoricPropertiesViewer is considered a singleton so constructor should be treated as private,39    * please use Alfresco.module.getHistoricPropertiesViewerInstance() instead.40    *41    * @param {string} htmlId The HTML id of the parent element42    * @return {Alfresco.module.HistoricPropertiesViewer} The new HistoricPropertiesViewer instance43    * @constructor44    * @private45    */46   Alfresco.module.HistoricPropertiesViewer = function(containerId)47   {48      this.name = "Alfresco.module.HistoricPropertiesViewer";49      this.id = containerId;50      var instance = Alfresco.util.ComponentManager.get(this.id);51      if (instance !== null)52      {53         throw new Error("An instance of Alfresco.module.HistoricPropertiesViewer already exists.");54      }55      /* Register this component */56      Alfresco.util.ComponentManager.register(this);57      // Load YUI Components58      Alfresco.util.YUILoaderHelper.require(["button", "container"], this.onComponentsLoaded, this);59      return this;60   };61   Alfresco.module.HistoricPropertiesViewer.prototype =62   {63      /**64       * The default config for the gui state for the historic properties dialog.65       * The user can override these properties in the show() method.66       *67       * @property defaultShowConfig68       * @type object69       */70      defaultShowConfig:71      {72         nodeRef: null,73         filename: null,74         version: null75      },76      /**77       * The merged result of the defaultShowConfig and the config passed in78       * to the show method.79       *80       * @property showConfig81       * @type object82       */83      showConfig: {},84      /**85       *  A local cache of the document version response86       *  this is retrieved during set up & updated on each show87       *88       *  @property versions89       *  @type array90       */91      versions: [],92      /**93       * A reference to the earliest version.94       * Set when creating the dropdown menu95       *96       * @property earliestVersion97       * @type object98       */99      earliestVersion: {},100      /**101       * Object container for storing YUI widget and HTMLElement instances.102       *103       * @property widgets104       * @type object105       */106      widgets: {},107      /**108       * Fired by YUILoaderHelper when required component script files have109       * been loaded into the browser.110       *111       * @method onComponentsLoaded112       */113      onComponentsLoaded: function HPV_onComponentsLoaded()114      {115         // Shortcut for dummy instance116         if (this.id === null)117         {118            return;119         }120      },121      /**122       * Show can be called multiple times and will display the dialog123       * in different ways depending on the config parameter.124       *125       * @method show126       * @param config {object} describes how the dialog should be displayed127       * The config object is in the form of:128       * {129       *    nodeRef: {string},  // the nodeRef130       *    version: {string}   // the version to show properties of131       * }132       */133      show: function HPV_show(config)134      {135         // Merge the supplied config with default config and check mandatory properties136         this.showConfig = YAHOO.lang.merge(this.defaultShowConfig, config);137         if (this.showConfig.nodeRef === undefined ||138             this.showConfig.filename === undefined ||139             this.showConfig.currentNodeRef === undefined)140         {141             throw new Error("A nodeRef, filename and version must be provided");142         }143         // Read versions from cache144         var documentVersions = Alfresco.util.ComponentManager.findFirst("Alfresco.DocumentVersions");145         if (documentVersions) {146            this.versions = documentVersions.versionCache;147         }148         // Check if the dialog has been showed before149         if (this.widgets.panel)150         {151            // It'll need updating, probably.152            this.update(this.showConfig.nodeRef);153            // The displaying.154            this._showPanel();155         }156         else157         {158            // If it hasn't load the gui (template) from the server159            Alfresco.util.Ajax.request(160            {161               url: Alfresco.constants.URL_SERVICECONTEXT + "modules/document-details/historic-properties-viewer?nodeRef=" + this.showConfig.currentNodeRef + "&htmlid=" + this.id,162               successCallback:163               {164                  fn: this.onTemplateLoaded,165                  scope: this166               },167               failureMessage: "Could not load html template for properties viewer",168               execScripts: true169            });170            // Register the ESC key to close the dialog171            this.widgets.escapeListener = new KeyListener(document,172            {173               keys: KeyListener.KEY.ESCAPE174            },175            {176               fn: this.onCancelButtonClick,177               scope: this,178               correctScope: true179            });180         }181      },182      /**183       * Called when the dialog html template has been returned from the server.184       * Creates the YIU gui objects such as the panel.185       *186       * @method onTemplateLoaded187       * @param response {object} a Alfresco.util.Ajax.request response object188       */189      onTemplateLoaded: function HPV_onTemplateLoaded(response)190      {191         // Inject the template from the XHR request into a new DIV element192         var containerDiv = document.createElement("div");193         containerDiv.innerHTML = response.serverResponse.responseText;194         var dialogDiv = YAHOO.util.Dom.getFirstChild(containerDiv);195         // Create the panel from the HTML returned in the server reponse196         this.widgets.panel = Alfresco.util.createYUIPanel(dialogDiv);197         // Create menu button:198         this.createMenu(dialogDiv);199         // Save a reference to the HTMLElement displaying texts so we can alter the text later200         this.widgets.headerText = Dom.get(this.id + "-header-span");201         this.widgets.cancelButton = Alfresco.util.createYUIButton(this, "cancel-button", this.onCancelButtonClick);202         this.widgets.formContainer = Dom.get(this.id + "-properties-form");203         // Set up Nav events:204         navEls = Dom.getElementsByClassName("historic-properties-nav", "a", this.id + "-dialog");205         Event.addListener(navEls[0], "click", this.onNavButtonClick, this, true);206         Event.addListener(navEls[1], "click", this.onNavButtonClick, this, true);207         this.updateNavState();208         // Load Form content209         this.loadProperties();210         // Show panel211         this._showPanel();212      },213      /**214       *215       * Fired when the option in the dropdown version menu is changed216       *217       * @method onVersionMenuChange218       *219       */220      onVersionMenuChange: function HPV_onVersionMenuChange(sType, aArgs, p_obj)221      {222         var domEvent = aArgs[0],223            eventTarget = aArgs[1],224            newNodeRef = eventTarget.value;225         // Update the display:226         this.update(newNodeRef);227      },228      /**229       *230       * This function updates the display, menu and config with a new NodeRef.231       *232       * @method update233       *234       */235      update: function HPV_update(newNodeRef)236      {237         if (newNodeRef) {238            // Update Config Node Ref.239            this.showConfig.nodeRef = newNodeRef;240            // Update the properties display241            this.loadProperties();242            // Update the Menu243            this.setMenuTitle();244            // Update the Navigation245            this.updateNavState();246         }247      },248      /**249       *250       * Determines if the Next and Previous buttons should be enabled.251       * Buttons are disabled by added a disabled class to them252       *253       * @method updateNavState254       *255       */256      updateNavState: function HPV_updateNavState()257      {258         var navEls = Dom.getElementsByClassName("historic-properties-nav", "a", this.id + "-dialog");259         // Start from a known state, default = enabled.260         Dom.removeClass(navEls, "disabled");261         if (this.showConfig.nodeRef === this.earliestVersion.nodeRef)262         {263            // At earliest, so disable the previous button264            Dom.addClass(navEls[0], "disabled");265         }266         else if (this.showConfig.nodeRef === this.showConfig.latestVersion.nodeRef)267         {268            // at latest, so disable the next button.269            Dom.addClass(navEls[1], "disabled");270         }271      },272      /**273       *274       * Instantiates a YUI Menu Button & Writes the Menu HTML for it.275       *276       * @method createMenu277       * @param {HTMLElement} The containing element for the Version History Dialogue278       *279       */280      createMenu: function HPV_createMenu(dialogDiv)281      {282         var menuContainer = Dom.get(this.id + "-versionNav-menu"),283            navContainer = Dom.getElementsByClassName("nav", "div", dialogDiv)[0],284            currentVersionHeader = document.createElement("h6"),285            previousVersionHeader = document.createElement("h6"),286            currentTitle = Alfresco.util.message("historicProperties.menu.title", this.name,287               {288                  "0": this.showConfig.latestVersion.label289               }),290            i, menuHTML = [], menuTitle;291         // Write HTML for menu & add current version and option groups to menu:292         menuHTML.push(293         {294            value: this.showConfig.latestVersion.nodeRef,295            text: currentTitle296         });297         // Add an option element for each of the previous versions298         for (i in this.versions) {299            var version = this.versions[i],300               title = Alfresco.util.message("historicProperties.menu.title", this.name,301                  {302                     "0": version.label303                  });304            // Check if this version is the earliest available305            if (parseInt(i, 10) === this.versions.length - 1)306            {307               this.earliestVersion = version;308            }309            menuHTML.push(310            {311               value: version.nodeRef,312               text: title313            });314            if (version.nodeRef === this.showConfig.nodeRef) {315               menuTitle = title;316            }317         }318         for (var i = 0; i < menuHTML.length; i++)319         {320            var option = document.createElement("option");321            option.text = menuHTML[i].text;322            option.value = menuHTML[i].value;323            menuContainer.add(option);324         }325         // Instantiate the Menu326         this.widgets.versionMenu = new Alfresco.util.createYUIButton(this, "versionNav-button", this.onVersionMenuChange, {327            type: "menu",328            menu: menuContainer,329            lazyloadmenu: false330         });331         // Set the menu title:332         this.setMenuTitle(menuTitle);333         var firstUL = Dom.getElementsByClassName("first-of-type", "ul", navContainer)[0],334         firstLI = Dom.getElementsByClassName("first-of-type", "li", firstUL)[0];335         // Inject item headers336         currentVersionHeader.innerHTML = Alfresco.util.message("historicProperties.menu.current", this.name);337         previousVersionHeader.innerHTML = Alfresco.util.message("historicProperties.menu.previous", this.name);338         Dom.insertBefore(currentVersionHeader, firstLI);339         Dom.insertAfter(previousVersionHeader, firstLI);340      },341      /**342       *343       * @method getVersion344       * @param {string} - either "previous", "next", or a version label345       * @return {string} - nodeRef to the specified version346       */347      getVersionNodeRef: function HPV_getVersionNodeRef(returnLabel)348      {349         var visibleNodeRef = this.showConfig.nodeRef,350            i, returnNodeRef, visibleIndex, returnIndex;351         // Latest version isn't in the versions array, so default visibleIndex to -1 to allow the maths below to work352         visibleIndex = -1;353         // find the index of the version we're showing at the moment:354         for (i in this.versions) {355              if (this.versions[i].nodeRef === visibleNodeRef) {356                 visibleIndex = i;357              }358              // While we're looping through, check to see if we were passed in a label.359              if (this.versions[i].label === returnLabel) {360                 returnIndex = i;361              }362         }363         if (returnLabel === this.showConfig.latestVersion.label) {364            return this.showConfig.latestVersion.nodeRef;365         }366         // NOTE: the versions array has the most recent item first, so to navigate backwards in time, we need to increase the index.367         else if (returnLabel === "next") {368            returnIndex = parseInt(visibleIndex, 10) - 1;369         }370         else if (returnLabel === "previous") {371            returnIndex = parseInt(visibleIndex, 10) + 1372         }373         // Treat current version specially: -1 = current version374         if (returnIndex === -1)375         {376            return this.showConfig.latestVersion.nodeRef;377         }378         returnVersion = this.versions[returnIndex]379         if (typeof(returnVersion) !== "undefined") {380            returnNodeRef = returnVersion.nodeRef;381            return returnNodeRef;382         }383      },384      /**385       * Fired when the user clicks the cancel button.386       * Closes the panel.387       *388       * @method onCancelButtonClick389       * @param event {object} a Button "click" event390       */391      onCancelButtonClick: function HPV_onCancelButtonClick()392      {393         // Hide the panel394         this.widgets.panel.hide();395         // Disable the Esc key listener396         this.widgets.escapeListener.disable();397      },398      /**399       *400       * Triggered by the user clicking on the Next or Previous navigation buttons.401       *402       * @method onNavButtonClick403       *404       */405      onNavButtonClick: function HPV_onNavButtonClick(event, p_obj)406      {407         var target = Event.getTarget(event),408            dir = target.rel,409            newNodeRef = this.getVersionNodeRef(dir);410         if (!Dom.hasClass(target, "disabled"))411         {412            this.update(newNodeRef);413         }414         //prevent the default action.415         Event.preventDefault(event);416      },417      /**418       *419       * Trigger an AJAX request to load the properties via the forms service420       *421       * @method loadProperties422       *423       */424      loadProperties: function HPV_loadProperties(){425         Alfresco.util.Ajax.request(426               {427                  url: Alfresco.constants.URL_SERVICECONTEXT + "components/form?itemKind=node&itemId=" + this.showConfig.nodeRef + "&mode=view&htmlid=" + this.id,428                  successCallback:429                  {430                     fn: this.onPropertiesLoaded,431                     scope: this432                  },433                  failureMessage: "Could not version properties",434                  execScripts: true435               });436      },437      /**438       *439       * Updates the title on the dropdown box with the current version number.440       *441       * @method setMenuTitle442       */443      setMenuTitle: function HPV_setMenuTitle(title){444         var label, i;445         // If the title hasn't been passed, we'll need to find it from the currentNodeRef.446         if (!title) {447            if (this.showConfig.nodeRef === this.showConfig.latestVersion.nodeRef) {448               label = this.showConfig.latestVersion.label;449               title = Alfresco.util.message("historicProperties.menu.title.latest", this.name,450                     {451                        "0": label452                     });453            }454            else455            {456               for (i in this.versions) {457                  if (this.versions[i].nodeRef === this.showConfig.nodeRef) {458                     label = this.versions[i].label;459                  }460               }461               title = Alfresco.util.message("historicProperties.menu.title", this.name,462                     {463                        "0": label464                     });465            }466         }467         // Set the title.468         this.widgets.versionMenu.set("label", title);469      },470      /**471       *472       * Fired when loadProperties successfully returns473       * Loads the results of the AJAX call into the HTML element we grabbed a reference to earlier474       *475       * @method onPropertiesLoaded476       *477       */478      onPropertiesLoaded: function HPV_onPropertiesLoaded(response){479         this.widgets.formContainer.innerHTML = response.serverResponse.responseText;480         var dateFields = Dom.getElementsByClassName("viewmode-value-date", "span", this.widgets.formContainer);481		 482         for (var i = 0; i < dateFields.length; i++)483         {484            var showTime = Dom.getAttribute(dateFields[i], "data-show-time"),485                fieldValue = Dom.getAttribute(dateFields[i], "data-date-iso8601"),486                ignoreTime = (showTime == 'false'),487                dateFormat = ignoreTime ? Alfresco.util.message("date-format.defaultDateOnly") : Alfresco.util.message("date-format.default"),488                theDate = Alfresco.util.fromISO8601(fieldValue, ignoreTime);489            490            dateFields[i].innerHTML = Alfresco.util.formatDate(theDate, dateFormat);491         }492         493      },494      /**495       * Adjust the gui according to the config passed into the show method.496       *497       * @method _applyConfig498       * @private499       */500      _applyConfig: function HPV__applyConfig()501      {502         // Set the panel section503         var header = Alfresco.util.message("historicProperties.dialogue.header", this.name,504         {505            "0": "<strong>" + this.showConfig.filename + "</strong>"506         });507         this.widgets.headerText["innerHTML"] = header;508         this.widgets.cancelButton.set("disabled", false);509      },510      /**511       * Prepares the gui and shows the panel.512       *513       * @method _showPanel514       * @private515       */516      _showPanel: function HPV__showPanel()517      {518         // Apply the config before it is showed519         this._applyConfig();520         // Enable the Esc key listener521         this.widgets.escapeListener.enable();522         // Show the panel523         this.widgets.panel.show();524      }525   };526})();527Alfresco.module.getHistoricPropertiesViewerInstance = function()528{529   var instanceId = "alfresco-historicPropertiesViewer-instance";530   return Alfresco.util.ComponentManager.get(instanceId) || new Alfresco.module.HistoricPropertiesViewer(instanceId);...revert-wiki-version.js
Source:revert-wiki-version.js  
1/**2 * Copyright (C) 2005-2010 Alfresco Software Limited.3 *4 * This file is part of Alfresco5 *6 * Alfresco is free software: you can redistribute it and/or modify7 * it under the terms of the GNU Lesser General Public License as published by8 * the Free Software Foundation, either version 3 of the License, or9 * (at your option) any later version.10 *11 * Alfresco is distributed in the hope that it will be useful,12 * but WITHOUT ANY WARRANTY; without even the implied warranty of13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the14 * GNU Lesser General Public License for more details.15 *16 * You should have received a copy of the GNU Lesser General Public License17 * along with Alfresco. If not, see <http://www.gnu.org/licenses/>.18 */192021/**22 * RevertWikiVersion component.23 *24 * Popups a YUI panel and lets the user choose version and comment for the revert.25 *26 * @namespace Alfresco.module27 * @class Alfresco.module.RevertWikiVersion28 */29(function()30{3132   /**33    * RevertWikiVersion constructor.34    *35    * RevertWikiVersion is considered a singleton so constructor should be treated as private,36    * please use Alfresco.module.getRevertWikiVersionInstance() instead.37    *38    * @param {string} htmlId The HTML id of the parent element39    * @return {Alfresco.module.RevertWikiVersion} The new RevertWikiVersion instance40    * @constructor41    * @private42    */43   Alfresco.module.RevertWikiVersion = function(containerId)44   {45      this.name = "Alfresco.module.RevertWikiVersion";46      this.id = containerId;4748      var instance = Alfresco.util.ComponentManager.get(this.id);49      if (instance !== null)50      {51         throw new Error("An instance of Alfresco.module.RevertWikiVersion already exists.");52      }5354      /* Register this component */55      Alfresco.util.ComponentManager.register(this);5657      // Load YUI Components58      Alfresco.util.YUILoaderHelper.require(["button", "container", "datatable", "datasource"], this.onComponentsLoaded, this);5960      return this;61   }6263   Alfresco.module.RevertWikiVersion.prototype =64   {6566      /**67       * The default config for the gui state for the revert dialog.68       * The user can override these properties in the show() method.69       *70       * @property defaultShowConfig71       * @type object72       */73      defaultShowConfig:74      {75         siteId: null,76         pageTitle: null,77         version: null,78         versionId: null,79         onRevertWikiVersionComplete: null80      },8182      /**83       * The merged result of the defaultShowConfig and the config passed in84       * to the show method.85       *86       * @property defaultShowConfig87       * @type object88       */89      showConfig: {},9091      /**92       * Object container for storing YUI widget and HTMLElement instances.93       *94       * @property widgets95       * @type object96       */97      widgets: {},9899      /**100       * Fired by YUILoaderHelper when required component script files have101       * been loaded into the browser.102       *103       * @method onComponentsLoaded104       */105      onComponentsLoaded: function RV_onComponentsLoaded()106      {107         // Shortcut for dummy instance108         if (this.id === null)109         {110            return;111         }112      },113114      /**115       * Show can be called multiple times and will display the revert dialog116       * in different ways depending on the config parameter.117       *118       * @method show119       * @param config {object} describes how the revert dialog should be displayed120       * The config object is in the form of:121       * {122       *    nodeRef: {string},  // the nodeRef to revert123       *    version: {string}   // the version to revert nodeRef to124       * }125       */126      show: function RV_show(config)127      {128         // Merge the supplied config with default config and check mandatory properties129         this.showConfig = YAHOO.lang.merge(this.defaultShowConfig, config);130         if (false &&131             this.showConfig.nodeRef === undefined &&132             this.showConfig.version === undefined)133         {134             throw new Error("A nodeRef, filename and version must be provided");135         }136         // Check if the revert dialog has been showed before137         if (this.widgets.panel)138         {139            this._showPanel();140         }141         else142         {143            // If it hasn't load the gui (template) from the server144            Alfresco.util.Ajax.request(145            {146               url: Alfresco.constants.URL_SERVICECONTEXT + "modules/wiki/revert-wiki-version?htmlid=" + this.id,147               successCallback:148               {149                  fn: this.onTemplateLoaded,150                  scope: this151               },152               failureMessage: Alfresco.util.message("message.templateFailure", this.name),153               execScripts: true154            });155         }156      },157158159      /**160       * Called when the revret dialog html template has been returned from the server.161       * Creates the YIU gui objects such as the panel.162       *163       * @method onTemplateLoaded164       * @param response {object} a Alfresco.util.Ajax.request response object165       */166      onTemplateLoaded: function RV_onTemplateLoaded(response)167      {168         var Dom = YAHOO.util.Dom;169170         // Inject the template from the XHR request into a new DIV element171         var containerDiv = document.createElement("div");172         containerDiv.innerHTML = response.serverResponse.responseText;173174         // Create the panel from the HTML returned in the server reponse175         var dialogDiv = YAHOO.util.Dom.getFirstChild(containerDiv);176         this.widgets.panel = Alfresco.util.createYUIPanel(dialogDiv);177178         // Save a reference to the HTMLElement displaying texts so we can alter the texts later179         this.widgets.promptText = Dom.get(this.id + "-prompt-span");180181         // Create and save a reference to the buttons so we can alter them later182         this.widgets.okButton = Alfresco.util.createYUIButton(this, "ok-button", this.onOkButtonClick);183         this.widgets.cancelButton = Alfresco.util.createYUIButton(this, "cancel-button", this.onCancelButtonClick);         184185         // Show panel186         this._showPanel();187      },188189      /**190       * Called when the user clicks on the ok button191       *192       * @method onOkButtonClick193       */194      onOkButtonClick: function RevertWikiVersion_onOkButtonClick()195      {196         this.widgets.okButton.set("disabled", true);197         this.widgets.cancelButton.set("disabled", true);198199         // Its ok to load the version using the proxy as long as its content isn't inserted into the Dom.200         var actionUrl = YAHOO.lang.substitute(Alfresco.constants.PROXY_URI + "slingshot/wiki/version/{site}/{title}/{version}",201         {202            site: this.showConfig.siteId,203            title: encodeURIComponent(this.showConfig.pageTitle),204            version: this.showConfig.versionId205         });206207		   Alfresco.util.Ajax.request(208			{209				method: Alfresco.util.Ajax.GET,210		      url: actionUrl,211				successCallback:212				{213					fn: this.onVersionContent,214					scope: this215				},216		      failureMessage: "Could not retrieve version content"217		   });218219         this.widgets.panel.hide();220         this.widgets.feedbackMessage = Alfresco.util.PopupManager.displayMessage(221         {222            text: Alfresco.util.message("message.reverting", this.name,223            {224               "0": this.showConfig.pageTitle,225               "1": this.showConfig.version226            }),227            spanClass: "wait",228            displayTime: 0229         });230      },231232      /**233       * Called when the content for the version has been loaded.234       * Makes a235       *236       * @method onVersionContent237       */238      onVersionContent: function RevertWikiVersion_onVersionContent(event)239      {240	      // Make a PUT request241         var actionUrl = YAHOO.lang.substitute(Alfresco.constants.PROXY_URI + "slingshot/wiki/page/{site}/{title}",242         {243            site: this.showConfig.siteId,244            title: encodeURIComponent(this.showConfig.pageTitle)245         });246247		   var content = event.serverResponse.responseText;248   		var obj =249   		{250   		   pagecontent: content,251   		   page: "wiki-page",252   		   forceSave: true253   	   };254255		   Alfresco.util.Ajax.request(256			{257				method: Alfresco.util.Ajax.PUT,258		      url: actionUrl,259		      dataObj: obj,260		      requestContentType: Alfresco.util.Ajax.JSON,261				successCallback:262				{263					fn: this.onRevertSuccess,264					scope: this265				},266		      failureCallback:267		      {268					fn: this.onRevertFailure,269					scope: this270		      }271		   });272      },273274      /**275       * Called when a node has been successfully reverted276       *277       * @method onRevertSuccess278       */279      onRevertSuccess: function RV_onRevertSuccess(response)280      {281         // Hide the current message display282         this.widgets.feedbackMessage.destroy();283284         // Tell the document list to refresh itself if present285         YAHOO.Bubbling.fire("wikiVersionReverted",286         {287            siteId: this.showConfig.siteId,288            pageTitle: this.showConfig.pageTitle,289            version: this.showConfig.version,290            versionId: this.showConfig.versionId291         });292293         var objComplete =294         {295            successful: [296            {297               siteId: this.showConfig.siteId,298               pageTitle: this.showConfig.pageTitle,299               version: this.showConfig.version,300               versionId: this.showConfig.versionId301            }]302         };303304         var callback = this.showConfig.onRevertWikiVersionComplete;305         if (callback && typeof callback.fn == "function")306         {307            // Call the onRevertWikiVersionComplete callback in the correct scope308            callback.fn.call((typeof callback.scope == "object" ? callback.scope : this), objComplete, callback.obj);309         }310      },311312      /**313       * Called when a node failed to be reverted314       * Informs the user.315       *316       * @method onRevertFailure317       */318      onRevertFailure: function RV_onRevertFailure(response)319      {320         // Hide the current message display321         this.widgets.feedbackMessage.destroy();322323         // Make sure the ok button is enabled for next time324         this.widgets.okButton.set("disabled", false);325326         // Inform user that revert was successful327         Alfresco.util.PopupManager.displayMessage(328         {329            text: Alfresco.util.message("message.failure", this.name,330            {331               "0": this.showConfig.pageTitle332            })333         });334335      },336337      /**338       * Fired when the user clicks the cancel button.339       * Closes the panel.340       *341       * @method onCancelButtonClick342       * @param event {object} a Button "click" event343       */344      onCancelButtonClick: function RV_onCancelButtonClick()345      {346         // Hide the panel347         this.widgets.panel.hide();348349         // and make sure ok is enabed next time its showed350         this.widgets.okButton.set("disabled", false);351352      },353354      /**355       * Adjust the gui according to the config passed into the show method.356       *357       * @method _applyConfig358       * @private359       */360      _applyConfig: function RV__applyConfig()361      {362         var Dom = YAHOO.util.Dom;363364         // Set the panel section365         var prompt = Alfresco.util.message("label.prompt", this.name,366         {367            "0": this.showConfig.pageTitle,368            "1": this.showConfig.version369         });370         this.widgets.promptText["innerHTML"] = prompt;371372         this.widgets.cancelButton.set("disabled", false);373      },374375      /**376       * Prepares the gui and shows the panel.377       *378       * @method _showPanel379       * @private380       */381      _showPanel: function RV__showPanel()382      {383         // Apply the config before it is showed384         this._applyConfig();385386         // Show the revert panel387         this.widgets.panel.show();388      }389390   };391392})();393394Alfresco.module.getRevertWikiVersionInstance = function()395{396   var instanceId = "alfresco-revertWikiVersion-instance";397   return Alfresco.util.ComponentManager.get(instanceId) || new Alfresco.module.RevertWikiVersion(instanceId);
...revert-version.js
Source:revert-version.js  
1/**2 * Copyright (C) 2005-2010 Alfresco Software Limited.3 *4 * This file is part of Alfresco5 *6 * Alfresco is free software: you can redistribute it and/or modify7 * it under the terms of the GNU Lesser General Public License as published by8 * the Free Software Foundation, either version 3 of the License, or9 * (at your option) any later version.10 *11 * Alfresco is distributed in the hope that it will be useful,12 * but WITHOUT ANY WARRANTY; without even the implied warranty of13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the14 * GNU Lesser General Public License for more details.15 *16 * You should have received a copy of the GNU Lesser General Public License17 * along with Alfresco. If not, see <http://www.gnu.org/licenses/>.18 */1920/**21 * RevertVersion component.22 *23 * Popups a YUI panel and lets the user choose version and comment for the revert.24 *25 * @namespace Alfresco.module26 * @class Alfresco.module.RevertVersion27 */28(function()29{30   /**31    * RevertVersion constructor.32    *33    * RevertVersion is considered a singleton so constructor should be treated as private,34    * please use Alfresco.module.getRevertVersionInstance() instead.35    *36    * @param {string} htmlId The HTML id of the parent element37    * @return {Alfresco.module.RevertVersion} The new RevertVersion instance38    * @constructor39    * @private40    */41   Alfresco.module.RevertVersion = function(containerId)42   {43      this.name = "Alfresco.module.RevertVersion";44      this.id = containerId;4546      var instance = Alfresco.util.ComponentManager.get(this.id);47      if (instance !== null)48      {49         throw new Error("An instance of Alfresco.module.RevertVersion already exists.");50      }5152      /* Register this component */53      Alfresco.util.ComponentManager.register(this);5455      // Load YUI Components56      Alfresco.util.YUILoaderHelper.require(["button", "container", "datatable", "datasource"], this.onComponentsLoaded, this);5758      return this;59   };6061   Alfresco.module.RevertVersion.prototype =62   {6364      /**65       * The default config for the gui state for the revert dialog.66       * The user can override these properties in the show() method.67       *68       * @property defaultShowConfig69       * @type object70       */71      defaultShowConfig:72      {73         nodeRef: null,74         filename: null,75         version: null,76         onRevertVersionComplete: null77      },7879      /**80       * The merged result of the defaultShowConfig and the config passed in81       * to the show method.82       *83       * @property defaultShowConfig84       * @type object85       */86      showConfig: {},8788      /**89       * Object container for storing YUI widget and HTMLElement instances.90       *91       * @property widgets92       * @type object93       */94      widgets: {},9596      /**97       * Fired by YUILoaderHelper when required component script files have98       * been loaded into the browser.99       *100       * @method onComponentsLoaded101       */102      onComponentsLoaded: function RV_onComponentsLoaded()103      {104         // Shortcut for dummy instance105         if (this.id === null)106         {107            return;108         }109      },110111      /**112       * Show can be called multiple times and will display the revert dialog113       * in different ways depending on the config parameter.114       *115       * @method show116       * @param config {object} describes how the revert dialog should be displayed117       * The config object is in the form of:118       * {119       *    nodeRef: {string},  // the nodeRef to revert120       *    version: {string}   // the version to revert nodeRef to121       * }122       */123      show: function RV_show(config)124      {125         // Merge the supplied config with default config and check mandatory properties126         this.showConfig = YAHOO.lang.merge(this.defaultShowConfig, config);127         if (this.showConfig.nodeRef === undefined &&128             this.showConfig.filename === undefined &&129             this.showConfig.version === undefined)130         {131             throw new Error("A nodeRef, filename and version must be provided");132         }133         // Check if the revert dialog has been showed before134         if (this.widgets.panel)135         {136            this._showPanel();137         }138         else139         {140            // If it hasn't load the gui (template) from the server141            Alfresco.util.Ajax.request(142            {143               url: Alfresco.constants.URL_SERVICECONTEXT + "modules/document-details/revert-version?htmlid=" + this.id,144               successCallback:145               {146                  fn: this.onTemplateLoaded,147                  scope: this148               },149               failureMessage: "Could not load html revert template",150               execScripts: true151            });152         }153      },154155      /**156       * Called when the revert dialog html template has been returned from the server.157       * Creates the YIU gui objects such as the panel.158       *159       * @method onTemplateLoaded160       * @param response {object} a Alfresco.util.Ajax.request response object161       */162      onTemplateLoaded: function RV_onTemplateLoaded(response)163      {164         var Dom = YAHOO.util.Dom;165166         // Inject the template from the XHR request into a new DIV element167         var containerDiv = document.createElement("div");168         containerDiv.innerHTML = response.serverResponse.responseText;169170         // Create the panel from the HTML returned in the server reponse171         var dialogDiv = YAHOO.util.Dom.getFirstChild(containerDiv);172         this.widgets.panel = Alfresco.util.createYUIPanel(dialogDiv);173174         // Save a reference to the HTMLElement displaying texts so we can alter the texts later175         this.widgets.headerText = Dom.get(this.id + "-header-span");176177         // Save references to hidden fields so we can set them later178         this.widgets.nodeRef = Dom.get(this.id + "-nodeRef-hidden");179         this.widgets.version = Dom.get(this.id + "-version-hidden");180181         // Save reference to version section elements so we can set its values later182         this.widgets.description = YAHOO.util.Dom.get(this.id + "-description-textarea");183         this.widgets.minorVersion = YAHOO.util.Dom.get(this.id + "-minorVersion-radioButton");184185         // Create and save a reference to the buttons so we can alter them later186         this.widgets.okButton = Alfresco.util.createYUIButton(this, "ok-button", null,187         {188            type: "submit"189         });190         this.widgets.cancelButton = Alfresco.util.createYUIButton(this, "cancel-button", this.onCancelButtonClick);191192         // Configure the forms runtime193         var form = new Alfresco.forms.Form(this.id + "-revertVersion-form");194         this.widgets.form = form;195196         // The ok button is the submit button, and it should be enabled when the form is ready197         form.setSubmitElements(this.widgets.okButton);198         form.doBeforeFormSubmit =199         {200            fn: function()201            {202               this.widgets.cancelButton.set("disabled", true);203               this.widgets.panel.hide();204               this.widgets.feedbackMessage = Alfresco.util.PopupManager.displayMessage(205               {206                  text: Alfresco.util.message("message.reverting", this.name,207                  {208                     "0": this.showConfig.filename,209                     "1": this.showConfig.version210                  }),211                  spanClass: "wait",212                  displayTime: 0213               });214            },215            obj: null,216            scope: this217         }218219         // Submit as an ajax submit (not leave the page), in json format220         form.setAJAXSubmit(true,221         {222            successCallback:223            {224               fn: this.onRevertSuccess,225               scope: this226            },227            failureCallback:228            {229               fn: this.onRevertFailure,230               scope: this231            }232         });233         form.setSubmitAsJSON(true);234235         // We're in a popup, so need the tabbing fix236         form.applyTabFix();237         form.init();238239         // Show panel240         this._showPanel();241      },242243      /**244       * Called when a node has been successfully reverted245       *246       * @method onRevertSuccess247       */248      onRevertSuccess: function RV_onRevertSuccess(response)249      {250         // Hide the current message display251         this.widgets.feedbackMessage.destroy();252253         // Make sure the ok button is enabled for next time254         this.widgets.okButton.set("disabled", false);255256         // Tell the document list to refresh itself if present257         YAHOO.Bubbling.fire("versionReverted",258         {259            nodeRef: this.showConfig.nodeRef,260            filename: this.showConfig.filename,261            version: this.showConfig.version262         });263264         var objComplete =265         {266            successful: [{nodeRef: this.showConfig.nodeRef, version: this.showConfig.version}]267         };268269         var callback = this.showConfig.onRevertVersionComplete;270         if (callback && typeof callback.fn == "function")271         {272            // Call the onRevertVersionComplete callback in the correct scope273            callback.fn.call((typeof callback.scope == "object" ? callback.scope : this), objComplete, callback.obj);274         }275      },276277      /**278       * Called when a node failed to be reverted279       * Informs the user.280       *281       * @method onRevertFailure282       */283      onRevertFailure: function RV_onRevertFailure(response)284      {285         // Hide the current message display286         this.widgets.feedbackMessage.destroy();287288         // Inform user that revert was successful289         Alfresco.util.PopupManager.displayMessage(290         {291            text: Alfresco.util.message("message.failure", this.name, 292            {293               "0": this.showConfig.filename294            })295         });296297      },298299      /**300       * Fired when the user clicks the cancel button.301       * Closes the panel.302       *303       * @method onCancelButtonClick304       * @param event {object} a Button "click" event305       */306      onCancelButtonClick: function RV_onCancelButtonClick()307      {308         // Hide the panel309         this.widgets.panel.hide();310311         // and make sure ok is enabed next time its showed312         this.widgets.okButton.set("disabled", false);313314      },315316      /**317       * Adjust the gui according to the config passed into the show method.318       *319       * @method _applyConfig320       * @private321       */322      _applyConfig: function RV__applyConfig()323      {324         var Dom = YAHOO.util.Dom;325326         // Set the panel section327         var header = Alfresco.util.message("header.revert", this.name,328         {329            "0": this.showConfig.filename,330            "1": this.showConfig.version331         });332         this.widgets.headerText["innerHTML"] = header;333334         this.widgets.cancelButton.set("disabled", false);335336         // Set the hidden parameters337         this.widgets.nodeRef.value = this.showConfig.nodeRef;338         this.widgets.version.value = this.showConfig.version;339      },340341      /**342       * Prepares the gui and shows the panel.343       *344       * @method _showPanel345       * @private346       */347      _showPanel: function RV__showPanel()348      {349         // Reset references and the gui before showing it350         this.widgets.description.value = "";351         this.widgets.minorVersion.checked = true;352353         // Apply the config before it is showed354         this._applyConfig();355356         // Show the revert panel357         this.widgets.panel.show();358      }359   };360})();361362Alfresco.module.getRevertVersionInstance = function()363{364   var instanceId = "alfresco-revertVersion-instance";365   return Alfresco.util.ComponentManager.get(instanceId) || new Alfresco.module.RevertVersion(instanceId);
...showConfig.controller.js
Source:showConfig.controller.js  
1import { catchAsync } from '../utils/catchAsync';2import showConfigService from '../services/showConfig.service';3import metaDataService from '../services/metaData.service';4export const getShowConfig = catchAsync(async(req, res) => {5    const showConfig = await showConfigService.getShowConfig({_id: req.params.id});6    showConfig.meta = await metaDataService.getMetaDataForShowConfig(showConfig);7    showConfig.meta.episodes = [];8    res.json(showConfig);9});10export const createShowConfig = catchAsync(async(req, res) => {11    const showConfig = await showConfigService.createShowConfig(req.body);12    res.json(showConfig);13});14export const updateShowConfig = catchAsync(async(req, res) => {15    const data = {16        name: req.body.name,17        releaseFilter: req.body.releaseFilter,18        releaseType: req.body.releaseType,19        season: req.body.season,20        targetDirName: req.body.targetDirName21    };22    const success = await showConfigService.updateShowConfig({_id: req.params.id}, data);23    res.json(success ? {...data, _id: req.params.id} : {error: true});24});25export const deleteShowConfig = catchAsync(async(req, res) => {26    const success =  await showConfigService.deleteShowConfig({_id: req.params.id});27    res.json(success ? {deleted: req.params.id} : null);28});29export const getAllShowConfig = catchAsync(async(req, res) => {30    let showConfigs = await showConfigService.getAllShowConfig();31    showConfigs = await Promise.all(showConfigs.map(async showConfig =>32        ({...showConfig, meta: await metaDataService.getMetaDataForShowConfig(showConfig)})33    ));34    showConfigs = showConfigs.map(showConfig => ({...showConfig, meta: {...showConfig.meta, episodes: []}}));35    res.json(showConfigs);36});37export const searchShow = catchAsync(async(req, res) => {38    const results = await metaDataService.searchTvShows(req.params.query);39    res.json(results);40});41export const addByMetaId = catchAsync(async(req, res) => {42    if (!req.body.theMovieDbId) {43        res.json({error: 'NO_META_ID'});44    }45    const checkDupe = await showConfigService.getShowConfig({theMovieDbId: req.body.theMovieDbId});46    if (checkDupe?.theMovieDbId) {47        res.json({error: 'DUPLICATED_ENTRY'});48    }49    const showData = await metaDataService.getTmdbDataById(req.body.theMovieDbId);50    const showConfig = await showConfigService.createShowConfig({51        name: showData.name,52        releaseFilter: showData.name.toLowerCase().replace(/[^a-z0-9]+/gi, '.'),53        releaseType: '1080p',54        targetDirName: showData.name.replace(/[^a-z0-9]+/gi, '.'),55        season: showData.numberOfSeasons,56        theMovieDbId: showData.theMovieDbId57    });58    res.json({59        ...showConfig,60        newItem: true,61        meta: showData62    });63});64export default {65    getShowConfig,66    getAllShowConfig,67    createShowConfig,68    updateShowConfig,69    deleteShowConfig,70    searchShow,71    addByMetaId...showConfigSlice.js
Source:showConfigSlice.js  
1import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';2import axios from 'axios';3axios.defaults.baseURL = '/api';4const initialState = {5    showConfigs: []6};7export const loadShowConfigs = createAsyncThunk(8    'showConfig/loadShowConfigs',9    async () => {10        const response = await axios.get('/showConfig');11        return response?.data;12    }13);14export const addShowConfig = createAsyncThunk(15    'showConfig/addShowConfig',16    async (theMovieDbId) => {17        const response = await axios.post('/showConfig/addByMetaId', {theMovieDbId});18        return response?.data;19    }20);21export const deleteShowConfig = createAsyncThunk(22    'showConfig/deleteShowConfig',23    async (showConfig) => {24        const response = await axios.delete('/showConfig/' + showConfig._id);25        return response?.data;26    }27);28export const updateShowConfig = createAsyncThunk(29    'showConfig/updateShowConfig',30    async (showConfig) => {31        const response = await axios.patch('/showConfig/' + showConfig._id, showConfig);32        return response?.data;33    }34);35export const showConfigSlice = createSlice({36    name: 'showConfig',37    initialState,38    reducers: {},39    extraReducers: (builder) => {40        builder41            .addCase(loadShowConfigs.fulfilled, (state, action) => {42                state.showConfigs = action.payload.sort((a, b) => a.name.localeCompare(b.name));43            })44            .addCase(addShowConfig.fulfilled, (state, action) => {45                state.showConfigs = [action.payload, ...state.showConfigs.map(e => ({...e, newItem: false}))]46                    .sort((a, b) =>47                        a.name.localeCompare(b.name)48                    );49            })50            .addCase(deleteShowConfig.fulfilled, (state, action) => {51                state.showConfigs = state.showConfigs.filter(e => e._id !== action.payload?.deleted);52            })53            .addCase(updateShowConfig.fulfilled, (state, action) => {54                if (!action.payload.error) {55                    const idx = state.showConfigs.findIndex(e => e._id === action.payload._id);56                    if (idx !== -1) {57                        state.showConfigs[idx] = {...state.showConfigs[idx], ...action.payload};58                    }59                }60            });61    }62});63export const selectShowConfigs = (state) => state.showConfig.showConfigs;...IFree.ClickMeController.js
Source:IFree.ClickMeController.js  
1IFree.ClickMeControllerSingleton = IFree.RandomPlayer.extend({2	3	_trainClickElementId: "ifree-train-click-element",4	_trainElementId: "ifree-world-train",5	6	_popupShowInterval: 2000,7	_popupDelay: 2000,8	9	hide: function()10	{11		IFree.ClickMePopup.hide();12	},13	14	_getObjectPosition: function(showConfig)15	{16		return showConfig.objectId == this._trainClickElementId ? IFree.TrainController.getTrainPosition() : IFree.XYHelper.getOffset(showConfig.objectId);	17	},18	19	_getTargetSide: function(showConfig)20	{21		if (showConfig.objectId != this._trainClickElementId)22			return showConfig.targetSide;23			24		var trainAngle = IFree.TrainController.trainAngle();25		26		return trainAngle > 180 ? "left top" : "right top";27	},28	29	showForObject: function(showConfig)30	{31		var objectPosition = this._getObjectPosition(showConfig);32		var object = IFree.ObjectRegistry.getItem(showConfig.objectId);3334		var targetSide = this._getTargetSide(showConfig);35		36		IFree.ClickMePopup.showAt(objectPosition.left, objectPosition.top, object.width(), object.height(), targetSide, showConfig.offsetLeft, showConfig.offsetTop);37	},38	39	start: function()40	{41		this._super();42	43		this._playNext();44	},45	46	/*Override*/47	_createPlayObjectList: function()48	{49		var objectMap = IFree.Popup.ClickableObjectRegistry.getItems();50		51		var list = [];52		53		for (var key in objectMap)54		{55			list.push(objectMap[key]);56		}57		58		return list;59	},60	61	/*Override*/62	_objectReady: function(playObject)63	{64		return playObject.config().objectId == this._trainClickElementId ? IFree.TrainController.trainVisible() : true;65	},	66	67	/*Override*/68	_playObject: function(nextObject)69	{70		this.showForObject(nextObject.config());71		72		setTimeout(IFree.Util.createDelegate(function(){73			74			this.hide();75			76			setTimeout(IFree.Util.createDelegate(this._playNext, this), this._popupDelay);77			78		}, this), this._popupShowInterval);79	}80});81
...showConfig.service.js
Source:showConfig.service.js  
1import {ShowConfig} from '../models/showConfig.model';2import { parseReleaseName } from '../utils/parseReleaseName';3import { createItem, deleteItem, getItem, getAllItem, updateItem } from './common.service';4export const getShowConfig = async (filter) => getItem(ShowConfig, filter);5export const getAllShowConfig = async () => getAllItem(ShowConfig, {});6export const createShowConfig = async (data) => createItem(ShowConfig, data);7export const deleteShowConfig = async (filter) => deleteItem(ShowConfig, filter);8export const updateShowConfig = async (filter, data, opts) => updateItem(ShowConfig, filter, data, opts);9export const isTitleInFilterConfigs = async (title) => {10    const showConfigs = await getAllShowConfig();11    const episodeData = parseReleaseName(title);12    for (const showConfig of showConfigs) {13        const regexTitle = new RegExp(showConfig.releaseFilter.toLowerCase(), 'i');14        const regexReleaseType = showConfig.releaseType ? new RegExp(showConfig.releaseType.toLowerCase(), 'i') : null;15        if (16            regexTitle.test(episodeData.name) &&17            (showConfig.season === episodeData.season || showConfig.season === 0) &&18            (!showConfig.releaseType || regexReleaseType.test(episodeData.releaseData))19        ) {20            return showConfig;21        }22    }23    return false;24};25export default {26    getShowConfig,27    getAllShowConfig,28    createShowConfig,29    updateShowConfig,30    deleteShowConfig,31    isTitleInFilterConfigs...Using AI Code Generation
1driver.showConfig()2driver.hideKeyboard()3driver.openNotifications()4driver.lock()5driver.shake()6driver.isLocked()7driver.unlock()8driver.installApp()9driver.removeApp()10driver.launchApp()11driver.closeApp()12driver.resetApp()13driver.runAppInBackground()14driver.endTestCoverage()15driver.startRecordingScreen()16driver.stopRecordingScreen()17driver.toggleLocationServices()18driver.getDeviceTime()19driver.toggleWiFi()20driver.toggleData()21driver.toggleAirplaneMode()22driver.toggleFlightMode()Using AI Code Generation
1var AppiumDriver = require('./AppiumDriver.js');2var appiumDriver = new AppiumDriver();3appiumDriver.showConfig();4var AppiumDriver = require('./AppiumDriver.js');5var appiumDriver = new AppiumDriver();6appiumDriver.showConfig();7var AppiumDriver = require('./AppiumDriver.js');8var appiumDriver = new AppiumDriver();9appiumDriver.showConfig();10var AppiumDriver = require('./AppiumDriver.js');11var appiumDriver = new AppiumDriver();12appiumDriver.showConfig();13var AppiumDriver = require('./AppiumDriver.js');14var appiumDriver = new AppiumDriver();15appiumDriver.showConfig();16var AppiumDriver = require('./AppiumDriver.js');17var appiumDriver = new AppiumDriver();18appiumDriver.showConfig();19var AppiumDriver = require('./AppiumDriver.js');20var appiumDriver = new AppiumDriver();21appiumDriver.showConfig();22var AppiumDriver = require('./AppiumDriver.js');23var appiumDriver = new AppiumDriver();24appiumDriver.showConfig();25var AppiumDriver = require('./AppiumDriver.js');26var appiumDriver = new AppiumDriver();27appiumDriver.showConfig();28var AppiumDriver = require('./AppiumDriver.js');29var appiumDriver = new AppiumDriver();30appiumDriver.showConfig();31var AppiumDriver = require('./AppiumDriver.js');32var appiumDriver = new AppiumDriver();33appiumDriver.showConfig();34var AppiumDriver = require('./AppiumDriver.js');35var appiumDriver = new AppiumDriver();36appiumDriver.showConfig();Using AI Code Generation
1const Appium = require('appium');2const appium = new Appium();3appium.showConfig();4appium.startServer();5appium.stopServer();6class Appium {7  showConfig() {8    console.log("Appium Configuration");9  }10  startServer() {11    console.log("Appium Server Started");12  }13  stopServer() {14    console.log("Appium Server Stopped");15  }16}17module.exports = Appium;18Node.js - Import a Module in Another Module Using require()19Node.js - Import a Module in Another Module Using import20Node.js - Import a Function in Another Module Using require()21Node.js - Import a Function in Another Module Using import22Node.js - Import a Variable in Another Module Using require()23Node.js - Import a Variable in Another Module Using import24Node.js - Import a Class in Another Module Using require()25Node.js - Import a Class in Another Module Using importUsing AI Code Generation
1var appiumDriver = new AppiumDriver();2appiumDriver.showConfig();3var AppiumDriver = function() {4    this.showConfig = function() {5        console.log("Appium driver configuration");6    }7}8module.exports = AppiumDriver;Using AI Code Generation
1public class Appium {2    public void showConfig() {3    }4}5var appium = require("./Appium.js");6appium.showConfig();7public class Appium {8    public void showConfig() {9        System.out.println("Appium server is running on port 4723");10    }11}12var appium = require("./Appium.js");13appium.showConfig();14public class Appium {15    public void showConfig() {16        System.out.println("Appium server is running on port 4723");17    }18}19var appium = require("./Appium.js");20appium.showConfig();21public class Appium {22    public void showConfig() {23        System.out.println("Appium server is running on port 4723");24    }25}Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
