<commit_before>/*
 * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

var deviceModule;
deviceModule = function () {
    //var log = new Log("modules/device.js");

    var utility = require('/modules/utility.js').utility;
    var constants = require('/modules/constants.js');
    var mdmProps = require('/config/mdm-props.js').config();

    var ArrayList = Packages.java.util.ArrayList;
    var Properties = Packages.java.util.Properties;
    var DeviceIdentifier = Packages.org.wso2.carbon.device.mgt.common.DeviceIdentifier;
    var DeviceManagerUtil = Packages.org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
    var SimpleOperation = Packages.org.wso2.carbon.device.mgt.core.operation.mgt.SimpleOperation;
    var ConfigOperation = Packages.org.wso2.carbon.device.mgt.core.operation.mgt.ConfigOperation;
    var CommandOperation = Packages.org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation;

    var deviceManagementService = utility.getDeviceManagementService();

    var publicMethods = {};
    var privateMethods = {};

    privateMethods.validateAndReturn = function (value) {
        return (value == undefined || value == null) ? constants.UNSPECIFIED : value;
    };

    /*
     @Deprecated
     */
    publicMethods.listDevices = function () {
        var carbonUser = session.get(constants.USER_SESSION_KEY);
        var utility = require('/modules/utility.js').utility;
        if (!carbonUser) {
            log.error("User object was not found in the session");
            throw constants.ERRORS.USER_NOT_FOUND;
        }
        try{
            utility.startTenantFlow(carbonUser);
            var deviceManagementService = utility.getDeviceManagementService();
            var devices = deviceManagementService.getAllDevices();
            var deviceList = [];
            var i, device, propertiesList, deviceObject;
            for (i = 0; i < devices.size(); i++) {
                device = devices.get(i);
                propertiesList = DeviceManagerUtil.convertDevicePropertiesToMap(device.getProperties());

                deviceObject = {};
                deviceObject[constants.DEVICE_IDENTIFIER] =
                    privateMethods.validateAndReturn(device.getDeviceIdentifier());
                deviceObject[constants.DEVICE_NAME] =
                    privateMethods.validateAndReturn(device.getName());
                deviceObject[constants.DEVICE_OWNERSHIP] =
                    privateMethods.validateAndReturn(device.getEnrolmentInfo().getOwnership());
                deviceObject[constants.DEVICE_OWNER] =
                    privateMethods.validateAndReturn(device.getEnrolmentInfo().getOwner());
                deviceObject[constants.DEVICE_TYPE] =
                    privateMethods.validateAndReturn(device.getType());
                deviceObject[constants.DEVICE_PROPERTIES] = {};
                if (device.getType() == constants.PLATFORM_IOS) {
                    deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_MODEL] =
                        privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_PRODUCT));
                    deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_VENDOR] = constants.VENDOR_APPLE;
                } else {
                    deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_MODEL] =
                        privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_MODEL));
                    deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_VENDOR] =
                        privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_VENDOR));
                }
                deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_OS_VERSION] =
                    privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_OS_VERSION));

                deviceList.push(deviceObject);
            }
            return deviceList;
        }catch (e) {
            throw e;
        } finally {
            utility.endTenantFlow();
        }
    };

    publicMethods.listDevicesForUser = function (username) {
        var carbonUser = session.get(constants.USER_SESSION_KEY);
        var utility = require('/modules/utility.js').utility;
        if (!carbonUser) {
            log.error("User object was not found in the session");
            throw constants.ERRORS.USER_NOT_FOUND;
        }
        try{
            utility.startTenantFlow(carbonUser);
            var deviceManagementService = utility.getDeviceManagementService();
            var devices = deviceManagementService.getDeviceListOfUser(username);
            var deviceList = [];
            var i, device, propertiesList, deviceObject;
            for (i = 0; i < devices.size(); i++) {
                device = devices.get(i);
                propertiesList = DeviceManagerUtil.convertDevicePropertiesToMap(device.getProperties());

                deviceObject = {};
                deviceObject[constants.DEVICE_IDENTIFIER] =
                    privateMethods.validateAndReturn(device.getDeviceIdentifier());
                deviceObject[constants.DEVICE_NAME] =
                    privateMethods.validateAndReturn(device.getName());
                deviceObject[constants.DEVICE_OWNERSHIP] =
                    privateMethods.validateAndReturn(device.getEnrolmentInfo().getOwnership());
                deviceObject[constants.DEVICE_OWNER] =
                    privateMethods.validateAndReturn(device.getEnrolmentInfo().getOwner());
                deviceObject[constants.DEVICE_TYPE] =
                    privateMethods.validateAndReturn(device.getType());
                deviceObject[constants.DEVICE_PROPERTIES] = {};
                if (device.getType() == constants.PLATFORM_IOS) {
                    deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_MODEL] =
                        privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_PRODUCT));
                    deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_VENDOR] = constants.VENDOR_APPLE;
                } else {
                    deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_MODEL] =
                        privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_MODEL));
                    deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_VENDOR] =
                        privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_VENDOR));
                }
                deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_OS_VERSION] =
                    privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_OS_VERSION));

                deviceList.push(deviceObject);
            }
            return deviceList;
        }catch (e) {
            throw e;
        } finally {
            utility.endTenantFlow();
        }
    };

    /*
     @Deprecated
     */
    /*
     Get the supported features by the device type
     */
    publicMethods.getFeatures = function (deviceType) {
        var carbonUser = session.get(constants.USER_SESSION_KEY);
        var utility = require('/modules/utility.js').utility;
        if (!carbonUser) {
            log.error("User object was not found in the session");
            throw constants.ERRORS.USER_NOT_FOUND;
        }
        try{
            utility.startTenantFlow(carbonUser);
            var deviceManagementService = utility.getDeviceManagementService();
            var features = deviceManagementService.getFeatureManager(deviceType).getFeatures();
            var featuresConverted = {};
            if (features) {
                var i, feature, featureObject;
                for (i = 0; i < features.size(); i++) {
                    feature = features.get(i);
                    featureObject = {};
                    featureObject[constants.FEATURE_NAME] = feature.getName();
                    featureObject[constants.FEATURE_DESCRIPTION] = feature.getDescription();
                    featuresConverted[feature.getName()] = featureObject;
                }
            }
            return featuresConverted;
        }catch (e) {
            throw e;
        } finally {
            utility.endTenantFlow();
        }
    };

    /*
     @Deprecated
     */
    publicMethods.performOperation = function (devices, operation) {
        var carbonUser = session.get(constants.USER_SESSION_KEY);
        var utility = require('/modules/utility.js').utility;
        if (!carbonUser) {
            log.error("User object was not found in the session");
            throw constants.ERRORS.USER_NOT_FOUND;
        }
        try{
            utility.startTenantFlow(carbonUser);
            var deviceManagementService = utility.getDeviceManagementService();
            var operationInstance;
            if (operation.type == "COMMAND") {
                operationInstance = new CommandOperation();
            } else if (operation.type == "CONFIG") {
                operationInstance = new ConfigOperation();
            } else {
                operationInstance = new SimpleOperation();
            }
            operationInstance.setCode(operation.featureName);
            var props = new Properties();
            var i, object;
            for (i = 0; i < operation.properties.length; i++) {
                object = properties[i];
                props.setProperty(object.key, object.value);
            }
            operationInstance.setProperties(props);
            var deviceList = new ArrayList();
            var j, device, deviceIdentifier;
            for (j = 0; j < devices.length; i++) {
                device = devices[j];
                deviceIdentifier = new DeviceIdentifier();
                deviceIdentifier.setId(device.id);
                deviceIdentifier.setType(device.type);
                deviceList.add(deviceIdentifier);
            }
            deviceManagementService.addOperation(operationInstance, deviceList);
        }catch (e) {
            throw e;
        } finally {
            utility.endTenantFlow();
        }
    };

    privateMethods.getDevice = function (type, deviceId) {
        var carbonUser = session.get(constants.USER_SESSION_KEY);
        var utility = require('/modules/utility.js').utility;
        if (!carbonUser) {
            log.error("User object was not found in the session");
            throw constants.ERRORS.USER_NOT_FOUND;
        }
        try{
            utility.startTenantFlow(carbonUser);
            var deviceManagementService = utility.getDeviceManagementService();
            var deviceIdentifier = new DeviceIdentifier();
            deviceIdentifier.setType(type);
            deviceIdentifier.setId(deviceId);
            return deviceManagementService.getDevice(deviceIdentifier);
        }catch (e) {
            throw e;
        } finally {
            utility.endTenantFlow();
        }
    };

    publicMethods.viewDevice = function (type, deviceId) {
        var carbonUser = session.get(constants.USER_SESSION_KEY);
        var utility = require('/modules/utility.js').utility;
        if (!carbonUser) {
            log.error("User object was not found in the session");
            throw constants.ERRORS.USER_NOT_FOUND;
        }
        var utility = require('/modules/utility.js')["utility"];
        try{
            utility.startTenantFlow(carbonUser);

            var url = mdmProps["httpsURL"] + "/mdm-admin/devices/"+type+"/"+deviceId;
            var xhr = new XMLHttpRequest();
            xhr.open("GET", url);
            xhr.send();

            var response = {};
            if (xhr.status == 200 && xhr.readyState == 4) {
                var device = parse(xhr.responseText);
                if(device){
                    var propertiesList = device.properties;
                    var properties = {};
                    for(var i = 0; i < propertiesList.length; i++){
                        properties[propertiesList[i].name] = propertiesList[i].value;
                    }

                    var deviceObject = {};
                    deviceObject[constants.DEVICE_IDENTIFIER] = device.deviceIdentifier;
                    deviceObject[constants.DEVICE_NAME] = device.name;
                    deviceObject[constants.DEVICE_OWNERSHIP] = device.enrolmentInfo.ownership;
                    deviceObject[constants.DEVICE_OWNER] = device.enrolmentInfo.owner;
                    deviceObject[constants.DEVICE_TYPE] = device.type;
                    if (device.type == constants.PLATFORM_IOS) {
                        properties[constants.DEVICE_MODEL] = properties[constants.DEVICE_PRODUCT];
                        delete properties[constants.DEVICE_PRODUCT];
                        properties[constants.DEVICE_VENDOR] = constants.VENDOR_APPLE;
                    }
                    deviceObject[constants.DEVICE_PROPERTIES] = properties;
                    return deviceObject;
                }
            } else {
                response["status"] = "error";
                return response;
            }
        } catch (e) {
            throw e;
        } finally {
            utility.endTenantFlow();
        }
    };

    publicMethods.getLicense = function () {

        var deviceManagementService = utility.getDeviceManagementService();
        return deviceManagementService.getLicense(constants.PLATFORM_IOS, constants.LANGUAGE_US);

    };

    return publicMethods;
}();
<commit_msg>Updating device Response object changes<commit_after>/*
 * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

var deviceModule;
deviceModule = function () {
    //var log = new Log("modules/device.js");

    var utility = require('/modules/utility.js').utility;
    var constants = require('/modules/constants.js');
    var mdmProps = require('/config/mdm-props.js').config();

    var ArrayList = Packages.java.util.ArrayList;
    var Properties = Packages.java.util.Properties;
    var DeviceIdentifier = Packages.org.wso2.carbon.device.mgt.common.DeviceIdentifier;
    var DeviceManagerUtil = Packages.org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
    var SimpleOperation = Packages.org.wso2.carbon.device.mgt.core.operation.mgt.SimpleOperation;
    var ConfigOperation = Packages.org.wso2.carbon.device.mgt.core.operation.mgt.ConfigOperation;
    var CommandOperation = Packages.org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation;

    var deviceManagementService = utility.getDeviceManagementService();

    var publicMethods = {};
    var privateMethods = {};

    privateMethods.validateAndReturn = function (value) {
        return (value == undefined || value == null) ? constants.UNSPECIFIED : value;
    };

    /*
     @Deprecated
     */
    publicMethods.listDevices = function () {
        var carbonUser = session.get(constants.USER_SESSION_KEY);
        var utility = require('/modules/utility.js').utility;
        if (!carbonUser) {
            log.error("User object was not found in the session");
            throw constants.ERRORS.USER_NOT_FOUND;
        }
        try{
            utility.startTenantFlow(carbonUser);
            var deviceManagementService = utility.getDeviceManagementService();
            var devices = deviceManagementService.getAllDevices();
            var deviceList = [];
            var i, device, propertiesList, deviceObject;
            for (i = 0; i < devices.size(); i++) {
                device = devices.get(i);
                propertiesList = DeviceManagerUtil.convertDevicePropertiesToMap(device.getProperties());

                deviceObject = {};
                deviceObject[constants.DEVICE_IDENTIFIER] =
                    privateMethods.validateAndReturn(device.getDeviceIdentifier());
                deviceObject[constants.DEVICE_NAME] =
                    privateMethods.validateAndReturn(device.getName());
                deviceObject[constants.DEVICE_OWNERSHIP] =
                    privateMethods.validateAndReturn(device.getEnrolmentInfo().getOwnership());
                deviceObject[constants.DEVICE_OWNER] =
                    privateMethods.validateAndReturn(device.getEnrolmentInfo().getOwner());
                deviceObject[constants.DEVICE_TYPE] =
                    privateMethods.validateAndReturn(device.getType());
                deviceObject[constants.DEVICE_PROPERTIES] = {};
                if (device.getType() == constants.PLATFORM_IOS) {
                    deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_MODEL] =
                        privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_PRODUCT));
                    deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_VENDOR] = constants.VENDOR_APPLE;
                } else {
                    deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_MODEL] =
                        privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_MODEL));
                    deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_VENDOR] =
                        privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_VENDOR));
                }
                deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_OS_VERSION] =
                    privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_OS_VERSION));

                deviceList.push(deviceObject);
            }
            return deviceList;
        }catch (e) {
            throw e;
        } finally {
            utility.endTenantFlow();
        }
    };

    publicMethods.listDevicesForUser = function (username) {
        var carbonUser = session.get(constants.USER_SESSION_KEY);
        var utility = require('/modules/utility.js').utility;
        if (!carbonUser) {
            log.error("User object was not found in the session");
            throw constants.ERRORS.USER_NOT_FOUND;
        }
        try{
            utility.startTenantFlow(carbonUser);
            var deviceManagementService = utility.getDeviceManagementService();
            var devices = deviceManagementService.getDeviceListOfUser(username);
            var deviceList = [];
            var i, device, propertiesList, deviceObject;
            for (i = 0; i < devices.size(); i++) {
                device = devices.get(i);
                propertiesList = DeviceManagerUtil.convertDevicePropertiesToMap(device.getProperties());

                deviceObject = {};
                deviceObject[constants.DEVICE_IDENTIFIER] =
                    privateMethods.validateAndReturn(device.getDeviceIdentifier());
                deviceObject[constants.DEVICE_NAME] =
                    privateMethods.validateAndReturn(device.getName());
                deviceObject[constants.DEVICE_OWNERSHIP] =
                    privateMethods.validateAndReturn(device.getEnrolmentInfo().getOwnership());
                deviceObject[constants.DEVICE_OWNER] =
                    privateMethods.validateAndReturn(device.getEnrolmentInfo().getOwner());
                deviceObject[constants.DEVICE_TYPE] =
                    privateMethods.validateAndReturn(device.getType());
                deviceObject[constants.DEVICE_PROPERTIES] = {};
                if (device.getType() == constants.PLATFORM_IOS) {
                    deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_MODEL] =
                        privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_PRODUCT));
                    deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_VENDOR] = constants.VENDOR_APPLE;
                } else {
                    deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_MODEL] =
                        privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_MODEL));
                    deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_VENDOR] =
                        privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_VENDOR));
                }
                deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_OS_VERSION] =
                    privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_OS_VERSION));

                deviceList.push(deviceObject);
            }
            return deviceList;
        }catch (e) {
            throw e;
        } finally {
            utility.endTenantFlow();
        }
    };

    /*
     @Deprecated
     */
    /*
     Get the supported features by the device type
     */
    publicMethods.getFeatures = function (deviceType) {
        var carbonUser = session.get(constants.USER_SESSION_KEY);
        var utility = require('/modules/utility.js').utility;
        if (!carbonUser) {
            log.error("User object was not found in the session");
            throw constants.ERRORS.USER_NOT_FOUND;
        }
        try{
            utility.startTenantFlow(carbonUser);
            var deviceManagementService = utility.getDeviceManagementService();
            var features = deviceManagementService.getFeatureManager(deviceType).getFeatures();
            var featuresConverted = {};
            if (features) {
                var i, feature, featureObject;
                for (i = 0; i < features.size(); i++) {
                    feature = features.get(i);
                    featureObject = {};
                    featureObject[constants.FEATURE_NAME] = feature.getName();
                    featureObject[constants.FEATURE_DESCRIPTION] = feature.getDescription();
                    featuresConverted[feature.getName()] = featureObject;
                }
            }
            return featuresConverted;
        }catch (e) {
            throw e;
        } finally {
            utility.endTenantFlow();
        }
    };

    /*
     @Deprecated
     */
    publicMethods.performOperation = function (devices, operation) {
        var carbonUser = session.get(constants.USER_SESSION_KEY);
        var utility = require('/modules/utility.js').utility;
        if (!carbonUser) {
            log.error("User object was not found in the session");
            throw constants.ERRORS.USER_NOT_FOUND;
        }
        try{
            utility.startTenantFlow(carbonUser);
            var deviceManagementService = utility.getDeviceManagementService();
            var operationInstance;
            if (operation.type == "COMMAND") {
                operationInstance = new CommandOperation();
            } else if (operation.type == "CONFIG") {
                operationInstance = new ConfigOperation();
            } else {
                operationInstance = new SimpleOperation();
            }
            operationInstance.setCode(operation.featureName);
            var props = new Properties();
            var i, object;
            for (i = 0; i < operation.properties.length; i++) {
                object = properties[i];
                props.setProperty(object.key, object.value);
            }
            operationInstance.setProperties(props);
            var deviceList = new ArrayList();
            var j, device, deviceIdentifier;
            for (j = 0; j < devices.length; i++) {
                device = devices[j];
                deviceIdentifier = new DeviceIdentifier();
                deviceIdentifier.setId(device.id);
                deviceIdentifier.setType(device.type);
                deviceList.add(deviceIdentifier);
            }
            deviceManagementService.addOperation(operationInstance, deviceList);
        }catch (e) {
            throw e;
        } finally {
            utility.endTenantFlow();
        }
    };

    privateMethods.getDevice = function (type, deviceId) {
        var carbonUser = session.get(constants.USER_SESSION_KEY);
        var utility = require('/modules/utility.js').utility;
        if (!carbonUser) {
            log.error("User object was not found in the session");
            throw constants.ERRORS.USER_NOT_FOUND;
        }
        try{
            utility.startTenantFlow(carbonUser);
            var deviceManagementService = utility.getDeviceManagementService();
            var deviceIdentifier = new DeviceIdentifier();
            deviceIdentifier.setType(type);
            deviceIdentifier.setId(deviceId);
            return deviceManagementService.getDevice(deviceIdentifier);
        }catch (e) {
            throw e;
        } finally {
            utility.endTenantFlow();
        }
    };

    publicMethods.viewDevice = function (type, deviceId) {
        var carbonUser = session.get(constants.USER_SESSION_KEY);
        var utility = require('/modules/utility.js').utility;
        if (!carbonUser) {
            log.error("User object was not found in the session");
            throw constants.ERRORS.USER_NOT_FOUND;
        }
        var utility = require('/modules/utility.js')["utility"];
        try{
            utility.startTenantFlow(carbonUser);

            var url = mdmProps["httpsURL"] + "/mdm-admin/devices/"+type+"/"+deviceId;
            var xhr = new XMLHttpRequest();
            xhr.open("GET", url);
            xhr.send();

            var response = {};
            if (xhr.status == 200 && xhr.readyState == 4) {
                var responsePayload = parse(xhr.responseText);
                var device = responsePayload["responseContent"];
                if(device){
                    var propertiesList = device.properties;
                    var properties = {};
                    for(var i = 0; i < propertiesList.length; i++){
                        properties[propertiesList[i].name] = propertiesList[i].value;
                    }

                    var deviceObject = {};
                    deviceObject[constants.DEVICE_IDENTIFIER] = device.deviceIdentifier;
                    deviceObject[constants.DEVICE_NAME] = device.name;
                    deviceObject[constants.DEVICE_OWNERSHIP] = device.enrolmentInfo.ownership;
                    deviceObject[constants.DEVICE_OWNER] = device.enrolmentInfo.owner;
                    deviceObject[constants.DEVICE_TYPE] = device.type;
                    if (device.type == constants.PLATFORM_IOS) {
                        properties[constants.DEVICE_MODEL] = properties[constants.DEVICE_PRODUCT];
                        delete properties[constants.DEVICE_PRODUCT];
                        properties[constants.DEVICE_VENDOR] = constants.VENDOR_APPLE;
                    }
                    deviceObject[constants.DEVICE_PROPERTIES] = properties;
                    return deviceObject;
                }
            } else {
                response["status"] = "error";
                return response;
            }
        } catch (e) {
            throw e;
        } finally {
            utility.endTenantFlow();
        }
    };

    publicMethods.getLicense = function () {

        var deviceManagementService = utility.getDeviceManagementService();
        return deviceManagementService.getLicense(constants.PLATFORM_IOS, constants.LANGUAGE_US);

    };

    return publicMethods;
}();
<|endoftext|>


<commit_before>/**
 @ngdoc service
 * @name umbraco.services.editorService
 *
 * @description
 * Added in Umbraco 8.0. Application-wide service for handling infinite editing.
 */
(function () {
    "use strict";

    function editorService(eventsService) {

        var editors = [];

        /**
         * @ngdoc method
         * @name umbraco.services.editorService#getEditors
         * @methodOf umbraco.services.editorService
         *
         * @description
         * Method to return all open editors
         */
        function getEditors() {
            return editors;
        };

        /**
         * @ngdoc method
         * @name umbraco.services.editorService#open
         * @methodOf umbraco.services.editorService
         *
         * @description
         * Method to open a new editor in infinite editing
         */
        function open(editor) {

            // set flag so we know when the editor is open in "infinie mode"
            editor.infiniteMode = true;

            editors.push(editor);

            var args = {
                editors: editors,
                editor: editor
            };

            eventsService.emit("appState.editors.open", args);
        }

        /**
         * @ngdoc method
         * @name umbraco.services.editorService#close
         * @methodOf umbraco.services.editorService
         *
         * @description
         * Opens a media editor in infinite editing, the submit callback returns the updated content item
         */
        function close() {
            var length = editors.length;
            var closedEditor = editors[length - 1];
            // close last opened editor
            editors.splice(-1, 1);

            var args = {
                editors: editors,
                editor: closedEditor
            };

            eventsService.emit("appState.editors.close", args);
        }

        /**
         * @ngdoc method
         * @name umbraco.services.editorService#contentEditor
         * @methodOf umbraco.services.editorService
         *
         * @description
         * Opens a media editor in infinite editing, the submit callback returns the updated content item
         * @param {String} editor.id The id of the content item
         * @param {Boolean} editor.create Create new content item
         * @returns {Object} editor object
         */
        function contentEditor(editor) {
            editor.view = "views/content/edit.html";
            open(editor);
        }

        /**
         * @ngdoc method
         * @name umbraco.services.editorService#mediaEditor
         * @methodOf umbraco.services.editorService
         *
         * @description
         * Opens a media editor in infinite editing, the submit callback returns the updated media item
         * @param {String} editor.id The id of the media item
         * @param {Boolean} editor.create Create new media item
         * @param {Callback} editor.submit Saves, submits, and closes the editor
         * @param {Callback} editor.close Closes the editor
         * @returns {Object} editor object
         */
        function mediaEditor(editor) {
            editor.view = "views/media/edit.html";
            open(editor);
        }

        /**
         * @ngdoc method
         * @name umbraco.services.editorService#mediaPicker
         * @methodOf umbraco.services.editorService
         *
         * @description
         * Opens a media picker in infinite editing, the submit callback returns an array of selected media items
         * @param {Boolean} editor.multiPicker Pick one or multiple items
         * @param {Boolean} editor.onlyImages Only display files that have an image file-extension
         * @param {Boolean} editor.disableFolderSelect Disable folder selection
         * @param {Array} editor.updatedMediaNodes A list of ids for media items that have been updated through the media picker
         * @param {Callback} editor.submit Submits the editor
         * @param {Callback} editor.close Closes the editor
         * @returns {Object} editor object
         */
        function mediaPicker(editor) {
            editor.view = "views/common/infiniteeditors/mediapicker/mediapicker.html";
            editor.size = "small";
            editor.updatedMediaNodes = [];
            open(editor);
        }

        /**
         * @ngdoc method
         * @name umbraco.services.editorService#iconPicker
         * @methodOf umbraco.services.editorService
         *
         * @description
         * Opens an icon picker in infinite editing, the submit callback returns the selected icon
         * @param {Callback} editor.submit Submits the editor
         * @param {Callback} editor.close Closes the editor
         * @returns {Object} editor object
         */
        function iconPicker(editor) {
            editor.view = "views/common/infiniteeditors/iconpicker/iconpicker.html";
            editor.size = "small";
            open(editor);
        }

        var service = {
            getEditors: getEditors,
            open: open,
            close: close,
            mediaEditor: mediaEditor,
            contentEditor: contentEditor,
            mediaPicker: mediaPicker,
            iconPicker: iconPicker
        };

        return service;

    }

    angular.module("umbraco.services").factory("editorService", editorService);

})();
<commit_msg>add new helper function to open document type<commit_after>/**
 @ngdoc service
 * @name umbraco.services.editorService
 *
 * @description
 * Added in Umbraco 8.0. Application-wide service for handling infinite editing.
 */
(function () {
    "use strict";

    function editorService(eventsService) {

        var editors = [];

        /**
         * @ngdoc method
         * @name umbraco.services.editorService#getEditors
         * @methodOf umbraco.services.editorService
         *
         * @description
         * Method to return all open editors
         */
        function getEditors() {
            return editors;
        };

        /**
         * @ngdoc method
         * @name umbraco.services.editorService#open
         * @methodOf umbraco.services.editorService
         *
         * @description
         * Method to open a new editor in infinite editing
         */
        function open(editor) {

            // set flag so we know when the editor is open in "infinie mode"
            editor.infiniteMode = true;

            editors.push(editor);

            var args = {
                editors: editors,
                editor: editor
            };

            eventsService.emit("appState.editors.open", args);
        }

        /**
         * @ngdoc method
         * @name umbraco.services.editorService#close
         * @methodOf umbraco.services.editorService
         *
         * @description
         * Opens a media editor in infinite editing, the submit callback returns the updated content item
         */
        function close() {
            var length = editors.length;
            var closedEditor = editors[length - 1];
            // close last opened editor
            editors.splice(-1, 1);

            var args = {
                editors: editors,
                editor: closedEditor
            };

            eventsService.emit("appState.editors.close", args);
        }

        /**
         * @ngdoc method
         * @name umbraco.services.editorService#contentEditor
         * @methodOf umbraco.services.editorService
         *
         * @description
         * Opens a media editor in infinite editing, the submit callback returns the updated content item
         * @param {String} editor.id The id of the content item
         * @param {Boolean} editor.create Create new content item
         * @returns {Object} editor object
         */
        function contentEditor(editor) {
            editor.view = "views/content/edit.html";
            open(editor);
        }

        /**
         * @ngdoc method
         * @name umbraco.services.editorService#mediaEditor
         * @methodOf umbraco.services.editorService
         *
         * @description
         * Opens a media editor in infinite editing, the submit callback returns the updated media item
         * @param {String} editor.id The id of the media item
         * @param {Boolean} editor.create Create new media item
         * @param {Callback} editor.submit Saves, submits, and closes the editor
         * @param {Callback} editor.close Closes the editor
         * @returns {Object} editor object
         */
        function mediaEditor(editor) {
            editor.view = "views/media/edit.html";
            open(editor);
        }

        /**
         * @ngdoc method
         * @name umbraco.services.editorService#mediaPicker
         * @methodOf umbraco.services.editorService
         *
         * @description
         * Opens a media picker in infinite editing, the submit callback returns an array of selected media items
         * @param {Boolean} editor.multiPicker Pick one or multiple items
         * @param {Boolean} editor.onlyImages Only display files that have an image file-extension
         * @param {Boolean} editor.disableFolderSelect Disable folder selection
         * @param {Array} editor.updatedMediaNodes A list of ids for media items that have been updated through the media picker
         * @param {Callback} editor.submit Submits the editor
         * @param {Callback} editor.close Closes the editor
         * @returns {Object} editor object
         */
        function mediaPicker(editor) {
            editor.view = "views/common/infiniteeditors/mediapicker/mediapicker.html";
            editor.size = "small";
            editor.updatedMediaNodes = [];
            open(editor);
        }

        /**
         * @ngdoc method
         * @name umbraco.services.editorService#iconPicker
         * @methodOf umbraco.services.editorService
         *
         * @description
         * Opens an icon picker in infinite editing, the submit callback returns the selected icon
         * @param {Callback} editor.submit Submits the editor
         * @param {Callback} editor.close Closes the editor
         * @returns {Object} editor object
         */
        function iconPicker(editor) {
            editor.view = "views/common/infiniteeditors/iconpicker/iconpicker.html";
            editor.size = "small";
            open(editor);
        }

        /**
         * @ngdoc method
         * @name umbraco.services.editorService#documentTypeEditor
         * @methodOf umbraco.services.editorService
         *
         * @description
         * Opens the document type editor in infinite editing, the submit callback returns the save document type
         * @param {Callback} editor.submit Submits the editor
         * @param {Callback} editor.close Closes the editor
         * @returns {Object} editor object
         */
        function documentTypeEditor(editor) {
            editor.view = "views/documenttypes/edit.html";
            open(editor);
        }

        var service = {
            getEditors: getEditors,
            open: open,
            close: close,
            mediaEditor: mediaEditor,
            contentEditor: contentEditor,
            mediaPicker: mediaPicker,
            iconPicker: iconPicker,
            documentTypeEditor: documentTypeEditor
        };

        return service;

    }

    angular.module("umbraco.services").factory("editorService", editorService);

})();
<|endoftext|>


<commit_before>/**
 * @file DropdownFilter component
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {findDOMNode} from 'react-dom';

import TextField from '../TextField';
import Popup from '../Popup';
import List from '../List';
import DynamicRenderList from '../DynamicRenderList';
import Theme from '../Theme';

import Util from '../_vendors/Util';
import SelectMode from '../_statics/SelectMode';
import DropdownCalculation from '../_vendors/DropdownCalculation';

class DropdownFilter extends Component {

    static SelectMode = SelectMode;
    static Theme = Theme;

    constructor(props, ...restArgs) {

        super(props, ...restArgs);

        this.triggerEl = null;

        this.state = {
            value: props.value,
            filter: '',
            popupVisible: false,
            isAbove: false
        };

        this.filterData = ::this.filterData;
        this.triggerFocusHandler = ::this.triggerFocusHandler;
        this.triggerBlurHandler = ::this.triggerBlurHandler;
        this.filterChangeHandler = ::this.filterChangeHandler;
        this.filterPressEnterHandler = ::this.filterPressEnterHandler;
        this.closePopup = ::this.closePopup;
        this.popupRenderHandler = ::this.popupRenderHandler;
        this.changeHandler = ::this.changeHandler;

    }

    filterData(filter = this.state.filter, data = this.props.data) {

        if (!filter) {
            return data;
        }

        const {displayField, filterCallback} = this.props;

        if (filterCallback) {
            return filterCallback(filter, data);
        }

        const filterFunc = (originData) => {
            return originData.filter(item => typeof item === 'object' && !!item[displayField] ?
                item[displayField].toString().toUpperCase().includes(filter.toUpperCase())
                :
                item.toString().toUpperCase().includes(filter.toUpperCase()));
        };

        return filterFunc(data);

    }

    triggerFocusHandler(...args) {

        const {disabled, onFocus} = this.props,
            {filter} = this.state;

        onFocus && onFocus(...args);

        !disabled && filter && this.setState({
            popupVisible: true
        });

    }

    triggerBlurHandler(...args) {
        const {disabled, onBlur} = this.props;
        !disabled && onBlur && onBlur(...args);
    }

    filterChangeHandler(filter) {

        const value = this.state.value,
            state = {
                filter,
                popupVisible: !!filter
            };

        if (!filter) {
            state.value = undefined;
        }

        this.setState(state, () => {
            const {onFilterChange} = this.props;
            onFilterChange && onFilterChange(filter);
        });

    }

    filterPressEnterHandler(e, filter) {

        const {autoClose} = this.props,
            callback = () => {
                const {onFilterPressEnter} = this.props;
                onFilterPressEnter && onFilterPressEnter(filter);
            };

        if (autoClose) {
            this.setState({
                popupVisible: false
            }, () => {
                callback();
            });
        } else {
            callback();
        }

    }

    closePopup() {
        this.setState({
            popupVisible: false
        }, () => {
            const {onPopupClosed} = this.props;
            onPopupClosed && onPopupClosed();
        });
    }

    popupRenderHandler(popupEl) {

        const isAbove = DropdownCalculation.isAbove(this.dropdownFilterEl, this.triggerEl, findDOMNode(popupEl));

        if (isAbove !== this.state.isAbove) {
            this.setState({
                isAbove
            });
        }

    }

    changeHandler(value) {

        const state = {value};

        if (this.props.autoClose) {
            state.popupVisible = false;
        }

        this.setState(state, () => {
            const {onChange} = this.props;
            onChange && onChange(value);
        });

    }

    componentDidMount() {
        this.dropdownFilterEl = this.refs.dropdownFilter;
        this.triggerEl = findDOMNode(this.refs.trigger);
    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.value !== this.state.value) {
            this.setState({
                value: nextProps.value
            });
        }
    }

    render() {

        const {

                className, popupClassName, style, popupStyle, theme, popupTheme, placeholder, selectMode,
                disabled, iconCls, rightIconCls, valueField, displayField, descriptionField,
                useDynamicRenderList, listHeight, itemHeight, scrollBuffer,
                noMatchedPopupVisible, noMatchedMsg, popupChildren, renderer,

                radioUncheckedIconCls, radioCheckedIconCls,
                checkboxUncheckedIconCls, checkboxCheckedIconCls, checkboxIndeterminateIconCls,

                onItemTouchTap, onFilterClear, onTriggerMouseOver, onTriggerMouseOut

            } = this.props,
            {isAbove, value, filter, popupVisible} = this.state,

            emptyEl = [{
                itemRenderer() {
                    return (

                            {
                                noMatchedMsg ?
                                    noMatchedMsg
                                    :

                                        No matched value.

                            }

                    );
                },
                disableTouchRipple: true
            }],

            listData = this.filterData(),
            isEmpty = listData.length < 1,

            wrapperClassName = (className ? ' ' + className : ''),
            triggerClassName = (isEmpty && !noMatchedPopupVisible ? '' : (popupVisible ? ' activated' : ''))
                + (isAbove ? ' above' : ' blow'),
            autoCompletePopupClassName = (isAbove ? ' above' : ' blow') + (popupClassName ? ' ' + popupClassName : ''),
            autoCompletePopupStyle = Object.assign({
                width: this.triggerEl && getComputedStyle(this.triggerEl).width
            }, popupStyle);

        return (

                <TextField ref="trigger"
                           className={'dropdown-filter-trigger' + triggerClassName}
                           theme={theme}
                           value={filter}
                           placeholder={placeholder}
                           disabled={disabled}
                           iconCls={iconCls}
                           rightIconCls={rightIconCls}
                           onFocus={this.triggerFocusHandler}
                           onBlur={this.triggerBlurHandler}
                           onMouseOver={onTriggerMouseOver}
                           onMouseOut={onTriggerMouseOut}
                           onChange={this.filterChangeHandler}
                           onPressEnter={this.filterPressEnterHandler}
                           onClear={onFilterClear}
                           onRightIconTouchTap={this.filterPressEnterHandler}/>

                {
                    isEmpty && !noMatchedPopupVisible ?
                        null
                        :
                        <Popup className={'dropdown-filter-popup' + autoCompletePopupClassName}
                               style={autoCompletePopupStyle}
                               theme={popupTheme}
                               visible={popupVisible}
                               triggerEl={this.triggerEl}
                               hasTriangle={false}
                               triggerMode={Popup.TriggerMode.OPEN}
                               position={isAbove ? Popup.Position.TOP_LEFT : Popup.Position.BOTTOM_LEFT}
                               onRender={this.popupRenderHandler}
                               onRequestClose={this.closePopup}>

                            {
                                isEmpty ?
                                    <List className="dropdown-filter-list"
                                          theme={popupTheme}
                                          selectMode={SelectMode.SINGLE_SELECT}
                                          data={emptyEl}/>
                                    :
                                    (
                                        useDynamicRenderList ?
                                            <DynamicRenderList className="dropdown-filter-list"
                                                               theme={popupTheme}
                                                               value={value}
                                                               selectMode={selectMode || SelectMode.SINGLE_SELECT}
                                                               data={listData}
                                                               valueField={valueField}
                                                               displayField={displayField}
                                                               descriptionField={descriptionField}
                                                               renderer={renderer}
                                                               listHeight={listHeight}
                                                               itemHeight={itemHeight}
                                                               scrollBuffer={scrollBuffer}
                                                               radioUncheckedIconCls={radioUncheckedIconCls}
                                                               radioCheckedIconCls={radioCheckedIconCls}
                                                               checkboxUncheckedIconCls={checkboxUncheckedIconCls}
                                                               checkboxCheckedIconCls={checkboxCheckedIconCls}
                                                               checkboxIndeterminateIconCls={checkboxIndeterminateIconCls}
                                                               onItemTouchTap={onItemTouchTap}
                                                               onChange={this.changeHandler}/>
                                            :
                                            <List className="dropdown-filter-list"
                                                  theme={popupTheme}
                                                  value={value}
                                                  selectMode={selectMode || SelectMode.SINGLE_SELECT}
                                                  data={listData}
                                                  valueField={valueField}
                                                  displayField={displayField}
                                                  descriptionField={descriptionField}
                                                  renderer={renderer}
                                                  radioUncheckedIconCls={radioUncheckedIconCls}
                                                  radioCheckedIconCls={radioCheckedIconCls}
                                                  checkboxUncheckedIconCls={checkboxUncheckedIconCls}
                                                  checkboxCheckedIconCls={checkboxCheckedIconCls}
                                                  checkboxIndeterminateIconCls={checkboxIndeterminateIconCls}
                                                  onItemTouchTap={onItemTouchTap}
                                                  onChange={this.changeHandler}/>
                                    )
                            }

                            {popupChildren}

                        </Popup>
                }

        );
    }

};

DropdownFilter.propTypes = {

    /**
     * The CSS class name of the root element.
     */
    className: PropTypes.string,

    /**
     * The CSS class name of the popup element.
     */
    popupClassName: PropTypes.string,

    /**
     * Override the styles of the root element.
     */
    style: PropTypes.object,

    /**
     * Override the styles of the popup element.
     */
    popupStyle: PropTypes.object,

    /**
     * The theme.
     */
    theme: PropTypes.oneOf(Util.enumerateValue(Theme)),

    /**
     * The theme.
     */
    popupTheme: PropTypes.oneOf(Util.enumerateValue(Theme)),

    /**
     * The placeholder of the field.
     */
    placeholder: PropTypes.string,

    /**
     * Children passed into the List.
     */
    data: PropTypes.oneOfType([

        // not grouped
        PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.shape({

            /**
             * The CSS class name of the list button.
             */
            className: PropTypes.string,

            /**
             * Override the styles of the list button.
             */
            style: PropTypes.object,

            /**
             * The theme of the list button.
             */
            theme: PropTypes.oneOf(Util.enumerateValue(Theme)),

            /**
             * The text value of the list button.Type can be string or number.
             */
            value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),

            /**
             * The desc value of the list button. Type can be string or number.
             */
            desc: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),

            /**
             * If true, the list button will be disabled.
             */
            disabled: PropTypes.bool,

            /**
             * If true,the button will be have loading effect.
             */
            isLoading: PropTypes.bool,

            /**
             * If true,the element's ripple effect will be disabled.
             */
            disableTouchRipple: PropTypes.bool,

            /**
             * Use this property to display an icon. It will display on the left.
             */
            iconCls: PropTypes.string,

            /**
             * Use this property to display an icon. It will display on the right.
             */
            rightIconCls: PropTypes.string,

            /**
             * You can create a complicated renderer callback instead of value and desc prop.
             */
            itemRenderer: PropTypes.func,

            /**
             * Callback function fired when a list item touch-tapped.
             */
            onTouchTap: PropTypes.func

        }), PropTypes.string, PropTypes.number])),

        // grouped
        PropTypes.array

    ]).isRequired,

    /**
     * If true, the auto complete will be disabled.
     */
    disabled: PropTypes.bool,

    /**
     * The value field name in data. (default: "value")
     */
    valueField: PropTypes.string,

    /**
     * The display field name in data. (default: "text")
     */
    displayField: PropTypes.string,

    /**
     * The description field name in data. (default: "desc")
     */
    descriptionField: PropTypes.string,

    /**
     * If true, the popup list automatically closed after selection.
     */
    autoClose: PropTypes.bool,

    /**
     * The type of dropDown list,can be normal,checkbox,radio.
     */
    selectMode: PropTypes.oneOf(Util.enumerateValue(SelectMode)),

    /**
     * Callback function fired when filter changed.
     */
    filterCallback: PropTypes.func,

    /**
     * Use this property to display an icon.
     */
    iconCls: PropTypes.string,

    /**
     * Use this property to display an icon.
     */
    rightIconCls: PropTypes.string,

    /**
     * The visiblity of no matched popup.
     */
    noMatchedPopupVisible: PropTypes.bool,

    /**
     * The message of no matched value.
     */
    noMatchedMsg: PropTypes.string,

    popupChildren: PropTypes.any,

    useDynamicRenderList: PropTypes.bool,
    listHeight: PropTypes.number,
    itemHeight: PropTypes.number,
    scrollBuffer: PropTypes.number,

    radioUncheckedIconCls: PropTypes.string,
    radioCheckedIconCls: PropTypes.string,
    checkboxUncheckedIconCls: PropTypes.string,
    checkboxCheckedIconCls: PropTypes.string,
    checkboxIndeterminateIconCls: PropTypes.string,

    /**
     * You can create a complicated renderer callback instead of value and desc prop.
     */
    renderer: PropTypes.func,

    /**
     * The function that trigger when filter changes.
     */
    onFilterChange: PropTypes.func,

    /**
     * The function that trigger when press enter.
     */
    onFilterPressEnter: PropTypes.func,

    /**
     * The function that trigger when filter cleared.
     */
    onFilterClear: PropTypes.func,

    /**
     * The function that trigger when value changed.
     */
    onChange: PropTypes.func,

    /**
     * The function that trigger when touch-tap the list items.
     */
    onItemTouchTap: PropTypes.func,

    /**
     * Callback function fired when DropdownFilter get focus.
     */
    onFocus: PropTypes.func,

    /**
     * Callback function fired when DropdownFilter lose focus.
     */
    onBlur: PropTypes.func,

    onTriggerMouseOver: PropTypes.func,
    onTriggerMouseOut: PropTypes.func,
    onPopupClosed: PropTypes.func

};

DropdownFilter.defaultProps = {

    className: null,
    popupClassName: null,
    style: null,
    popupStyle: null,
    theme: Theme.DEFAULT,
    popupTheme: Theme.DEFAULT,

    placeholder: null,
    data: [],
    disabled: false,
    valueField: 'value',
    displayField: 'text',
    descriptionField: 'desc',
    autoClose: false,
    selectMode: SelectMode.SINGLE_SELECT,
    iconCls: null,
    rightIconCls: 'fa fa-search',
    noMatchedPopupVisible: true,
    noMatchedMsg: null,

    popupChildren: null,

    useDynamicRenderList: false,

    radioUncheckedIconCls: null,
    radioCheckedIconCls: null,
    checkboxUncheckedIconCls: 'fa fa-square-o',
    checkboxCheckedIconCls: 'fa fa-check-square',
    checkboxIndeterminateIconCls: 'fa fa-minus-square'

};

export default DropdownFilter;<commit_msg>update DropdownFilter<commit_after>/**
 * @file DropdownFilter component
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {findDOMNode} from 'react-dom';
import classNames from 'classnames';

import TextField from '../TextField';
import Popup from '../Popup';
import List from '../List';
import DynamicRenderList from '../DynamicRenderList';
import Theme from '../Theme';

import Util from '../_vendors/Util';
import SelectMode from '../_statics/SelectMode';
import DropdownCalculation from '../_vendors/DropdownCalculation';

class DropdownFilter extends Component {

    static SelectMode = SelectMode;
    static Theme = Theme;

    constructor(props, ...restArgs) {

        super(props, ...restArgs);

        this.triggerEl = null;

        this.state = {
            value: props.value,
            filter: '',
            popupVisible: false,
            isAbove: false
        };

        this.filterData = ::this.filterData;
        this.triggerFocusHandler = ::this.triggerFocusHandler;
        this.triggerBlurHandler = ::this.triggerBlurHandler;
        this.filterChangeHandler = ::this.filterChangeHandler;
        this.filterPressEnterHandler = ::this.filterPressEnterHandler;
        this.closePopup = ::this.closePopup;
        this.popupRenderHandler = ::this.popupRenderHandler;
        this.changeHandler = ::this.changeHandler;

    }

    filterData(filter = this.state.filter, data = this.props.data) {

        if (!filter) {
            return data;
        }

        const {displayField, filterCallback} = this.props;

        if (filterCallback) {
            return filterCallback(filter, data);
        }

        const filterFunc = (originData) => {
            return originData.filter(item => typeof item === 'object' && !!item[displayField] ?
                item[displayField].toString().toUpperCase().includes(filter.toUpperCase())
                :
                item.toString().toUpperCase().includes(filter.toUpperCase()));
        };

        return filterFunc(data);

    }

    triggerFocusHandler(...args) {

        const {disabled, onFocus} = this.props,
            {filter} = this.state;

        onFocus && onFocus(...args);

        !disabled && filter && this.setState({
            popupVisible: true
        });

    }

    triggerBlurHandler(...args) {
        const {disabled, onBlur} = this.props;
        !disabled && onBlur && onBlur(...args);
    }

    filterChangeHandler(filter) {

        const value = this.state.value,
            state = {
                filter,
                popupVisible: !!filter
            };

        if (!filter) {
            state.value = undefined;
        }

        this.setState(state, () => {
            const {onFilterChange} = this.props;
            onFilterChange && onFilterChange(filter);
        });

    }

    filterPressEnterHandler(e, filter) {

        const {autoClose} = this.props,
            callback = () => {
                const {onFilterPressEnter} = this.props;
                onFilterPressEnter && onFilterPressEnter(filter);
            };

        if (autoClose) {
            this.setState({
                popupVisible: false
            }, () => {
                callback();
            });
        } else {
            callback();
        }

    }

    closePopup() {
        this.setState({
            popupVisible: false
        }, () => {
            const {onPopupClosed} = this.props;
            onPopupClosed && onPopupClosed();
        });
    }

    popupRenderHandler(popupEl) {

        const isAbove = DropdownCalculation.isAbove(this.dropdownFilterEl, this.triggerEl, findDOMNode(popupEl));

        if (isAbove !== this.state.isAbove) {
            this.setState({
                isAbove
            });
        }

    }

    changeHandler(value) {

        const state = {value};

        if (this.props.autoClose) {
            state.popupVisible = false;
        }

        this.setState(state, () => {
            const {onChange} = this.props;
            onChange && onChange(value);
        });

    }

    componentDidMount() {
        this.dropdownFilterEl = this.refs.dropdownFilter;
        this.triggerEl = findDOMNode(this.refs.trigger);
    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.value !== this.state.value) {
            this.setState({
                value: nextProps.value
            });
        }
    }

    render() {

        const {

                className, popupClassName, style, popupStyle, theme, popupTheme, placeholder, selectMode,
                disabled, iconCls, rightIconCls, valueField, displayField, descriptionField,
                useDynamicRenderList, listHeight, itemHeight, scrollBuffer,
                noMatchedPopupVisible, noMatchedMsg, popupChildren, renderer,

                radioUncheckedIconCls, radioCheckedIconCls,
                checkboxUncheckedIconCls, checkboxCheckedIconCls, checkboxIndeterminateIconCls,

                onItemTouchTap, onFilterClear, onTriggerMouseOver, onTriggerMouseOut

            } = this.props,
            {isAbove, value, filter, popupVisible} = this.state,

            emptyEl = [{
                itemRenderer() {
                    return (

                            {
                                noMatchedMsg ?
                                    noMatchedMsg
                                    :

                                        No matched value.

                            }

                    );
                },
                disableTouchRipple: true
            }],

            listData = this.filterData(),
            isEmpty = listData.length < 1,

            wrapperClassName = classNames('dropdown-filter', {
                [className]: className
            }),
            triggerClassName = classNames('dropdown-filter-trigger',
                isEmpty && !noMatchedPopupVisible ? '' : (popupVisible ? 'activated' : ''),
                isAbove ? 'above' : 'blow'),
            autoCompletePopupClassName = classNames('dropdown-filter-popup', isAbove ? ' above' : ' blow', {
                [popupClassName]: popupClassName
            }),
            autoCompletePopupStyle = Object.assign({
                width: this.triggerEl && getComputedStyle(this.triggerEl).width
            }, popupStyle);

        return (

                <TextField ref="trigger"
                           className={triggerClassName}
                           theme={theme}
                           value={filter}
                           placeholder={placeholder}
                           disabled={disabled}
                           iconCls={iconCls}
                           rightIconCls={rightIconCls}
                           onFocus={this.triggerFocusHandler}
                           onBlur={this.triggerBlurHandler}
                           onMouseOver={onTriggerMouseOver}
                           onMouseOut={onTriggerMouseOut}
                           onChange={this.filterChangeHandler}
                           onPressEnter={this.filterPressEnterHandler}
                           onClear={onFilterClear}
                           onRightIconTouchTap={this.filterPressEnterHandler}/>

                {
                    isEmpty && !noMatchedPopupVisible ?
                        null
                        :
                        <Popup className={autoCompletePopupClassName}
                               style={autoCompletePopupStyle}
                               theme={popupTheme}
                               visible={popupVisible}
                               triggerEl={this.triggerEl}
                               hasTriangle={false}
                               triggerMode={Popup.TriggerMode.OPEN}
                               position={isAbove ? Popup.Position.TOP_LEFT : Popup.Position.BOTTOM_LEFT}
                               onRender={this.popupRenderHandler}
                               onRequestClose={this.closePopup}>

                            {
                                isEmpty ?
                                    <List className="dropdown-filter-list"
                                          theme={popupTheme}
                                          selectMode={SelectMode.SINGLE_SELECT}
                                          data={emptyEl}/>
                                    :
                                    (
                                        useDynamicRenderList ?
                                            <DynamicRenderList className="dropdown-filter-list"
                                                               theme={popupTheme}
                                                               value={value}
                                                               selectMode={selectMode || SelectMode.SINGLE_SELECT}
                                                               data={listData}
                                                               valueField={valueField}
                                                               displayField={displayField}
                                                               descriptionField={descriptionField}
                                                               renderer={renderer}
                                                               listHeight={listHeight}
                                                               itemHeight={itemHeight}
                                                               scrollBuffer={scrollBuffer}
                                                               radioUncheckedIconCls={radioUncheckedIconCls}
                                                               radioCheckedIconCls={radioCheckedIconCls}
                                                               checkboxUncheckedIconCls={checkboxUncheckedIconCls}
                                                               checkboxCheckedIconCls={checkboxCheckedIconCls}
                                                               checkboxIndeterminateIconCls={checkboxIndeterminateIconCls}
                                                               onItemTouchTap={onItemTouchTap}
                                                               onChange={this.changeHandler}/>
                                            :
                                            <List className="dropdown-filter-list"
                                                  theme={popupTheme}
                                                  value={value}
                                                  selectMode={selectMode || SelectMode.SINGLE_SELECT}
                                                  data={listData}
                                                  valueField={valueField}
                                                  displayField={displayField}
                                                  descriptionField={descriptionField}
                                                  renderer={renderer}
                                                  radioUncheckedIconCls={radioUncheckedIconCls}
                                                  radioCheckedIconCls={radioCheckedIconCls}
                                                  checkboxUncheckedIconCls={checkboxUncheckedIconCls}
                                                  checkboxCheckedIconCls={checkboxCheckedIconCls}
                                                  checkboxIndeterminateIconCls={checkboxIndeterminateIconCls}
                                                  onItemTouchTap={onItemTouchTap}
                                                  onChange={this.changeHandler}/>
                                    )
                            }

                            {popupChildren}

                        </Popup>
                }

        );
    }

};

DropdownFilter.propTypes = {

    /**
     * The CSS class name of the root element.
     */
    className: PropTypes.string,

    /**
     * The CSS class name of the popup element.
     */
    popupClassName: PropTypes.string,

    /**
     * Override the styles of the root element.
     */
    style: PropTypes.object,

    /**
     * Override the styles of the popup element.
     */
    popupStyle: PropTypes.object,

    /**
     * The theme.
     */
    theme: PropTypes.oneOf(Util.enumerateValue(Theme)),

    /**
     * The theme.
     */
    popupTheme: PropTypes.oneOf(Util.enumerateValue(Theme)),

    /**
     * The placeholder of the field.
     */
    placeholder: PropTypes.string,

    /**
     * Children passed into the List.
     */
    data: PropTypes.oneOfType([

        // not grouped
        PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.shape({

            /**
             * The CSS class name of the list button.
             */
            className: PropTypes.string,

            /**
             * Override the styles of the list button.
             */
            style: PropTypes.object,

            /**
             * The theme of the list button.
             */
            theme: PropTypes.oneOf(Util.enumerateValue(Theme)),

            /**
             * The text value of the list button.Type can be string or number.
             */
            value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),

            /**
             * The desc value of the list button. Type can be string or number.
             */
            desc: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),

            /**
             * If true, the list button will be disabled.
             */
            disabled: PropTypes.bool,

            /**
             * If true,the button will be have loading effect.
             */
            isLoading: PropTypes.bool,

            /**
             * If true,the element's ripple effect will be disabled.
             */
            disableTouchRipple: PropTypes.bool,

            /**
             * Use this property to display an icon. It will display on the left.
             */
            iconCls: PropTypes.string,

            /**
             * Use this property to display an icon. It will display on the right.
             */
            rightIconCls: PropTypes.string,

            /**
             * You can create a complicated renderer callback instead of value and desc prop.
             */
            itemRenderer: PropTypes.func,

            /**
             * Callback function fired when a list item touch-tapped.
             */
            onTouchTap: PropTypes.func

        }), PropTypes.string, PropTypes.number])),

        // grouped
        PropTypes.array

    ]).isRequired,

    /**
     * If true, the auto complete will be disabled.
     */
    disabled: PropTypes.bool,

    /**
     * The value field name in data. (default: "value")
     */
    valueField: PropTypes.string,

    /**
     * The display field name in data. (default: "text")
     */
    displayField: PropTypes.string,

    /**
     * The description field name in data. (default: "desc")
     */
    descriptionField: PropTypes.string,

    /**
     * If true, the popup list automatically closed after selection.
     */
    autoClose: PropTypes.bool,

    /**
     * The type of dropDown list,can be normal,checkbox,radio.
     */
    selectMode: PropTypes.oneOf(Util.enumerateValue(SelectMode)),

    /**
     * Callback function fired when filter changed.
     */
    filterCallback: PropTypes.func,

    /**
     * Use this property to display an icon.
     */
    iconCls: PropTypes.string,

    /**
     * Use this property to display an icon.
     */
    rightIconCls: PropTypes.string,

    /**
     * The visiblity of no matched popup.
     */
    noMatchedPopupVisible: PropTypes.bool,

    /**
     * The message of no matched value.
     */
    noMatchedMsg: PropTypes.string,

    popupChildren: PropTypes.any,

    useDynamicRenderList: PropTypes.bool,
    listHeight: PropTypes.number,
    itemHeight: PropTypes.number,
    scrollBuffer: PropTypes.number,

    radioUncheckedIconCls: PropTypes.string,
    radioCheckedIconCls: PropTypes.string,
    checkboxUncheckedIconCls: PropTypes.string,
    checkboxCheckedIconCls: PropTypes.string,
    checkboxIndeterminateIconCls: PropTypes.string,

    /**
     * You can create a complicated renderer callback instead of value and desc prop.
     */
    renderer: PropTypes.func,

    /**
     * The function that trigger when filter changes.
     */
    onFilterChange: PropTypes.func,

    /**
     * The function that trigger when press enter.
     */
    onFilterPressEnter: PropTypes.func,

    /**
     * The function that trigger when filter cleared.
     */
    onFilterClear: PropTypes.func,

    /**
     * The function that trigger when value changed.
     */
    onChange: PropTypes.func,

    /**
     * The function that trigger when touch-tap the list items.
     */
    onItemTouchTap: PropTypes.func,

    /**
     * Callback function fired when DropdownFilter get focus.
     */
    onFocus: PropTypes.func,

    /**
     * Callback function fired when DropdownFilter lose focus.
     */
    onBlur: PropTypes.func,

    onTriggerMouseOver: PropTypes.func,
    onTriggerMouseOut: PropTypes.func,
    onPopupClosed: PropTypes.func

};

DropdownFilter.defaultProps = {

    className: null,
    popupClassName: null,
    style: null,
    popupStyle: null,
    theme: Theme.DEFAULT,
    popupTheme: Theme.DEFAULT,

    placeholder: null,
    data: [],
    disabled: false,
    valueField: 'value',
    displayField: 'text',
    descriptionField: 'desc',
    autoClose: false,
    selectMode: SelectMode.SINGLE_SELECT,
    iconCls: null,
    rightIconCls: 'fa fa-search',
    noMatchedPopupVisible: true,
    noMatchedMsg: null,

    popupChildren: null,

    useDynamicRenderList: false,

    radioUncheckedIconCls: null,
    radioCheckedIconCls: null,
    checkboxUncheckedIconCls: 'fa fa-square-o',
    checkboxCheckedIconCls: 'fa fa-check-square',
    checkboxIndeterminateIconCls: 'fa fa-minus-square'

};

export default DropdownFilter;<|endoftext|>


<commit_before>/*!
 * Copyright 2015 Geoscience Australia (http://www.ga.gov.au/copyright.html)
 */

(function(angular) {

'use strict';

angular.module("icsm.toolbar", [])

.directive("icsmToolbar", [function() {
	return {
		controller: 'toolbarLinksCtrl'
	};
}])

/**
 * Override the default mars tool bar row so that a different implementation of the toolbar can be used.
 */
.directive('icsmToolbarRow', [function() {
	return {
		scope:{
			map:"="
		},
		restrict:'AE',
		templateUrl:'icsm/toolbar/toolbar.html'
	};
}])

.directive('icsmToolbarInfo', [function() {
	return {
		templateUrl: 'radwaste/toolbar/toolbarInfo.html'
	};
}])

.controller("toolbarLinksCtrl", ["$scope", "configService", function($scope, configService) {

	var self = this;
	configService.getConfig().then(function(config) {
		self.links = config.toolbarLinks;
	});

	$scope.item = "";
	$scope.toggleItem = function(item) {
		$scope.item = ($scope.item == item) ? "" : item;
	};

}]);

})(angular);<commit_msg>Implement eslint suggestion around equals comparison<commit_after>/*!
 * Copyright 2015 Geoscience Australia (http://www.ga.gov.au/copyright.html)
 */

(function(angular) {

'use strict';

angular.module("icsm.toolbar", [])

.directive("icsmToolbar", [function() {
	return {
		controller: 'toolbarLinksCtrl'
	};
}])

/**
 * Override the default mars tool bar row so that a different implementation of the toolbar can be used.
 */
.directive('icsmToolbarRow', [function() {
	return {
		scope:{
			map:"="
		},
		restrict:'AE',
		templateUrl:'icsm/toolbar/toolbar.html'
	};
}])

.directive('icsmToolbarInfo', [function() {
	return {
		templateUrl: 'radwaste/toolbar/toolbarInfo.html'
	};
}])

.controller("toolbarLinksCtrl", ["$scope", "configService", function($scope, configService) {

	var self = this;
	configService.getConfig().then(function(config) {
		self.links = config.toolbarLinks;
	});

	$scope.item = "";
	$scope.toggleItem = function(item) {
		$scope.item = ($scope.item === item) ? "" : item;
	};

}]);

})(angular);<|endoftext|>


<commit_before>define([
  'summernote/core/list',
  'summernote/core/func',
  'summernote/core/dom',
  'summernote/core/range'
], function (list, func, dom, range) {

  var Bullet = function () {
    /**
     * toggle ordered list
     * @type command
     */
    this.insertOrderedList = function () {
      this.toggleList('OL');
    };

    /**
     * toggle unordered list
     * @type command
     */
    this.insertUnorderedList = function () {
      this.toggleList('UL');
    };

    /**
     * indent
     * @type command
     */
    this.indent = function () {
      var self = this;
      var rng = range.create().wrapBodyInlineWithPara();

      var paras = rng.nodes(dom.isPara, { includeAncestor: true });
      var clustereds = list.clusterBy(paras, func.peq2('parentNode'));

      $.each(clustereds, function (idx, paras) {
        var head = list.head(paras);
        if (dom.isLi(head)) {
          self.wrapList(paras, head.parentNode.nodeName);
        } else {
          $.each(paras, function (idx, para) {
            $(para).css('marginLeft', function (idx, val) {
              return (parseInt(val, 10) || 0) + 25;
            });
          });
        }
      });

      rng.select();
    };

    /**
     * outdent
     * @type command
     */
    this.outdent = function () {
      var self = this;
      var rng = range.create().wrapBodyInlineWithPara();

      var paras = rng.nodes(dom.isPara, { includeAncestor: true });
      var clustereds = list.clusterBy(paras, func.peq2('parentNode'));

      $.each(clustereds, function (idx, paras) {
        var head = list.head(paras);
        if (dom.isLi(head)) {
          self.releaseList([paras]);
        } else {
          $.each(paras, function (idx, para) {
            $(para).css('marginLeft', function (idx, val) {
              val = (parseInt(val, 10) || 0);
              return val > 25 ? val - 25 : '';
            });
          });
        }
      });

      rng.select();
    };

    /**
     * toggle list
     * @param {String} listName - OL or UL
     */
    this.toggleList = function (listName) {
      var self = this;
      var rng = range.create().wrapBodyInlineWithPara();

      var paras = rng.nodes(dom.isPara, { includeAncestor: true });
      var bookmark = rng.paraBookmark(paras);
      var clustereds = list.clusterBy(paras, func.peq2('parentNode'));

      // paragraph to list
      if (list.find(paras, dom.isPurePara)) {
        var wrappedParas = [];
        $.each(clustereds, function (idx, paras) {
          wrappedParas = wrappedParas.concat(self.wrapList(paras, listName));
        });
        paras = wrappedParas;
      // list to paragraph or change list style
      } else {
        var diffLists = rng.nodes(dom.isList, {
          includeAncestor: true
        }).filter(function (listNode) {
          return !$.nodeName(listNode, listName);
        });

        if (diffLists.length) {
          $.each(diffLists, function (idx, listNode) {
            dom.replace(listNode, listName);
          });
        } else {
          paras = this.releaseList(clustereds, true);
        }
      }

      range.createFromParaBookmark(bookmark, paras).select();
    };

    /**
     * @param {Node[]} paras
     * @param {String} listName
     * @return {Node[]}
     */
    this.wrapList = function (paras, listName) {
      var head = list.head(paras);
      var last = list.last(paras);

      var prevList = dom.isList(head.previousSibling) && head.previousSibling;
      var nextList = dom.isList(last.nextSibling) && last.nextSibling;

      var listNode = prevList || dom.insertAfter(dom.create(listName || 'UL'), last);

      // P to LI
      paras = $.map(paras, function (para) {
        return dom.isPurePara(para) ? dom.replace(para, 'LI') : para;
      });

      // append to list(<ul>, <ol>)
      dom.appendChildNodes(listNode, paras);

      if (nextList) {
        dom.appendChildNodes(listNode, list.from(nextList.childNodes));
        dom.remove(nextList);
      }

      return paras;
    };

    /**
     * @param {Array[]} clustereds
     * @param {Boolean} isEscapseToBody
     * @return {Node[]}
     */
    this.releaseList = function (clustereds, isEscapseToBody) {
      var releasedParas = [];

      $.each(clustereds, function (idx, paras) {
        var head = list.head(paras);
        var last = list.last(paras);

        var headList = isEscapseToBody ? dom.lastAncestor(head, dom.isList) :
                                         head.parentNode;
        var lastList = headList.childNodes.length > 1 ? dom.splitTree(headList, {
          node: last.parentNode,
          offset: dom.position(last) + 1
        }, true) : null;

        var middleList = dom.splitTree(headList, {
          node: head.parentNode,
          offset: dom.position(head)
        }, true);

        paras = isEscapseToBody ? dom.listDescendant(middleList, dom.isLi) :
                                  list.from(middleList.childNodes).filter(dom.isLi);

        // LI to P
        if (isEscapseToBody || !dom.isList(headList.parentNode)) {
          paras = $.map(paras, function (para) {
            return dom.replace(para, 'P');
          });
        }

        $.each(list.from(paras).reverse(), function (idx, para) {
          dom.insertAfter(para, headList);
        });

        // remove empty lists
        var rootLists = list.compact([headList, middleList, lastList]);
        $.each(rootLists, function (idx, rootList) {
          var listNodes = [rootList].concat(dom.listDescendant(rootList, dom.isList));
          $.each(listNodes.reverse(), function (idx, listNode) {
            if (!dom.nodeLength(listNode)) {
              dom.remove(listNode, true);
            }
          });
        });

        releasedParas = releasedParas.concat(paras);
      });

      return releasedParas;
    };
  };

  return Bullet;
});

<commit_msg>add jsduck<commit_after>define([
  'summernote/core/list',
  'summernote/core/func',
  'summernote/core/dom',
  'summernote/core/range'
], function (list, func, dom, range) {

  /**
   * @class editing.Bullet
   *
   * @singleton
   * @alternateClassName Bullet
   */
  var Bullet = function () {
    /**
     * @method insertOrderedList
     *
     * toggle ordered list
     *
     * @type command
     */
    this.insertOrderedList = function () {
      this.toggleList('OL');
    };

    /**
     * @method insertUnorderedList
     *
     * toggle unordered list
     *
     * @type command
     */
    this.insertUnorderedList = function () {
      this.toggleList('UL');
    };

    /**
     * @method indent
     *
     * indent
     *
     * @type command
     */
    this.indent = function () {
      var self = this;
      var rng = range.create().wrapBodyInlineWithPara();

      var paras = rng.nodes(dom.isPara, { includeAncestor: true });
      var clustereds = list.clusterBy(paras, func.peq2('parentNode'));

      $.each(clustereds, function (idx, paras) {
        var head = list.head(paras);
        if (dom.isLi(head)) {
          self.wrapList(paras, head.parentNode.nodeName);
        } else {
          $.each(paras, function (idx, para) {
            $(para).css('marginLeft', function (idx, val) {
              return (parseInt(val, 10) || 0) + 25;
            });
          });
        }
      });

      rng.select();
    };

    /**
     * @method outdent
     *
     * outdent
     *
     * @type command
     */
    this.outdent = function () {
      var self = this;
      var rng = range.create().wrapBodyInlineWithPara();

      var paras = rng.nodes(dom.isPara, { includeAncestor: true });
      var clustereds = list.clusterBy(paras, func.peq2('parentNode'));

      $.each(clustereds, function (idx, paras) {
        var head = list.head(paras);
        if (dom.isLi(head)) {
          self.releaseList([paras]);
        } else {
          $.each(paras, function (idx, para) {
            $(para).css('marginLeft', function (idx, val) {
              val = (parseInt(val, 10) || 0);
              return val > 25 ? val - 25 : '';
            });
          });
        }
      });

      rng.select();
    };

    /**
     * @method toggleList
     *
     * toggle list
     *
     * @param {String} listName - OL or UL
     */
    this.toggleList = function (listName) {
      var self = this;
      var rng = range.create().wrapBodyInlineWithPara();

      var paras = rng.nodes(dom.isPara, { includeAncestor: true });
      var bookmark = rng.paraBookmark(paras);
      var clustereds = list.clusterBy(paras, func.peq2('parentNode'));

      // paragraph to list
      if (list.find(paras, dom.isPurePara)) {
        var wrappedParas = [];
        $.each(clustereds, function (idx, paras) {
          wrappedParas = wrappedParas.concat(self.wrapList(paras, listName));
        });
        paras = wrappedParas;
      // list to paragraph or change list style
      } else {
        var diffLists = rng.nodes(dom.isList, {
          includeAncestor: true
        }).filter(function (listNode) {
          return !$.nodeName(listNode, listName);
        });

        if (diffLists.length) {
          $.each(diffLists, function (idx, listNode) {
            dom.replace(listNode, listName);
          });
        } else {
          paras = this.releaseList(clustereds, true);
        }
      }

      range.createFromParaBookmark(bookmark, paras).select();
    };

    /**
     * @method wrapList
     *
     * @param {Node[]} paras
     * @param {String} listName
     * @return {Node[]}
     */
    this.wrapList = function (paras, listName) {
      var head = list.head(paras);
      var last = list.last(paras);

      var prevList = dom.isList(head.previousSibling) && head.previousSibling;
      var nextList = dom.isList(last.nextSibling) && last.nextSibling;

      var listNode = prevList || dom.insertAfter(dom.create(listName || 'UL'), last);

      // P to LI
      paras = $.map(paras, function (para) {
        return dom.isPurePara(para) ? dom.replace(para, 'LI') : para;
      });

      // append to list(<ul>, <ol>)
      dom.appendChildNodes(listNode, paras);

      if (nextList) {
        dom.appendChildNodes(listNode, list.from(nextList.childNodes));
        dom.remove(nextList);
      }

      return paras;
    };

    /**
     * @method releaseList
     *
     * @param {Array[]} clustereds
     * @param {Boolean} isEscapseToBody
     * @return {Node[]}
     */
    this.releaseList = function (clustereds, isEscapseToBody) {
      var releasedParas = [];

      $.each(clustereds, function (idx, paras) {
        var head = list.head(paras);
        var last = list.last(paras);

        var headList = isEscapseToBody ? dom.lastAncestor(head, dom.isList) :
                                         head.parentNode;
        var lastList = headList.childNodes.length > 1 ? dom.splitTree(headList, {
          node: last.parentNode,
          offset: dom.position(last) + 1
        }, true) : null;

        var middleList = dom.splitTree(headList, {
          node: head.parentNode,
          offset: dom.position(head)
        }, true);

        paras = isEscapseToBody ? dom.listDescendant(middleList, dom.isLi) :
                                  list.from(middleList.childNodes).filter(dom.isLi);

        // LI to P
        if (isEscapseToBody || !dom.isList(headList.parentNode)) {
          paras = $.map(paras, function (para) {
            return dom.replace(para, 'P');
          });
        }

        $.each(list.from(paras).reverse(), function (idx, para) {
          dom.insertAfter(para, headList);
        });

        // remove empty lists
        var rootLists = list.compact([headList, middleList, lastList]);
        $.each(rootLists, function (idx, rootList) {
          var listNodes = [rootList].concat(dom.listDescendant(rootList, dom.isList));
          $.each(listNodes.reverse(), function (idx, listNode) {
            if (!dom.nodeLength(listNode)) {
              dom.remove(listNode, true);
            }
          });
        });

        releasedParas = releasedParas.concat(paras);
      });

      return releasedParas;
    };
  };

  return Bullet;
});

<|endoftext|>


<commit_before>var oldTicketArray = [];
var newTicketArray = [];

$( document ).ready(function() {
    $.getJSON( "/TicketsWcf/TicketsService.svc/GetOpenTickets", function (data) {
		oldTicketArray = data;
		$.each (data, function (index, ticketObject) {
			createDiv(ticketObject)
		});
	});

	setInterval(function() {
		$.getJSON( "/TicketsWcf/TicketsService.svc/GetOpenTickets", function (data) {
			newTicketArray = data;

			for (var i = 0; i < oldTicketArray.length; i++){
				//check for ticket numbers in new array.  Anything found compare the rest of the ticket info and update div if necissary. anything missing close

			}
			for (var i = 0; i < newTicketArray.length; i++){
				//check for ticket numbers in old array.  Anything missing open
			}
		});
	}, 30000);
});

function updateDiv(ticketNum){

}

function deleteDiv(ticketNum){

}

function createDiv(ticket){
	var ticketDiv = document.createElement("div");
	$(ticketDiv).addClass("ticketdiv");
	$(ticketDiv).data(ticket);

	var clientDiv = document.createElement("div");
	$(clientDiv).addClass("clientdiv");

	var clientDivText = document.createElement("span");
	clientDivText.innerHTML = ticket.ClientName;
	$(clientDiv).append(clientDivText);

	var descriptionDiv = document.createElement("div");
	$(descriptionDiv).addClass("deescriptiondiv");

	var descriptionDivText = document.createElement("span");
	descriptionDivText.innerHTML = ticket.Description;
	$(descriptionDiv).append(descriptionDivText);

	var assignDiv = document.createElement("div");
	$(assignDiv).addClass("assigndiv");

	var assignDivText = document.createElement("span");
	assignDivText.innerHTML = ticket.AssignTech;
	$(assignDiv).append(assignDivText);

	$(ticketDiv).append(clientDiv);
	$(ticketDiv).append(descriptionDiv);
	$(ticketDiv).append(assignDiv);

	$("#wrapper").append(ticketDiv);
}

<commit_msg>added code for delete function. not tested at all<commit_after>var oldTicketArray = [];
var newTicketArray = [];

$( document ).ready(function() {
    $.getJSON( "/TicketsWcf/TicketsService.svc/GetOpenTickets", function (data) {
		oldTicketArray = data;
		$.each (data, function (index, ticketObject) {
			createDiv(ticketObject)
		});
	});

	setInterval(function() {
		$.getJSON( "/TicketsWcf/TicketsService.svc/GetOpenTickets", function (data) {
			newTicketArray = data;

			for (var i = 0; i < oldTicketArray.length; i++){
				//check for ticket numbers in new array.  Anything found compare the rest of the ticket info and update div if necissary. anything missing close

			}
			for (var i = 0; i < newTicketArray.length; i++){
				//check for ticket numbers in old array.  Anything missing open
			}
		});
	}, 30000);
});

function updateDiv(ticketNum){

}

function deleteDiv(ticketNum){
	$('#wrapper > div').each(function () {
		if ($(this).data("ticketNum") == ticketNum){
			$(this).remove();
		}
	});
}

function createDiv(ticket){
	var ticketDiv = document.createElement("div");
	$(ticketDiv).addClass("ticketdiv");
	$(ticketDiv).data(ticket);

	var clientDiv = document.createElement("div");
	$(clientDiv).addClass("clientdiv");

	var clientDivText = document.createElement("span");
	clientDivText.innerHTML = ticket.ClientName;
	$(clientDiv).append(clientDivText);

	var descriptionDiv = document.createElement("div");
	$(descriptionDiv).addClass("deescriptiondiv");

	var descriptionDivText = document.createElement("span");
	descriptionDivText.innerHTML = ticket.Description;
	$(descriptionDiv).append(descriptionDivText);

	var assignDiv = document.createElement("div");
	$(assignDiv).addClass("assigndiv");

	var assignDivText = document.createElement("span");
	assignDivText.innerHTML = ticket.AssignTech;
	$(assignDiv).append(assignDivText);

	$(ticketDiv).append(clientDiv);
	$(ticketDiv).append(descriptionDiv);
	$(ticketDiv).append(assignDiv);

	$("#wrapper").append(ticketDiv);
}

<|endoftext|>


<commit_before>{
  const words = '[⎕\\]\\)A-Z_a-zÀ-ÖØ-Ýß-öø-üþ∆⍙Ⓐ-Ⓩ\\d]';
  const prefixRE = new RegExp(`^(${words}*)${words}*(?: \\1${words}*)*$`);

  D.ac = (me) => {
    me.tabComplete = 0;
    me.onDidChangeModelContent((e) => {
      const pk = D.prf.prefixKey();
      if (!me.dyalogBQ && e.changes.length === 1
        && e.changes[0].text === pk) {
        D.commands.BQC(me);
      } else {
        setTimeout(() => {
          const sw = me.contentWidgets['editor.widget.suggestWidget'];
          const swv = sw.widget.suggestWidgetVisible.get();
          const r = e.changes[0].range;
          const l = me.model.getLineContent(r.startLineNumber).toLowerCase();
          const bq2 = e.changes.length === 1 && RegExp(`${pk}${pk}\\w*`, 'i').test(l);
          if (swv && sw.widget.list.length === 1) {
            const t = sw.widget.focusedItem.suggestion.insertText.toLowerCase();
            if (l.slice(r.startColumn - t.length, r.startColumn) === t) {
              me.trigger('editor', 'hideSuggestWidget');
            } else {
              me.trigger('editor', 'editor.action.triggerSuggest');
            }
          } else if (swv && !sw.widget.list.length) {
            me.trigger('editor', 'hideSuggestWidget');
          } else if (swv && !bq2 && sw.widget.list.length > 1) {
            me.trigger('editor', 'editor.action.triggerSuggest');
          }
        }, 50);
      }
    });
    return (x) => { // win:editor or session instance to set up autocompletion in
      const { ac } = me.model;
      if (ac && ac.complete) {
        const l = ac.position.lineNumber;
        const c = ac.position.column;
        const manual = me.tabComplete;
        if (D.prf.autocompletion() === 'shell' && manual) {
          const prefix = x.options.join(' ').match(prefixRE)[1];
          if (prefix.length > x.skip) {
            const endCol = (c - x.skip) + prefix.length;
            me.executeEdits(
              'D',
              [{ range: new monaco.Range(l, c - x.skip, l, c), text: prefix }],
              [new monaco.Selection(l, endCol, l, endCol)],
            );
            me.trigger('editor', 'hideSuggestWidget');
            me.tabComplete = 0;
            return;
          } else if (me.tabComplete < 2) {
            me.trigger('editor', 'hideSuggestWidget');
            return;
          }
          me.tabComplete = 0;
        }
        if (!x.options.length || (D.prf.autocompletion() === 'shell' && !manual)) {
          me.trigger('editor', 'hideSuggestWidget');
          return;
        }
        ac.complete(x.options.map(i => ({
          label: i,
          range: new monaco.Range(l, c - x.skip, l, c),
        })));
      }
    };
  };
}
<commit_msg>shell complete ucmds with dot<commit_after>{
  const words = '[⎕\\]\\)\\.A-Z_a-zÀ-ÖØ-Ýß-öø-üþ∆⍙Ⓐ-Ⓩ\\d]';
  const prefixRE = new RegExp(`^(${words}*)${words}*(?: \\1${words}*)*$`);

  D.ac = (me) => {
    me.tabComplete = 0;
    me.onDidChangeModelContent((e) => {
      const pk = D.prf.prefixKey();
      if (!me.dyalogBQ && e.changes.length === 1
        && e.changes[0].text === pk) {
        D.commands.BQC(me);
      } else {
        setTimeout(() => {
          const sw = me.contentWidgets['editor.widget.suggestWidget'];
          const swv = sw.widget.suggestWidgetVisible.get();
          const r = e.changes[0].range;
          const l = me.model.getLineContent(r.startLineNumber).toLowerCase();
          const bq2 = e.changes.length === 1 && RegExp(`${pk}${pk}\\w*`, 'i').test(l);
          if (swv && sw.widget.list.length === 1) {
            const t = sw.widget.focusedItem.suggestion.insertText.toLowerCase();
            if (l.slice(r.startColumn - t.length, r.startColumn) === t) {
              me.trigger('editor', 'hideSuggestWidget');
            } else {
              me.trigger('editor', 'editor.action.triggerSuggest');
            }
          } else if (swv && !sw.widget.list.length) {
            me.trigger('editor', 'hideSuggestWidget');
          } else if (swv && !bq2 && sw.widget.list.length > 1) {
            me.trigger('editor', 'editor.action.triggerSuggest');
          }
        }, 50);
      }
    });
    return (x) => { // win:editor or session instance to set up autocompletion in
      const { ac } = me.model;
      if (ac && ac.complete) {
        const l = ac.position.lineNumber;
        const c = ac.position.column;
        const manual = me.tabComplete;
        if (D.prf.autocompletion() === 'shell' && manual) {
          const [,prefix] = x.options.join(' ').match(prefixRE);
          if (prefix && prefix.length > x.skip) {
            const endCol = (c - x.skip) + prefix.length;
            me.executeEdits(
              'D',
              [{ range: new monaco.Range(l, c - x.skip, l, c), text: prefix }],
              [new monaco.Selection(l, endCol, l, endCol)],
            );
            me.trigger('editor', 'hideSuggestWidget');
            me.tabComplete = 0;
            return;
          } else if (me.tabComplete < 2) {
            me.trigger('editor', 'hideSuggestWidget');
            return;
          }
          me.tabComplete = 0;
        }
        if (!x.options.length || (D.prf.autocompletion() === 'shell' && !manual)) {
          me.trigger('editor', 'hideSuggestWidget');
          return;
        }
        ac.complete(x.options.map(i => ({
          label: i,
          range: new monaco.Range(l, c - x.skip, l, c),
        })));
      }
    };
  };
}
<|endoftext|>