<commit_before>/*
* mvcAction
* author: ronglin
* create date: 2014.6.24
*/

'use strict';

var utils = require('./utilities'),
    injector = require('./mvcInjector'),
    httpMethod = require('./mvcHttpMethod'),
    actionResults = require('./mvcActionResults');

var lowerRootNs = function(namespace) {
    var index = namespace.search(/\.|\[|\]/);
    if (index > -1) {
        return namespace.substr(0, index).toLowerCase() + namespace.substr(index);
    } else {
        return namespace.toLowerCase();
    }
};

var mvcAction = function(set) {
    utils.extend(this, set);
};

mvcAction.isAction = true;

mvcAction.prototype = {

    ctrl: null, name: null, impl: null, sett: null,

    constructor: mvcAction,

    hasMethod: function(method) {
        if (!httpMethod.exists(method)) {
            return false;
        }
        //
        var methodStr = ',';
        if (!this.sett) {
            methodStr += 'GET,';
        } else if (utils.isString(this.sett)) {
            methodStr += this.sett + ',';
        } else if (utils.isObject(this.sett)) {
            utils.each(this.sett, function(key, val) {
                if (val) { methodStr += key + ','; }
            });
        }
        return methodStr.replace(/\s/g, '').toUpperCase().indexOf(',' + method.toUpperCase() + ',') > -1;
    },

    injectImpl: function(req) {
        var params = [];
        var paramNames = injector.annotate(this.impl);
        if (!paramNames || paramNames.length === 0) { return params; }
        //
        var body = {}, query = {}, routeData = {};
        utils.each(req.body, function(key, val) {
            utils.mapObj(body, lowerRootNs(key), val);
        });
        utils.each(req.query, function(key, val) {
            utils.mapObj(query, lowerRootNs(key), val);
        });
        utils.each(req.routeData, function(i, it) {
            utils.mapObj(routeData, lowerRootNs(it.name), it.value);
        });
        utils.each(paramNames, function(i, name) {
            var loweName = name.toLowerCase();
            if (loweName.charAt(0) === '$') {
                loweName = loweName.substr(1);
            }
            if (loweName in body) {
                params.push(body[loweName]);
            } else if (loweName in query) {
                params.push(query[loweName]);
            } else if(loweName in routeData) {
                params.push(routeData[loweName]);
            } else {
                params.push(null);
            }
        });
        //
        return params;
    },

    execute: function(req, res) {
        if (!utils.isFunction(this.impl)) { return; }
        // execute action
        var injectedParams = this.injectImpl(req);
        var actionContext = {
            request: req,
            response: res,
            params: injectedParams,
            result: null
        };
        this.ctrl.events.emit('actionExecuting', actionContext);
        actionContext.result = this.impl.apply(this.ctrl, injectedParams);
        this.ctrl.events.emit('actionExecuted', actionContext);
        // ret
        return actionContext.result;
    },

    executeResult: function(req, res, result) {
        if (result === undefined || result === null) { return; }
        //
        if (!(result instanceof actionResults.baseResult)) {
            result = new actionResults.contentResult({
                content: result.toString(),
                contentType: 'text/plain'
            });
        }
        else if (result instanceof actionResults.viewResult) {
            if (!result.viewName) {
                result.viewName = this.name;
            }
            if (!result.model) {
                result.model = this.ctrl.viewdata;
            }
        }
        else if (result instanceof actionResults.partialViewResult) {
            if (!result.viewName) {
                result.viewName = this.name;
            }
        }
        //
        var resultContext = {
            request: req,
            response: res,
            result: result,
            exception: null
        };
        this.ctrl.events.emit('resultExecuting', resultContext);
        result.execute(resultContext);
        this.ctrl.events.emit('resultExecuted', resultContext);
        // ret
        return resultContext.exception;
    }
};

module.exports = mvcAction;
<commit_msg>update<commit_after>/*
* mvcAction
* author: ronglin
* create date: 2014.6.24
*/

'use strict';

var utils = require('./utilities'),
    injector = require('./mvcInjector'),
    httpMethod = require('./mvcHttpMethod'),
    actionResults = require('./mvcActionResults');

var lowerRootNs = function(namespace) {
    var index = namespace.search(/\.|\[|\]/);
    if (index > -1) {
        return namespace.substr(0, index).toLowerCase() + namespace.substr(index);
    } else {
        return namespace.toLowerCase();
    }
};

var mvcAction = function(set) {
    utils.extend(this, set);
};

mvcAction.isAction = true;

mvcAction.prototype = {

    controller: null, name: null, impl: null, sett: null,

    constructor: mvcAction,

    hasMethod: function(method) {
        if (!httpMethod.exists(method)) {
            return false;
        }
        //
        var methodStr = ',';
        if (!this.sett) {
            methodStr += 'GET,';
        } else if (utils.isString(this.sett)) {
            methodStr += this.sett + ',';
        } else if (utils.isObject(this.sett)) {
            utils.each(this.sett, function(key, val) {
                if (val) { methodStr += key + ','; }
            });
        }
        return methodStr.replace(/\s/g, '').toUpperCase().indexOf(',' + method.toUpperCase() + ',') > -1;
    },

    injectImpl: function(req) {
        var params = [];
        var paramNames = injector.annotate(this.impl);
        if (!paramNames || paramNames.length === 0) { return params; }
        //
        var body = {}, query = {}, routeData = {};
        utils.each(req.body, function(key, val) {
            utils.mapObj(body, lowerRootNs(key), val);
        });
        utils.each(req.query, function(key, val) {
            utils.mapObj(query, lowerRootNs(key), val);
        });
        utils.each(req.routeData, function(i, it) {
            utils.mapObj(routeData, lowerRootNs(it.name), it.value);
        });
        utils.each(paramNames, function(i, name) {
            var loweName = name.toLowerCase();
            if (loweName.charAt(0) === '$') {
                loweName = loweName.substr(1);
            }
            if (loweName in body) {
                params.push(body[loweName]);
            } else if (loweName in query) {
                params.push(query[loweName]);
            } else if(loweName in routeData) {
                params.push(routeData[loweName]);
            } else {
                params.push(null);
            }
        });
        //
        return params;
    },

    execute: function(req, res) {
        if (!utils.isFunction(this.impl)) { return; }
        // execute action
        var injectedParams = this.injectImpl(req);
        var actionContext = {
            request: req,
            response: res,
            params: injectedParams,
            result: null
        };
        this.controller.events.emit('actionExecuting', actionContext);
        actionContext.result = this.impl.apply(this.controller, injectedParams);
        this.controller.events.emit('actionExecuted', actionContext);
        // ret
        return actionContext.result;
    },

    executeResult: function(req, res, result) {
        if (result === undefined || result === null) { return; }
        //
        if (!(result instanceof actionResults.baseResult)) {
            result = new actionResults.contentResult({
                content: result.toString(),
                contentType: 'text/plain'
            });
        }
        else if (result instanceof actionResults.viewResult) {
            if (!result.viewName) {
                result.viewName = this.name;
            }
            if (!result.model) {
                result.model = this.controller.viewData;
            }
        }
        else if (result instanceof actionResults.partialViewResult) {
            if (!result.viewName) {
                result.viewName = this.name;
            }
        }
        //
        var resultContext = {
            request: req,
            response: res,
            result: result,
            exception: null
        };
        this.controller.events.emit('resultExecuting', resultContext);
        result.execute(resultContext);
        this.controller.events.emit('resultExecuted', resultContext);
        // ret
        return resultContext.exception;
    }
};

module.exports = mvcAction;
<|endoftext|>


<commit_before>/*
* utilities
* author: ronglin
* create date: 2014.6.24
*/

'use strict';

var path = require('path'),
    utils = require('../jsg/utilities'),
    cmsDir = path.normalize(__dirname + path.sep + '..');

module.exports = utils.extend({}, utils, {

    absPath: function() {
        var args = utils.arg2arr(arguments);
        if (path.sep === '\\') {
            utils.each(args, function(i, val) {
                args[i] = val.replace(/\//g, '\\');
            });
        }
        args.unshift(cmsDir);
        return path.join.apply(path, args);
    }

});<commit_msg>isAbsolute<commit_after>/*
* utilities
* author: ronglin
* create date: 2014.6.24
*/

'use strict';

var path = require('path'),
    utils = require('../jsg/utilities'),
    cmsDir = path.normalize(__dirname + path.sep + '..');

module.exports = utils.extend({}, utils, {

    absPath: function() {
        var args = utils.arg2arr(arguments);
        if (path.sep === '\\') {
            utils.each(args, function(i, val) {
                args[i] = val.replace(/\//g, '\\');
            });
        }
        args.unshift(cmsDir);
        return path.join.apply(path, args);
    }，

    isAbsolute = function(path) {
        if ('/' == path.charAt(0)) { return true; }
        if (':' == path.charAt(1) && '\\' == path.charAt(2)) { return true; }
        if ('\\\\' == path.substring(0, 2)) { return true; } // Microsoft Azure absolute path
        return false;
    }

});<|endoftext|>


<commit_before>/*!
 * clipboard.js v1.5.5
 * https://zenorocha.github.io/clipboard.js
 *
 * Licensed MIT © Zeno Rocha
 */
!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,e.Clipboard=t()}}(function(){var t,e,n;return function t(e,n,r){function o(a,c){if(!n[a]){if(!e[a]){var s="function"==typeof require&&require;if(!c&&s)return s(a,!0);if(i)return i(a,!0);var u=new Error("Cannot find module '"+a+"'");throw u.code="MODULE_NOT_FOUND",u}var l=n[a]={exports:{}};e[a][0].call(l.exports,function(t){var n=e[a][1][t];return o(n?n:t)},l,l.exports,t,e,n,r)}return n[a].exports}for(var i="function"==typeof require&&require,a=0;a<r.length;a++)o(r[a]);return o}({1:[function(t,e,n){var r=t("matches-selector");e.exports=function(t,e,n){for(var o=n?t:t.parentNode;o&&o!==document;){if(r(o,e))return o;o=o.parentNode}}},{"matches-selector":2}],2:[function(t,e,n){function r(t,e){if(i)return i.call(t,e);for(var n=t.parentNode.querySelectorAll(e),r=0;r<n.length;++r)if(n[r]==t)return!0;return!1}var o=Element.prototype,i=o.matchesSelector||o.webkitMatchesSelector||o.mozMatchesSelector||o.msMatchesSelector||o.oMatchesSelector;e.exports=r},{}],3:[function(t,e,n){function r(t,e,n,r){var i=o.apply(this,arguments);return t.addEventListener(n,i),{destroy:function(){t.removeEventListener(n,i)}}}function o(t,e,n,r){return function(n){n.delegateTarget=i(n.target,e,!0),n.delegateTarget&&r.call(t,n)}}var i=t("closest");e.exports=r},{closest:1}],4:[function(t,e,n){n.node=function(t){return void 0!==t&&t instanceof HTMLElement&&1===t.nodeType},n.nodeList=function(t){var e=Object.prototype.toString.call(t);return void 0!==t&&("[object NodeList]"===e||"[object HTMLCollection]"===e)&&"length"in t&&(0===t.length||n.node(t[0]))},n.string=function(t){return"string"==typeof t||t instanceof String},n.function=function(t){var e=Object.prototype.toString.call(t);return"[object Function]"===e}},{}],5:[function(t,e,n){function r(t,e,n){if(!t&&!e&&!n)throw new Error("Missing required arguments");if(!c.string(e))throw new TypeError("Second argument must be a String");if(!c.function(n))throw new TypeError("Third argument must be a Function");if(c.node(t))return o(t,e,n);if(c.nodeList(t))return i(t,e,n);if(c.string(t))return a(t,e,n);throw new TypeError("First argument must be a String, HTMLElement, HTMLCollection, or NodeList")}function o(t,e,n){return t.addEventListener(e,n),{destroy:function(){t.removeEventListener(e,n)}}}function i(t,e,n){return Array.prototype.forEach.call(t,function(t){t.addEventListener(e,n)}),{destroy:function(){Array.prototype.forEach.call(t,function(t){t.removeEventListener(e,n)})}}}function a(t,e,n){return s(document.body,t,e,n)}var c=t("./is"),s=t("delegate");e.exports=r},{"./is":4,delegate:3}],6:[function(t,e,n){function r(t){var e;if("INPUT"===t.nodeName||"TEXTAREA"===t.nodeName)t.focus(),t.setSelectionRange(0,t.value.length),e=t.value;else{t.hasAttribute("contenteditable")&&t.focus();var n=window.getSelection(),r=document.createRange();r.selectNodeContents(t),n.removeAllRanges(),n.addRange(r),e=n.toString()}return e}e.exports=r},{}],7:[function(t,e,n){function r(){}r.prototype={on:function(t,e,n){var r=this.e||(this.e={});return(r[t]||(r[t]=[])).push({fn:e,ctx:n}),this},once:function(t,e,n){function r(){o.off(t,r),e.apply(n,arguments)}var o=this;return r._=e,this.on(t,r,n)},emit:function(t){var e=[].slice.call(arguments,1),n=((this.e||(this.e={}))[t]||[]).slice(),r=0,o=n.length;for(r;o>r;r++)n[r].fn.apply(n[r].ctx,e);return this},off:function(t,e){var n=this.e||(this.e={}),r=n[t],o=[];if(r&&e)for(var i=0,a=r.length;a>i;i++)r[i].fn!==e&&r[i].fn._!==e&&o.push(r[i]);return o.length?n[t]=o:delete n[t],this}},e.exports=r},{}],8:[function(t,e,n){"use strict";function r(t){return t&&t.__esModule?t:{"default":t}}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}n.__esModule=!0;var i=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),a=t("select"),c=r(a),s=function(){function t(e){o(this,t),this.resolveOptions(e),this.initSelection()}return t.prototype.resolveOptions=function t(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];this.action=e.action,this.emitter=e.emitter,this.target=e.target,this.text=e.text,this.trigger=e.trigger,this.selectedText=""},t.prototype.initSelection=function t(){if(this.text&&this.target)throw new Error('Multiple attributes declared, use either "target" or "text"');if(this.text)this.selectFake();else{if(!this.target)throw new Error('Missing required attributes, use either "target" or "text"');this.selectTarget()}},t.prototype.selectFake=function t(){var e=this;this.removeFake(),this.fakeHandler=document.body.addEventListener("click",function(){return e.removeFake()}),this.fakeElem=document.createElement("textarea"),this.fakeElem.style.position="absolute",this.fakeElem.style.left="-9999px",this.fakeElem.style.top=(window.pageYOffset||document.documentElement.scrollTop)+"px",this.fakeElem.setAttribute("readonly",""),this.fakeElem.value=this.text,document.body.appendChild(this.fakeElem),this.selectedText=c.default(this.fakeElem),this.copyText()},t.prototype.removeFake=function t(){this.fakeHandler&&(document.body.removeEventListener("click"),this.fakeHandler=null),this.fakeElem&&(document.body.removeChild(this.fakeElem),this.fakeElem=null)},t.prototype.selectTarget=function t(){this.selectedText=c.default(this.target),this.copyText()},t.prototype.copyText=function t(){var e=void 0;try{e=document.execCommand(this.action)}catch(n){e=!1}this.handleResult(e)},t.prototype.handleResult=function t(e){e?this.emitter.emit("success",{action:this.action,text:this.selectedText,trigger:this.trigger,clearSelection:this.clearSelection.bind(this)}):this.emitter.emit("error",{action:this.action,trigger:this.trigger,clearSelection:this.clearSelection.bind(this)})},t.prototype.clearSelection=function t(){this.target&&this.target.blur(),window.getSelection().removeAllRanges()},t.prototype.destroy=function t(){this.removeFake()},i(t,[{key:"action",set:function t(){var e=arguments.length<=0||void 0===arguments[0]?"copy":arguments[0];if(this._action=e,"copy"!==this._action&&"cut"!==this._action)throw new Error('Invalid "action" value, use either "copy" or "cut"')},get:function t(){return this._action}},{key:"target",set:function t(e){if(void 0!==e){if(!e||"object"!=typeof e||1!==e.nodeType)throw new Error('Invalid "target" value, use a valid Element');this._target=e}},get:function t(){return this._target}}]),t}();n.default=s,e.exports=n.default},{select:6}],9:[function(t,e,n){"use strict";function r(t){return t&&t.__esModule?t:{"default":t}}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function a(t,e){var n="data-clipboard-"+t;if(e.hasAttribute(n))return e.getAttribute(n)}n.__esModule=!0;var c=t("./clipboard-action"),s=r(c),u=t("tiny-emitter"),l=r(u),f=t("good-listener"),d=r(f),h=function(t){function e(n,r){o(this,e),t.call(this),this.resolveOptions(r),this.listenClick(n)}return i(e,t),e.prototype.resolveOptions=function t(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];this.action="function"==typeof e.action?e.action:this.defaultAction,this.target="function"==typeof e.target?e.target:this.defaultTarget,this.text="function"==typeof e.text?e.text:this.defaultText},e.prototype.listenClick=function t(e){var n=this;this.listener=d.default(e,"click",function(t){return n.onClick(t)})},e.prototype.onClick=function t(e){var n=e.delegateTarget||e.currentTarget;this.clipboardAction&&(this.clipboardAction=null),this.clipboardAction=new s.default({action:this.action(n),target:this.target(n),text:this.text(n),trigger:n,emitter:this})},e.prototype.defaultAction=function t(e){return a("action",e)},e.prototype.defaultTarget=function t(e){var n=a("target",e);return n?document.querySelector(n):void 0},e.prototype.defaultText=function t(e){return a("text",e)},e.prototype.destroy=function t(){this.listener.destroy(),this.clipboardAction&&(this.clipboardAction.destroy(),this.clipboardAction=null)},e}(l.default);n.default=h,e.exports=n.default},{"./clipboard-action":8,"good-listener":5,"tiny-emitter":7}]},{},[9])(9)});<commit_msg>Update clipboard.js to v1.5.9.<commit_after>/*!
 * clipboard.js v1.5.9
 * https://zenorocha.github.io/clipboard.js
 *
 * Licensed MIT © Zeno Rocha
 */
!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,e.Clipboard=t()}}(function(){var t,e,n;return function t(e,n,o){function r(c,s){if(!n[c]){if(!e[c]){var a="function"==typeof require&&require;if(!s&&a)return a(c,!0);if(i)return i(c,!0);var l=new Error("Cannot find module '"+c+"'");throw l.code="MODULE_NOT_FOUND",l}var u=n[c]={exports:{}};e[c][0].call(u.exports,function(t){var n=e[c][1][t];return r(n?n:t)},u,u.exports,t,e,n,o)}return n[c].exports}for(var i="function"==typeof require&&require,c=0;c<o.length;c++)r(o[c]);return r}({1:[function(t,e,n){var o=t("matches-selector");e.exports=function(t,e,n){for(var r=n?t:t.parentNode;r&&r!==document;){if(o(r,e))return r;r=r.parentNode}}},{"matches-selector":5}],2:[function(t,e,n){function o(t,e,n,o,i){var c=r.apply(this,arguments);return t.addEventListener(n,c,i),{destroy:function(){t.removeEventListener(n,c,i)}}}function r(t,e,n,o){return function(n){n.delegateTarget=i(n.target,e,!0),n.delegateTarget&&o.call(t,n)}}var i=t("closest");e.exports=o},{closest:1}],3:[function(t,e,n){n.node=function(t){return void 0!==t&&t instanceof HTMLElement&&1===t.nodeType},n.nodeList=function(t){var e=Object.prototype.toString.call(t);return void 0!==t&&("[object NodeList]"===e||"[object HTMLCollection]"===e)&&"length"in t&&(0===t.length||n.node(t[0]))},n.string=function(t){return"string"==typeof t||t instanceof String},n.fn=function(t){var e=Object.prototype.toString.call(t);return"[object Function]"===e}},{}],4:[function(t,e,n){function o(t,e,n){if(!t&&!e&&!n)throw new Error("Missing required arguments");if(!s.string(e))throw new TypeError("Second argument must be a String");if(!s.fn(n))throw new TypeError("Third argument must be a Function");if(s.node(t))return r(t,e,n);if(s.nodeList(t))return i(t,e,n);if(s.string(t))return c(t,e,n);throw new TypeError("First argument must be a String, HTMLElement, HTMLCollection, or NodeList")}function r(t,e,n){return t.addEventListener(e,n),{destroy:function(){t.removeEventListener(e,n)}}}function i(t,e,n){return Array.prototype.forEach.call(t,function(t){t.addEventListener(e,n)}),{destroy:function(){Array.prototype.forEach.call(t,function(t){t.removeEventListener(e,n)})}}}function c(t,e,n){return a(document.body,t,e,n)}var s=t("./is"),a=t("delegate");e.exports=o},{"./is":3,delegate:2}],5:[function(t,e,n){function o(t,e){if(i)return i.call(t,e);for(var n=t.parentNode.querySelectorAll(e),o=0;o<n.length;++o)if(n[o]==t)return!0;return!1}var r=Element.prototype,i=r.matchesSelector||r.webkitMatchesSelector||r.mozMatchesSelector||r.msMatchesSelector||r.oMatchesSelector;e.exports=o},{}],6:[function(t,e,n){function o(t){var e;if("INPUT"===t.nodeName||"TEXTAREA"===t.nodeName)t.focus(),t.setSelectionRange(0,t.value.length),e=t.value;else{t.hasAttribute("contenteditable")&&t.focus();var n=window.getSelection(),o=document.createRange();o.selectNodeContents(t),n.removeAllRanges(),n.addRange(o),e=n.toString()}return e}e.exports=o},{}],7:[function(t,e,n){function o(){}o.prototype={on:function(t,e,n){var o=this.e||(this.e={});return(o[t]||(o[t]=[])).push({fn:e,ctx:n}),this},once:function(t,e,n){function o(){r.off(t,o),e.apply(n,arguments)}var r=this;return o._=e,this.on(t,o,n)},emit:function(t){var e=[].slice.call(arguments,1),n=((this.e||(this.e={}))[t]||[]).slice(),o=0,r=n.length;for(o;r>o;o++)n[o].fn.apply(n[o].ctx,e);return this},off:function(t,e){var n=this.e||(this.e={}),o=n[t],r=[];if(o&&e)for(var i=0,c=o.length;c>i;i++)o[i].fn!==e&&o[i].fn._!==e&&r.push(o[i]);return r.length?n[t]=r:delete n[t],this}},e.exports=o},{}],8:[function(e,n,o){!function(r,i){if("function"==typeof t&&t.amd)t(["module","select"],i);else if("undefined"!=typeof o)i(n,e("select"));else{var c={exports:{}};i(c,r.select),r.clipboardAction=c.exports}}(this,function(t,e){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var r=n(e),i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol?"symbol":typeof t},c=function(){function t(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}return function(e,n,o){return n&&t(e.prototype,n),o&&t(e,o),e}}(),s=function(){function t(e){o(this,t),this.resolveOptions(e),this.initSelection()}return t.prototype.resolveOptions=function t(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];this.action=e.action,this.emitter=e.emitter,this.target=e.target,this.text=e.text,this.trigger=e.trigger,this.selectedText=""},t.prototype.initSelection=function t(){if(this.text&&this.target)throw new Error('Multiple attributes declared, use either "target" or "text"');if(this.text)this.selectFake();else{if(!this.target)throw new Error('Missing required attributes, use either "target" or "text"');this.selectTarget()}},t.prototype.selectFake=function t(){var e=this,n="rtl"==document.documentElement.getAttribute("dir");this.removeFake(),this.fakeHandler=document.body.addEventListener("click",function(){return e.removeFake()}),this.fakeElem=document.createElement("textarea"),this.fakeElem.style.fontSize="12pt",this.fakeElem.style.border="0",this.fakeElem.style.padding="0",this.fakeElem.style.margin="0",this.fakeElem.style.position="fixed",this.fakeElem.style[n?"right":"left"]="-9999px",this.fakeElem.style.top=(window.pageYOffset||document.documentElement.scrollTop)+"px",this.fakeElem.setAttribute("readonly",""),this.fakeElem.value=this.text,document.body.appendChild(this.fakeElem),this.selectedText=(0,r.default)(this.fakeElem),this.copyText()},t.prototype.removeFake=function t(){this.fakeHandler&&(document.body.removeEventListener("click"),this.fakeHandler=null),this.fakeElem&&(document.body.removeChild(this.fakeElem),this.fakeElem=null)},t.prototype.selectTarget=function t(){this.selectedText=(0,r.default)(this.target),this.copyText()},t.prototype.copyText=function t(){var e=void 0;try{e=document.execCommand(this.action)}catch(n){e=!1}this.handleResult(e)},t.prototype.handleResult=function t(e){e?this.emitter.emit("success",{action:this.action,text:this.selectedText,trigger:this.trigger,clearSelection:this.clearSelection.bind(this)}):this.emitter.emit("error",{action:this.action,trigger:this.trigger,clearSelection:this.clearSelection.bind(this)})},t.prototype.clearSelection=function t(){this.target&&this.target.blur(),window.getSelection().removeAllRanges()},t.prototype.destroy=function t(){this.removeFake()},c(t,[{key:"action",set:function t(){var e=arguments.length<=0||void 0===arguments[0]?"copy":arguments[0];if(this._action=e,"copy"!==this._action&&"cut"!==this._action)throw new Error('Invalid "action" value, use either "copy" or "cut"')},get:function t(){return this._action}},{key:"target",set:function t(e){if(void 0!==e){if(!e||"object"!==("undefined"==typeof e?"undefined":i(e))||1!==e.nodeType)throw new Error('Invalid "target" value, use a valid Element');this._target=e}},get:function t(){return this._target}}]),t}();t.exports=s})},{select:6}],9:[function(e,n,o){!function(r,i){if("function"==typeof t&&t.amd)t(["module","./clipboard-action","tiny-emitter","good-listener"],i);else if("undefined"!=typeof o)i(n,e("./clipboard-action"),e("tiny-emitter"),e("good-listener"));else{var c={exports:{}};i(c,r.clipboardAction,r.tinyEmitter,r.goodListener),r.clipboard=c.exports}}(this,function(t,e,n,o){"use strict";function r(t){return t&&t.__esModule?t:{"default":t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function c(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function a(t,e){var n="data-clipboard-"+t;if(e.hasAttribute(n))return e.getAttribute(n)}var l=r(e),u=r(n),f=r(o),d=function(t){function e(n,o){i(this,e);var r=c(this,t.call(this));return r.resolveOptions(o),r.listenClick(n),r}return s(e,t),e.prototype.resolveOptions=function t(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];this.action="function"==typeof e.action?e.action:this.defaultAction,this.target="function"==typeof e.target?e.target:this.defaultTarget,this.text="function"==typeof e.text?e.text:this.defaultText},e.prototype.listenClick=function t(e){var n=this;this.listener=(0,f.default)(e,"click",function(t){return n.onClick(t)})},e.prototype.onClick=function t(e){var n=e.delegateTarget||e.currentTarget;this.clipboardAction&&(this.clipboardAction=null),this.clipboardAction=new l.default({action:this.action(n),target:this.target(n),text:this.text(n),trigger:n,emitter:this})},e.prototype.defaultAction=function t(e){return a("action",e)},e.prototype.defaultTarget=function t(e){var n=a("target",e);return n?document.querySelector(n):void 0},e.prototype.defaultText=function t(e){return a("text",e)},e.prototype.destroy=function t(){this.listener.destroy(),this.clipboardAction&&(this.clipboardAction.destroy(),this.clipboardAction=null)},e}(u.default);t.exports=d})},{"./clipboard-action":8,"good-listener":4,"tiny-emitter":7}]},{},[9])(9)});<|endoftext|>


<commit_before>// doc({
//     attach_id: "basics/actions",
//     tests: [
//         test("Actions", () => {
//             let navbar = new Component("navbar");

//             navbar.act.ping = (q) => {
//                 return ["pong", q("li").length];
//             }

//             let navbar2 = new Component("navbar2");
//             navbar2.act = {
//                 ping: (q) => { return "pong" },
//                 pong: (q) => { return "ping" }
//             }

//             let navbar3 = new Component("navbar3");
//             navbar3.act.first_ping = (q) => "first_pong";
//             navbar3.act = {
//                 ping: (q) => { return "pong" },
//                 pong: (q) => { return "ping" }
//             }

//             return [
//                 assert("action function responds", navbar.act.ping()[0], "pong"),
//                 assert("action function employs the scoped selector", navbar.act.ping()[1], 2),
//                 assert("actions can be assigned with an entire object", [navbar2.act.ping(), navbar2.act.pong()], ["pong", "ping"]),
//                 assert("single and entire object declaration work gracefully", [
//                     navbar3.act.first_ping(),
//                     navbar3.act.ping(),
//                     navbar3.act.pong()
//                 ], [
//                     "first_pong",
//                     "pong",
//                     "ping"
//                 ])
//             ]
//         }, `
//
//

//
Home

//
Blog

//

//
//     `)
//     ]
// });<commit_msg>More tests<commit_after>import Component from "../../../mozart.js";
let timer = new Component("timer");

timer.get_hello = function() {
    return this.q(".hello").innerHTML;
}

timer.get_element_out_of_scope = function() {
    return this.q(".goodbye");
}

doc({
    attach_id: "basics/element-selection",
    tests: [
        test("Selecting an element", () => {
            return [
                assert("Can select scoped element", timer.get_hello(), "hello world"),
                assert("Does not select element out of scope", timer.get_element_out_of_scope(), undefined),
            ]
        }, `

hello world

You shouldn't see this.

    `)
    ]
});<|endoftext|>


<commit_before>const builder = require('focus').component.builder;
const React = require('react');
const types = require('focus').component.types;
const i18nBehaviour = require('../../i18n/mixin');
const mdlBehaviour = require('../../mixin/mdl-behaviour');
const {uniqueId} = require('lodash/utility');
const InputRadio = require('../../input/radio').component;

const selectRadioMixin = {
    mixins: [i18nBehaviour, mdlBehaviour],
    /**
    * Tag name.
    */
    displayName: 'select-radio',

    /** @inheritdoc */
    getDefaultProps() {
        return {
            values: [],
            valueKey: 'value',
            labelKey: 'label'
        };
    },

    /** @inheritdoc */
    propTypes: {
        values: types('array'),
        value: types(['number', 'string']),
        valueKey: types('string'),
        labelKey: types('string')
    },

    /** @inheritdoc */
    getInitialState() {
        return {
            uniqueName: uniqueId('options_'),
            value: this.props.value
        };
    },

    /** @inheritdoc */
    componentWillReceiveProps (newProps){
        this.setState({
            value: newProps.value
        });
    },

    /**
     * Get the value from the select in the DOM.
     * @return {string, number} selected value
     */
    getValue () {
        return this.state.value;
    },

    /**
    * handle click on radio
    * @param {object} event - the click event
    */
    _handleRadioChange(newValue) {
        console.debug(newValue);
        //Set the state then call the change handler.
        this.setState({value: newValue});
        if(this.props.onChange){
            this.props.onChange(newValue);
        }
    },
    /**
     * Closure to capture key and radio status.
     * @param  {string} key the key of radio
     * @return {func} status closure
     */
    _getRadioChangeHandler(key) {
        return () => {
            this._handleRadioChange(key);
        };
    },
    /**
    * Render radio for each values
    * @return {XML} the different radio values
    */
    renderSelectRadios() {
        const {uniqueName} = this.state;
        return this.props.values.map((val, idx)=>{
            const value = val[this.props.valueKey];
            const label = val[this.props.labelKey];
            const isChecked = value === this.state.value;
            return (
                <InputRadio key={idx} label={this.i18n(label)} name={uniqueName} onChange={this._getRadioChangeHandler(value)} value={isChecked} />
            );
        });
    },
    /** @inheritdoc */
    render() {
        return (

                {this.renderSelectRadios()}

        );
    }
};

module.exports = builder(selectRadioMixin);
<commit_msg>[select-radio] remove console log<commit_after>const builder = require('focus').component.builder;
const React = require('react');
const types = require('focus').component.types;
const i18nBehaviour = require('../../i18n/mixin');
const mdlBehaviour = require('../../mixin/mdl-behaviour');
const {uniqueId} = require('lodash/utility');
const InputRadio = require('../../input/radio').component;

const selectRadioMixin = {
    mixins: [i18nBehaviour, mdlBehaviour],
    /**
    * Tag name.
    */
    displayName: 'select-radio',

    /** @inheritdoc */
    getDefaultProps() {
        return {
            values: [],
            valueKey: 'value',
            labelKey: 'label'
        };
    },

    /** @inheritdoc */
    propTypes: {
        values: types('array'),
        value: types(['number', 'string']),
        valueKey: types('string'),
        labelKey: types('string')
    },

    /** @inheritdoc */
    getInitialState() {
        return {
            uniqueName: uniqueId('options_'),
            value: this.props.value
        };
    },

    /** @inheritdoc */
    componentWillReceiveProps (newProps){
        this.setState({
            value: newProps.value
        });
    },

    /**
     * Get the value from the select in the DOM.
     * @return {string, number} selected value
     */
    getValue () {
        return this.state.value;
    },

    /**
    * handle click on radio
    * @param {object} event - the click event
    */
    _handleRadioChange(newValue) {
        //Set the state then call the change handler.
        this.setState({value: newValue});
        if(this.props.onChange){
            this.props.onChange(newValue);
        }
    },
    /**
     * Closure to capture key and radio status.
     * @param  {string} key the key of radio
     * @return {func} status closure
     */
    _getRadioChangeHandler(key) {
        return () => {
            this._handleRadioChange(key);
        };
    },
    /**
    * Render radio for each values
    * @return {XML} the different radio values
    */
    renderSelectRadios() {
        const {uniqueName} = this.state;
        return this.props.values.map((val, idx)=>{
            const value = val[this.props.valueKey];
            const label = val[this.props.labelKey];
            const isChecked = value === this.state.value;
            return (
                <InputRadio key={idx} label={this.i18n(label)} name={uniqueName} onChange={this._getRadioChangeHandler(value)} value={isChecked} />
            );
        });
    },
    /** @inheritdoc */
    render() {
        return (

                {this.renderSelectRadios()}

        );
    }
};

module.exports = builder(selectRadioMixin);
<|endoftext|>


<commit_before>import runInParallel from './runInParallel';
import pluralize from '../util/pluralize';

const NUM_CONCURRENT_PROCESSES = 4;

/**
 * Run the given command in parallel, showing a progress bar of results.
 *
 * The provided async function should return an object that at least contains
 * a field called "error" that is truthy if there was a problem, but may contain
 * any other fields.
 */
export default async function runWithProgressBar(
    description, files, asyncFn, {runInSeries}={}) {
  let numProcessed = 0;
  let numFailures = 0;
  let numTotal = files.length;
  console.log(description);
  let numConcurrentProcesses = runInSeries ? 1 : NUM_CONCURRENT_PROCESSES;
  let results = await runInParallel(files, asyncFn, numConcurrentProcesses, ({result}) => {
    if (result.error) {
      numFailures++;
    }
    numProcessed++;
    let errorString = numFailures === 0 ? '' : ` (${pluralize(numFailures, 'failure')} so far)`;
    process.stdout.write(`\r${numProcessed}/${numTotal}${errorString}`);
  });
  process.stdout.write('\n');
  return results;
}
<commit_msg>fix: increase the parallelism from 4 to 8 (#57)<commit_after>import runInParallel from './runInParallel';
import pluralize from '../util/pluralize';

const NUM_CONCURRENT_PROCESSES = 8;

/**
 * Run the given command in parallel, showing a progress bar of results.
 *
 * The provided async function should return an object that at least contains
 * a field called "error" that is truthy if there was a problem, but may contain
 * any other fields.
 */
export default async function runWithProgressBar(
    description, files, asyncFn, {runInSeries}={}) {
  let numProcessed = 0;
  let numFailures = 0;
  let numTotal = files.length;
  console.log(description);
  let numConcurrentProcesses = runInSeries ? 1 : NUM_CONCURRENT_PROCESSES;
  let results = await runInParallel(files, asyncFn, numConcurrentProcesses, ({result}) => {
    if (result.error) {
      numFailures++;
    }
    numProcessed++;
    let errorString = numFailures === 0 ? '' : ` (${pluralize(numFailures, 'failure')} so far)`;
    process.stdout.write(`\r${numProcessed}/${numTotal}${errorString}`);
  });
  process.stdout.write('\n');
  return results;
}
<|endoftext|>


<commit_before>import { SETTINGS } from '../consts/types';
import { fetchUser } from './user';
import { fetchNotifs } from './notifs';

const { ipcRenderer } = require('electron');
const settings = require('electron-settings');

/**
 * Sets auto launch at OS startup
 * It sends a message to main process which sets the setting
 *
 * @param {bool} value
 */
const setAutoLaunch = (value) => {
  if (value) {
    ipcRenderer.send('auto-launch', true);
  } else {
    ipcRenderer.send('auto-launch', false);
  }
};
/**
 * Sets the webContents.zoomLevel
 * It sends a message to main process which sets the setting
 *
 * @param {float} value
 */
const setZoomLevel = (value) => {
  ipcRenderer.send('zoom-level', value);
};

/**
 * Saves the current state of the app
 *
 */
const saveUserState = () => (dispatch, getState) => {
  const state = getState();
  const customCols = [...state.columns];
  for (let index = 0; index < customCols.length; index += 1) {
    customCols[index].items = [];
    customCols[index].prev_set = 0;
    customCols[index].page = 0;
  }
  // We don't need to save everything, select the ones that we really need
  const savedState = {
    auth: state.auth,
    user: state.user,
    settings: state.settings,
    notifs: state.notifs,
    columns: customCols,
    search: state.search,
  };
  /**
   * Use localStorage to save the state. Much better than a file.
   * EDIT: I was wrong. LocalStorage is not saved is the app crashes abnormally.
   * so I will be using electron-settings package
   */
  settings.set('currentVersion', savedState);
};

/**
 * If the user wants to minimise the app when quit button is clicked
 *
 * @param {bool} value should minimise on close?
 */
const setMinimiseOnClose = value => (dispatch) => {
  if (value) {
    window.onbeforeunload = (e) => {
      ipcRenderer.send('minimiseApp');
      e.returnValue = false;
    };
  } else {
    window.onbeforeunload = () => {
      dispatch(saveUserState());
    };
  }
};

/**
 * If there is a new update, this sets the appropriate settings
 *
 * @param {bool} value is there a new update?
 */
const setUpdateStatus = value => (dispatch) => {
  if (value) {
    dispatch({
      type: SETTINGS.ACTION.CHANGE_GENERAL,
      primaryKey: 'update',
      buttonText: 'Update availble',
      value: true,
    });

    // const notification = new Notification('devRantron', {
    //   body: 'New update is availble',
    //   icon: 'http://i.imgur.com/iikd00P.png',
    //   requireInteraction: true,
    // });

    // let plat = '';

    // if (/^win/.test(process.platform)) { plat = 'windows'; }
    // if (/^dar/.test(process.platform)) { plat = 'osx'; }
    // if (/^lin/.test(process.platform)) { plat = 'linux'; }

    // if (plat === 'windows') {
    //   notification.onclick = () => {
    //     ipcRenderer.send('updateNow', true);
    //   };
    // } else {

    // }
  } else {
    dispatch({
      type: SETTINGS.ACTION.CHANGE_GENERAL,
      primaryKey: '',
      buttonText: 'Up to date',
      value: false,
    });
  }
};

/**
 * If the app has been launched for the first time, set some default settings
 *
 */
const setFirstLaunch = () => (dispatch) => {
  setAutoLaunch(true);
  dispatch(setMinimiseOnClose(true));
};

/**
 * Sets some settings according to saved user state on app startup
 * Auto launch and minimiseOnClose has to be set everytime the app starts up
 *
 */
const setOnStartup = () => (dispatch, getState) => {
  dispatch(fetchUser());
  dispatch(fetchNotifs());
  const generalSettings = getState().settings.general;
  if (generalSettings.autoLaunch.value === true) {
    setAutoLaunch(true);
  } else {
    setAutoLaunch(false);
  }
  if (generalSettings.minimiseOnClose.value === true) {
    dispatch(setMinimiseOnClose(true));
  } else {
    dispatch(setMinimiseOnClose(false));
  }
  if (generalSettings.zoomLevel.value !== 0) {
    setZoomLevel(generalSettings.zoomLevel.value);
  }
};

/**
 * Logs in the user
 *
 * @param {string} username Either username or email
 * @param {string} password Password for the user
 */
const changeGeneral = (primaryKey, secondaryKey, value) => (dispatch) => {
  if (primaryKey === 'autoLaunch') {
    setAutoLaunch(value);
  }
  if (primaryKey === 'zoomLevel') {
    setZoomLevel(value);
  }
  if (primaryKey === 'minimiseOnClose') {
    dispatch(setMinimiseOnClose(value));
  }
  if (primaryKey === 'update') {
    dispatch(saveUserState());
    ipcRenderer.send('updateNow', true);
  }
  if (primaryKey === 'reset_cache') {
    settings.deleteAll();
    ipcRenderer.send('reLaunch', true);
    return;
  }
  dispatch({
    type: SETTINGS.ACTION.CHANGE_GENERAL,
    primaryKey,
    secondaryKey,
    value,
  });
};

/**
 * We will use this for theming in future
 *
 */
const changeTheme = () => () => {

};

export {
  changeGeneral,
  changeTheme,
  setAutoLaunch,
  saveUserState,
  setFirstLaunch,
  setOnStartup,
  setUpdateStatus };
<commit_msg>Added notification for updates<commit_after>import { SETTINGS, ITEM } from '../consts/types';
import { fetchUser } from './user';
import { fetchNotifs } from './notifs';
import { openModal } from './modal';

const { ipcRenderer } = require('electron');
const settings = require('electron-settings');

/**
 * Sets auto launch at OS startup
 * It sends a message to main process which sets the setting
 *
 * @param {bool} value
 */
const setAutoLaunch = (value) => {
  if (value) {
    ipcRenderer.send('auto-launch', true);
  } else {
    ipcRenderer.send('auto-launch', false);
  }
};
/**
 * Sets the webContents.zoomLevel
 * It sends a message to main process which sets the setting
 *
 * @param {float} value
 */
const setZoomLevel = (value) => {
  ipcRenderer.send('zoom-level', value);
};

/**
 * Saves the current state of the app
 *
 */
const saveUserState = () => (dispatch, getState) => {
  const state = getState();
  const customCols = [...state.columns];
  for (let index = 0; index < customCols.length; index += 1) {
    customCols[index].items = [];
    customCols[index].prev_set = 0;
    customCols[index].page = 0;
  }
  // We don't need to save everything, select the ones that we really need
  const savedState = {
    auth: state.auth,
    user: state.user,
    settings: state.settings,
    notifs: state.notifs,
    columns: customCols,
    search: state.search,
  };
  /**
   * Use localStorage to save the state. Much better than a file.
   * EDIT: I was wrong. LocalStorage is not saved is the app crashes abnormally.
   * so I will be using electron-settings package
   */
  settings.set('currentVersion', savedState);
};

/**
 * If the user wants to minimise the app when quit button is clicked
 *
 * @param {bool} value should minimise on close?
 */
const setMinimiseOnClose = value => (dispatch) => {
  if (value) {
    window.onbeforeunload = (e) => {
      ipcRenderer.send('minimiseApp');
      e.returnValue = false;
    };
  } else {
    window.onbeforeunload = () => {
      dispatch(saveUserState());
    };
  }
};

/**
 * If there is a new update, this sets the appropriate settings
 *
 * @param {bool} value is there a new update?
 */
const setUpdateStatus = value => (dispatch) => {
  if (value) {
    dispatch({
      type: SETTINGS.ACTION.CHANGE_GENERAL,
      primaryKey: 'update',
      buttonText: 'Update availble',
      value: true,
    });

    const notification = new Notification('devRantron', {
      body: 'New update is availble',
      icon: 'http://i.imgur.com/iikd00P.png',
      requireInteraction: true,
    });

    notification.onclick = () => {
      dispatch(openModal(ITEM.RELEASE_INFO.NAME));
    };
  } else {
    dispatch({
      type: SETTINGS.ACTION.CHANGE_GENERAL,
      primaryKey: '',
      buttonText: 'Up to date',
      value: false,
    });
  }
};

/**
 * If the app has been launched for the first time, set some default settings
 *
 */
const setFirstLaunch = () => (dispatch) => {
  setAutoLaunch(true);
  dispatch(setMinimiseOnClose(true));
};

/**
 * Sets some settings according to saved user state on app startup
 * Auto launch and minimiseOnClose has to be set everytime the app starts up
 *
 */
const setOnStartup = () => (dispatch, getState) => {
  dispatch(fetchUser());
  dispatch(fetchNotifs());
  const generalSettings = getState().settings.general;
  if (generalSettings.autoLaunch.value === true) {
    setAutoLaunch(true);
  } else {
    setAutoLaunch(false);
  }
  if (generalSettings.minimiseOnClose.value === true) {
    dispatch(setMinimiseOnClose(true));
  } else {
    dispatch(setMinimiseOnClose(false));
  }
  if (generalSettings.zoomLevel.value !== 0) {
    setZoomLevel(generalSettings.zoomLevel.value);
  }
};

/**
 * Logs in the user
 *
 * @param {string} username Either username or email
 * @param {string} password Password for the user
 */
const changeGeneral = (primaryKey, secondaryKey, value) => (dispatch) => {
  if (primaryKey === 'autoLaunch') {
    setAutoLaunch(value);
  }
  if (primaryKey === 'zoomLevel') {
    setZoomLevel(value);
  }
  if (primaryKey === 'minimiseOnClose') {
    dispatch(setMinimiseOnClose(value));
  }
  if (primaryKey === 'update') {
    dispatch(saveUserState());
    ipcRenderer.send('updateNow', true);
  }
  if (primaryKey === 'reset_cache') {
    settings.deleteAll();
    ipcRenderer.send('reLaunch', true);
    return;
  }
  dispatch({
    type: SETTINGS.ACTION.CHANGE_GENERAL,
    primaryKey,
    secondaryKey,
    value,
  });
};

/**
 * We will use this for theming in future
 *
 */
const changeTheme = () => () => {

};

export {
  changeGeneral,
  changeTheme,
  setAutoLaunch,
  saveUserState,
  setFirstLaunch,
  setOnStartup,
  setUpdateStatus };
<|endoftext|>


<commit_before>/**
 * jquery.dialog.js 1.0
 * http://jquerywidget.com
 */
;(function (factory) {
    if (typeof define === "function" && (define.amd || define.cmd) && typeof jQuery == 'undefined'){
        // AMD或CMD
        define(['jquery'],function(){
            factory(jQuery);
            return jQuery;
        });
    } else if (typeof module === 'object' && module.exports) {
        // Node/CommonJS
        module.exports = function( root, jQuery ) {
            if ( jQuery === undefined ) {
                if ( typeof window !== 'undefined' ) {
                    jQuery = require('jquery');
                } else {
                    jQuery = require('jquery')(root);
                }
            }
            factory(jQuery);
            return jQuery;
        };
    } else {
        //Browser globals
        factory(jQuery);
    }
}(function ($) {
	$.fn.dialog = function(parameter,getApi) {
		if(typeof parameter == 'function'){ //重载
			getApi = parameter;
			parameter = {};
		}else{
			parameter = parameter || {};
			getApi = getApi||function(){};
		}
		var defaults = {
			prefix:'widget',
			content:'',
			title:'',
			backgroundColor:'#000',
			opacity: 0.5,
			autoOpen:false,
			isModel:true,
			buttons:{},
			beforeOpen:function(){},
			afterClose:function(){}
		};
		var options = $.extend({}, defaults, parameter);
		var $window = $(window);
		var $body = $("body");
		var isIE6 = navigator.appVersion.indexOf("MSIE 6") > -1; //IE6
		return this.each(function() {
			//全局变量
			var $this = $(this);
			var $children = options.content?$(options.content):$this.html(); //内容区域
			var $container = $('

');
			var $overlay = $();
			var $close = $('x');
			var $title = $('
'+options.title+'
');
			var $wg_head = $('

').append($title).append($close);
			var $wg_body = $('

').append($children);
			var $wg_foot = $('

');
			var _api = {};  //对外接口
			var _position = isIE6?'absolute':'fixed';
			var _isOpen = false; //是否是打开状态
			//结构修改
			$this.appendTo($body).empty();
			if(options.isModel){
				$overlay = $('

').css({
					'position': _position,
					'z-index': '998',
					'top': '0px',
					'left': '0px',
					'height': '100%',
					'width': '100%',
					'background': options.backgroundColor,
					'display': 'none'
				}).appendTo($this);
			}
			$container.css({
				'display':'none',
				'position':_position,
				'z-index': '999'
			}).appendTo($this).append($wg_head).append($wg_body).append($wg_foot);
			var i = 1;
			for(var name in options.buttons){
				(function(name){
					$('<button class="button-'+(i++)+'" type="button">'+name+'</button>').appendTo($wg_foot).click(function(){
						options.buttons[name](_api);
					});
				})(name);
			}
			//对话框开启
			_api.open = function(callback){
				if(options.beforeOpen(this)!=false){
					(callback || function(){})(); //如果open的时候传入了方法，则在执行时进行预处理
					$this.show();
					if(options.isModel){
						$overlay.css({
							'opacity': 0
						}).stop().fadeTo(200,options.opacity);
					}
					$container.css("opacity",0).fadeTo(200, 1);
					_api.resize();
					_isOpen = true;
				}
			};
			//对话框关闭
			_api.close = function(){
				$container.stop().fadeTo(200, 0);
				if(options.isModel){
					$overlay.stop().fadeOut(200,function(){
						$this.hide();
					});
				}else{
					$this.hide();
				}
				_isOpen = false;
				options.afterClose(this);
			};
			//对话框形状自动调整
			_api.resize = function(){
				$container.css({
					"left": ($window.width()-$container.outerWidth())/2 + "px",
					"top": ($window.height()-$container.outerHeight())/2 + "px"
				});
			};
			//设置标题
			_api.setTitle = function(title){
				$title.text(title);
			};
			//设置对话框内容
			_api.setContent = function(html){
				$wg_body.html(html);
			};
			//获取按键对象
			_api.getButtons = function(){
				return $wg_foot;
			};
			_api.isOpen = function(){
				return _isOpen;
			};
			//事件绑定
			if(options.autoOpen){
				_api.open();
			}
			$close.click(_api.close);
			$overlay.click(_api.close);
			$window.resize(_api.resize);
			getApi(_api);
		});
	};
}));
<commit_msg>updated 添加顶部位置<commit_after>/**
 * jquery.dialog.js 1.0
 * http://jquerywidget.com
 */
;(function (factory) {
    if (typeof define === "function" && (define.amd || define.cmd) && typeof jQuery == 'undefined'){
        // AMD或CMD
        define(['jquery'],function(){
            factory(jQuery);
            return jQuery;
        });
    } else if (typeof module === 'object' && module.exports) {
        // Node/CommonJS
        module.exports = function( root, jQuery ) {
            if ( jQuery === undefined ) {
                if ( typeof window !== 'undefined' ) {
                    jQuery = require('jquery');
                } else {
                    jQuery = require('jquery')(root);
                }
            }
            factory(jQuery);
            return jQuery;
        };
    } else {
        //Browser globals
        factory(jQuery);
    }
}(function ($) {
	$.fn.dialog = function(parameter,getApi) {
		if(typeof parameter == 'function'){ //重载
			getApi = parameter;
			parameter = {};
		}else{
			parameter = parameter || {};
			getApi = getApi||function(){};
		}
		var defaults = {
			prefix:'widget',
			content:'',
			title:'',
			top:null,
			backgroundColor:'#000',
			opacity: 0.5,
			autoOpen:false,
			isModel:true,
			buttons:{},
			beforeOpen:function(){},
			afterClose:function(){}
		};
		var options = $.extend({}, defaults, parameter);
		var $window = $(window);
		var $body = $("body");
		var isIE6 = navigator.appVersion.indexOf("MSIE 6") > -1; //IE6
		return this.each(function() {
			//全局变量
			var $this = $(this);
			var $children = options.content?$(options.content):$this.html(); //内容区域
			var $container = $('

');
			var $overlay = $();
			var $close = $('x');
			var $title = $('
'+options.title+'
');
			var $wg_head = $('

').append($title).append($close);
			var $wg_body = $('

').append($children);
			var $wg_foot = $('

');
			var _api = {};  //对外接口
			var _position = isIE6?'absolute':'fixed';
			var _isOpen = false; //是否是打开状态
			//结构修改
			$this.appendTo($body).empty();
			if(options.isModel){
				$overlay = $('

').css({
					'position': _position,
					'z-index': '998',
					'top': '0px',
					'left': '0px',
					'height': '100%',
					'width': '100%',
					'background': options.backgroundColor,
					'display': 'none'
				}).appendTo($this);
			}
			$container.css({
				'display':'none',
				'position':_position,
				'z-index': '999'
			}).appendTo($this).append($wg_head).append($wg_body).append($wg_foot);
			var i = 1;
			for(var name in options.buttons){
				(function(name){
					$('<button class="button-'+(i++)+'" type="button">'+name+'</button>').appendTo($wg_foot).click(function(){
						options.buttons[name](_api);
					});
				})(name);
			}
			//对话框开启
			_api.open = function(callback){
				if(options.beforeOpen(this)!=false){
					(callback || function(){})(); //如果open的时候传入了方法，则在执行时进行预处理
					$this.show();
					if(options.isModel){
						$overlay.css({
							'opacity': 0
						}).stop().fadeTo(200,options.opacity);
					}
					$container.css("opacity",0).fadeTo(200, 1);
					_api.resize();
					_isOpen = true;
				}
			};
			//对话框关闭
			_api.close = function(){
				$container.stop().fadeTo(200, 0);
				if(options.isModel){
					$overlay.stop().fadeOut(200,function(){
						$this.hide();
					});
				}else{
					$this.hide();
				}
				_isOpen = false;
				options.afterClose(this);
			};
			//对话框形状自动调整
			_api.resize = function(){
				if(options.top!=null){
					$container.css({
						"left": ($window.width()-$container.outerWidth())/2 + "px",
						"top": options.top + "px"
					});
				}else{
					$container.css({
						"left": ($window.width()-$container.outerWidth())/2 + "px",
						"top": ($window.height()-$container.outerHeight())/2 + "px"
					});
				}
			};
			//设置标题
			_api.setTitle = function(title){
				$title.text(title);
			};
			//设置对话框内容
			_api.setContent = function(html){
				$wg_body.html(html);
			};
			//获取按键对象
			_api.getButtons = function(){
				return $wg_foot;
			};
			_api.isOpen = function(){
				return _isOpen;
			};
			//事件绑定
			if(options.autoOpen){
				_api.open();
			}
			$close.click(_api.close);
			$overlay.click(_api.close);
			$window.resize(_api.resize);
			getApi(_api);
		});
	};
}));
<|endoftext|>


<commit_before>/*
 * ! ${copyright}
 */

// Provides control sap.m.QuickView.
sap.ui.define([
	'jquery.sap.global', './library', 'sap/ui/core/Control', 'sap/ui/core/IconPool',
		'./QuickViewBase', './ResponsivePopover', './NavContainer',
		'./PlacementType', './Page', './Bar', './Button'],
	function(jQuery, library, Control, IconPool,
			QuickViewBase, ResponsivePopover, NavContainer,
			PlacementType, Page, Bar, Button) {
	"use strict";

	/**
	 * Constructor for a new QuickView.
	 *
	 * @param {string} [sId] ID for the new control, generated automatically if no ID is given
	 * @param {object} [mSettings] Initial settings for the new control
	 *
	 * @class The QuickView control renders a responsive popover (sap.m.Popover or sap.m.Dialog)
	 * and displays information of an object in a business-card format. It also allows this object to be linked to
	 * another object using one of the links in the responsive popover. Clicking that link updates the information in the
	 * popover with the data of the linked object. Unlimited number of objects can be linked.
	 *
	 * @extends sap.m.QuickViewBase
	 *
	 * @author SAP SE
	 * @version ${version}
	 *
	 * @constructor
	 * @public
	 * @since 1.28.11
	 * @alias sap.m.QuickView
	 * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
	 */
	var QuickView = QuickViewBase.extend("sap.m.QuickView", /** @lends sap.m.QuickView.prototype */	{
				metadata: {

					library: "sap.m",
					properties: {
						/**
						 * This property is reused from sap.m.Popover and only takes effect when running on desktop or tablet. Please refer the documentation of the placement property of sap.m.Popover.
						 */
						placement : {
							type : "sap.m.PlacementType",
							group : "Misc",
							defaultValue : PlacementType.Right
						},
						/**
						 * The width of the QuickView. The property takes effect only when running on desktop or tablet.
						 */
						width : {
							type : 'sap.ui.core.CSSSize',
							group : 'Dimension',
							defaultValue : '320px'
						}
					},
					aggregations: {
					},
					events: {
						/**
						 * This event fires after the QuickView is opened.
						 */
						afterOpen: {
							parameters: {
								/**
								 * This parameter refers to the control, which opens the QuickView.
								 */
								openBy: {
									type: "sap.ui.core.Control"
								}
							}
						},

						/**
						 * This event fires after the QuickView is closed.
						 */
						afterClose: {
							parameters: {
								/**
								 * This parameter refers to the control, which opens the QuickView.
								 */
								openBy: {
									type: "sap.ui.core.Control"
								},

								/**
								 * This parameter contains the control,
								 * which triggers the close of the QuickView.
								 * It is undefined when running on desktop or tablet.
								 */
								origin : {
									type : "sap.m.Button"
								}
							}
						},

						/**
						 * This event fires before the QuickView is opened.
						 */
						beforeOpen: {
							parameters: {
								/**
								 * This parameter refers to the control, which opens the QuickView.
								 */
								openBy: {
									type: "sap.ui.core.Control"
								}
							}
						},

						/**
						 * This event fires before the QuickView is closed.
						 */
						beforeClose: {
							parameters: {
								/**
								 * This parameter refers to the control, which opens the QuickView.
								 */
								openBy: {
									type: "sap.ui.core.Control"
								},

								/**
								 * This parameter contains the control,
								 * which triggers the close of the QuickView.
								 * It is undefined when running on desktop or tablet.
								 */
								origin : {
									type : "sap.m.Button"
								}
							}
						}
					}
				}
			});

	/**
	 * Initialize the control.
	 *
	 * @private
	 */
	QuickView.prototype.init = function() {

		var oNavConfig = {
			pages: [new Page()],
			navigate: this._navigate.bind(this),
			afterNavigate: this._afterNavigate.bind(this)
		};

		if (!sap.ui.Device.system.phone) {
			oNavConfig.width = this.getWidth();
		}

		this._oNavContainer = new NavContainer(oNavConfig);

		var that = this;

		this._oPopover = new ResponsivePopover(this.getId() + '-quickView', {
			placement: this.getPlacement(),
			content: [this._oNavContainer],
			showHeader: false,
			showCloseButton : false,
			afterOpen: function (oEvent) {
				that._afterOpen(oEvent);
				that.fireAfterOpen({
					openBy: oEvent.getParameter("openBy")
				});
			},
			afterClose: function (oEvent) {
				that.fireAfterClose({
					openBy: oEvent.getParameter("openBy"),
					origin: that.getCloseButton()
				});
			},
			beforeOpen: function (oEvent) {
				that.fireBeforeOpen({
					openBy: oEvent.getParameter("openBy")
				});
			},
			beforeClose: function (oEvent) {
				that.fireBeforeClose({
					openBy: oEvent.getParameter("openBy"),
					origin: that.getCloseButton()
				});
			}
		});

		this._oPopover.addStyleClass('sapMQuickView');

		var oPopupControl = this._oPopover.getAggregation("_popup");
		oPopupControl.addEventDelegate({
			onBeforeRendering: this.onBeforeRenderingPopover,
			onkeydown: this._onPopupKeyDown
		}, this);

		var that = this;
		var fnSetArrowPosition = oPopupControl._fnAdjustPositionAndArrow;

		if (fnSetArrowPosition) {
			oPopupControl._fnAdjustPositionAndArrow = function () {
				fnSetArrowPosition.apply(oPopupControl, arguments);

				that._adjustContainerHeight();
			};
		}

		this._bItemsChanged = true;

		this._oPopover.addStyleClass("sapMQuickView");
	};

	QuickView.prototype.onBeforeRenderingPopover = function() {

		this._bRendered = true;

		// Update pages only if items aggregation is changed
		if (this._bItemsChanged) {
			this._initPages();

			// add a close button on phone devices when there are no pages
			var aPages = this.getAggregation("pages");
			if (!aPages && sap.ui.Device.system.phone) {
				this._addEmptyPage();
			}

			this._bItemsChanged = false;
		}
	};

	QuickView.prototype.exit = function() {

		this._bRendered = false;
		this._bItemsChanged = true;

		if (this._oPopover) {
			this._oPopover.destroy();
		}
	};

	/**
	 * Creates a new {@link sap.m.Page} that can be inserted in a QuickView.
	 * @param {sap.m.QuickViewPage} oQuickViewPage The object that contains the data to be displayed.
	 * @returns {sap.m.Page} The created page
	 * @private
	 */
	QuickView.prototype._createPage = function(oQuickViewPage) {
		return oQuickViewPage._createPage();
	};

	/**
	 * Keyboard handling function when the down arrow is pressed.
	 * @param {sap.ui.base.Event} oEvent The event object for this event.
	 * @private
	 */
	QuickView.prototype._onPopupKeyDown = function(oEvent) {
		this._processKeyboard(oEvent);
	};

	/**
	 * Helper function to restore the focus to the proper element after the QuickView is opened on phone.
	 * @private
	 */
	QuickView.prototype._afterOpen = function(oEvent) {
		if (sap.ui.Device.system.phone) {
			this._restoreFocus();
		}
	};

	/**
	 * Creates a new empty {@link sap.m.Page} and adds it to the QuickView.
	 * @private
	 */
	QuickView.prototype._addEmptyPage = function() {
		var oPage = new Page({
			customHeader : new Bar().addStyleClass("sapMQuickViewHeader")
		});

		var that = this;

		var oCustomHeader = oPage.getCustomHeader();
		oCustomHeader.addContentRight(
			new Button({
				icon : IconPool.getIconURI("decline"),
				press : function() {
					that._oPopover.close();
				}
			})
		);

		oPage.addStyleClass('sapMQuickViewPage');
		this._oNavContainer.addPage(oPage);
	};

	/**
	 * Adjusts the popup height based on the QuickView's content.
	 * @private
	 */
	QuickView.prototype._adjustContainerHeight = function() {
		var oPopupControl = this._oPopover.getAggregation("_popup");
		var $container = oPopupControl.$().find('.sapMPopoverCont');

		if ($container[0] && !$container[0].style.height) {
			$container[0].style.height = $container.height() + 'px';
		}
	};

	/**
	 * Returns the button, which closes the QuickView.
	 * On desktop or tablet, this method returns undefined.
	 * @returns {sap.ui.core.Control} The close button of the QuickView on phone or undefined on desktop and tablet.
	 * @private
	 */
	QuickView.prototype.getCloseButton = function() {
		if (!sap.ui.Device.system.phone) {
			return undefined;
		}

		var oPage = this._oNavContainer.getCurrentPage();
		var oButton = oPage.getCustomHeader().getContentRight()[0];

		return oButton;
	};

	/**
	 * The method sets placement position of the QuickView.
	 *
	 * @param {sap.m.PlacementType} sPlacement The side from which the QuickView appears relative to the control that opens it.
	 * @returns {sap.m.QuickView} Pointer to the control instance for chaining.
	 * @public
	 */
	QuickView.prototype.setPlacement = function (sPlacement) {
		this.setProperty("placement", sPlacement, true); // no re-rendering
		this._oPopover.setPlacement(sPlacement);

		return this;
	};

	/**
	 * The method sets the width of the QuickView.
	 * Works only on desktop or tablet.
	 * @param {sap.ui.core.CSSSize} sWidth The new width of the QuickView.
	 * @returns {sap.m.QuickView} Pointer to the control instance for chaining
	 * @public
	 */
	QuickView.prototype.setWidth = function (sWidth) {
		if (this._oNavContainer) {
			this._oNavContainer.setWidth(sWidth);
			this.setProperty('width', sWidth, true);
		}

		return this;
	};

	/**
	 * Opens the QuickView.
	 * @param {sap.ui.core.Control} oControl The control which opens the QuickView.
	 * @returns {sap.m.QuickView} Pointer to the control instance for chaining
	 * @public
	 */
	QuickView.prototype.openBy = function(oControl) {
		this._oPopover.openBy(oControl);

		return this;
	};

	["addStyleClass", "removeStyleClass", "toggleStyleClass", "hasStyleClass"].forEach(function(sName){
		QuickView.prototype[sName] = function() {
			if (this._oPopover && this._oPopover[sName]) {
				var res = this._oPopover[sName].apply(this._oPopover, arguments);
				return res === this._oPopover ? this : res;
			}
		};
	});

	["setModel", "bindAggregation", "setAggregation", "insertAggregation", "addAggregation",
		"removeAggregation", "removeAllAggregation", "destroyAggregation"].forEach(function (sFuncName) {
			QuickView.prototype["_" + sFuncName + "Old"] = QuickView.prototype[sFuncName];
			QuickView.prototype[sFuncName] = function () {
				var result = QuickView.prototype["_" + sFuncName + "Old"].apply(this, arguments);

				// Marks items aggregation as changed and invalidate popover to trigger rendering
				this._bItemsChanged = true;

				if (this._bRendered && this._oPopover) {
					this._oPopover.invalidate();
				}

				if (["removeAggregation", "removeAllAggregation"].indexOf(sFuncName) !== -1) {
					return result;
				}

				return this;
			};
		});

	return QuickView;

}, /* bExport= */true);
<commit_msg>[INTERNAL] sap.m.QuickView: Inherited properties issue solved<commit_after>/*
 * ! ${copyright}
 */

// Provides control sap.m.QuickView.
sap.ui.define([
	'jquery.sap.global', './library', 'sap/ui/core/Control', 'sap/ui/core/IconPool',
		'./QuickViewBase', './ResponsivePopover', './NavContainer',
		'./PlacementType', './Page', './Bar', './Button'],
	function(jQuery, library, Control, IconPool,
			QuickViewBase, ResponsivePopover, NavContainer,
			PlacementType, Page, Bar, Button) {
	"use strict";

	/**
	 * Constructor for a new QuickView.
	 *
	 * @param {string} [sId] ID for the new control, generated automatically if no ID is given
	 * @param {object} [mSettings] Initial settings for the new control
	 *
	 * @class The QuickView control renders a responsive popover (sap.m.Popover or sap.m.Dialog)
	 * and displays information of an object in a business-card format. It also allows this object to be linked to
	 * another object using one of the links in the responsive popover. Clicking that link updates the information in the
	 * popover with the data of the linked object. Unlimited number of objects can be linked.
	 *
	 * @extends sap.m.QuickViewBase
	 *
	 * @author SAP SE
	 * @version ${version}
	 *
	 * @constructor
	 * @public
	 * @since 1.28.11
	 * @alias sap.m.QuickView
	 * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
	 */
	var QuickView = QuickViewBase.extend("sap.m.QuickView", /** @lends sap.m.QuickView.prototype */	{
				metadata: {

					library: "sap.m",
					properties: {
						/**
						 * This property is reused from sap.m.Popover and only takes effect when running on desktop or tablet. Please refer the documentation of the placement property of sap.m.Popover.
						 */
						placement : {
							type : "sap.m.PlacementType",
							group : "Misc",
							defaultValue : PlacementType.Right
						},
						/**
						 * The width of the QuickView. The property takes effect only when running on desktop or tablet.
						 */
						width : {
							type : 'sap.ui.core.CSSSize',
							group : 'Dimension',
							defaultValue : '320px'
						}
					},
					aggregations: {
					},
					events: {
						/**
						 * This event fires after the QuickView is opened.
						 */
						afterOpen: {
							parameters: {
								/**
								 * This parameter refers to the control, which opens the QuickView.
								 */
								openBy: {
									type: "sap.ui.core.Control"
								}
							}
						},

						/**
						 * This event fires after the QuickView is closed.
						 */
						afterClose: {
							parameters: {
								/**
								 * This parameter refers to the control, which opens the QuickView.
								 */
								openBy: {
									type: "sap.ui.core.Control"
								},

								/**
								 * This parameter contains the control,
								 * which triggers the close of the QuickView.
								 * It is undefined when running on desktop or tablet.
								 */
								origin : {
									type : "sap.m.Button"
								}
							}
						},

						/**
						 * This event fires before the QuickView is opened.
						 */
						beforeOpen: {
							parameters: {
								/**
								 * This parameter refers to the control, which opens the QuickView.
								 */
								openBy: {
									type: "sap.ui.core.Control"
								}
							}
						},

						/**
						 * This event fires before the QuickView is closed.
						 */
						beforeClose: {
							parameters: {
								/**
								 * This parameter refers to the control, which opens the QuickView.
								 */
								openBy: {
									type: "sap.ui.core.Control"
								},

								/**
								 * This parameter contains the control,
								 * which triggers the close of the QuickView.
								 * It is undefined when running on desktop or tablet.
								 */
								origin : {
									type : "sap.m.Button"
								}
							}
						}
					}
				}
			});

	/**
	 * Initialize the control.
	 *
	 * @private
	 */
	QuickView.prototype.init = function() {

		var oNavConfig = {
			pages: [new Page()],
			navigate: this._navigate.bind(this),
			afterNavigate: this._afterNavigate.bind(this)
		};

		if (!sap.ui.Device.system.phone) {
			oNavConfig.width = this.getWidth();
		}

		this._oNavContainer = new NavContainer(oNavConfig);

		var that = this;

		this._oPopover = new ResponsivePopover(this.getId() + '-quickView', {
			placement: this.getPlacement(),
			content: [this._oNavContainer],
			showHeader: false,
			showCloseButton : false,
			afterOpen: function (oEvent) {
				that._afterOpen(oEvent);
				that.fireAfterOpen({
					openBy: oEvent.getParameter("openBy")
				});
			},
			afterClose: function (oEvent) {
				that.fireAfterClose({
					openBy: oEvent.getParameter("openBy"),
					origin: that.getCloseButton()
				});
			},
			beforeOpen: function (oEvent) {
				that.fireBeforeOpen({
					openBy: oEvent.getParameter("openBy")
				});
			},
			beforeClose: function (oEvent) {
				that.fireBeforeClose({
					openBy: oEvent.getParameter("openBy"),
					origin: that.getCloseButton()
				});
			}
		});

		this._oPopover.addStyleClass('sapMQuickView');

		var oPopupControl = this._oPopover.getAggregation("_popup");
		oPopupControl.addEventDelegate({
			onBeforeRendering: this.onBeforeRenderingPopover,
			onkeydown: this._onPopupKeyDown
		}, this);

		var that = this;
		var fnSetArrowPosition = oPopupControl._fnAdjustPositionAndArrow;

		if (fnSetArrowPosition) {
			oPopupControl._fnAdjustPositionAndArrow = function () {
				fnSetArrowPosition.apply(oPopupControl, arguments);

				that._adjustContainerHeight();
			};
		}

		this._bItemsChanged = true;

		this._oPopover.addStyleClass("sapMQuickView");
	};

	QuickView.prototype.onBeforeRenderingPopover = function() {

		this._bRendered = true;

		// Update pages only if items aggregation is changed
		if (this._bItemsChanged) {
			this._initPages();

			// add a close button on phone devices when there are no pages
			var aPages = this.getAggregation("pages");
			if (!aPages && sap.ui.Device.system.phone) {
				this._addEmptyPage();
			}

			this._bItemsChanged = false;
		}
	};

	QuickView.prototype.exit = function() {

		this._bRendered = false;
		this._bItemsChanged = true;

		if (this._oPopover) {
			this._oPopover.destroy();
		}
	};

	/**
	 * Creates a new {@link sap.m.Page} that can be inserted in a QuickView.
	 * @param {sap.m.QuickViewPage} oQuickViewPage The object that contains the data to be displayed.
	 * @returns {sap.m.Page} The created page
	 * @private
	 */
	QuickView.prototype._createPage = function(oQuickViewPage) {
		return oQuickViewPage._createPage();
	};

	/**
	 * Keyboard handling function when the down arrow is pressed.
	 * @param {sap.ui.base.Event} oEvent The event object for this event.
	 * @private
	 */
	QuickView.prototype._onPopupKeyDown = function(oEvent) {
		this._processKeyboard(oEvent);
	};

	/**
	 * Helper function to restore the focus to the proper element after the QuickView is opened on phone.
	 * @private
	 */
	QuickView.prototype._afterOpen = function(oEvent) {
		if (sap.ui.Device.system.phone) {
			this._restoreFocus();
		}
	};

	/**
	 * Creates a new empty {@link sap.m.Page} and adds it to the QuickView.
	 * @private
	 */
	QuickView.prototype._addEmptyPage = function() {
		var oPage = new Page({
			customHeader : new Bar().addStyleClass("sapMQuickViewHeader")
		});

		var that = this;

		var oCustomHeader = oPage.getCustomHeader();
		oCustomHeader.addContentRight(
			new Button({
				icon : IconPool.getIconURI("decline"),
				press : function() {
					that._oPopover.close();
				}
			})
		);

		oPage.addStyleClass('sapMQuickViewPage');
		this._oNavContainer.addPage(oPage);
	};

	/**
	 * Adjusts the popup height based on the QuickView's content.
	 * @private
	 */
	QuickView.prototype._adjustContainerHeight = function() {
		var oPopupControl = this._oPopover.getAggregation("_popup");
		var $container = oPopupControl.$().find('.sapMPopoverCont');

		if ($container[0] && !$container[0].style.height) {
			$container[0].style.height = $container.height() + 'px';
		}
	};

	QuickView.prototype.setProperty = function (sPropertyName, oValue, bSuppressInvalidate) {
		switch (sPropertyName) {
			case "busy":
			case "busyIndicatorDelay":
			case "visible":
			case "fieldGroupIds":
				if (this._oPopover) {
					this._oPopover.setProperty(sPropertyName, oValue, bSuppressInvalidate);
					return sap.ui.core.Control.prototype.setProperty.call(this, sPropertyName, oValue, true);
				}
				break;
			default:
				break;
		}

		return sap.ui.core.Control.prototype.setProperty.apply(this, arguments);
	};

	/**
	 * Returns the button, which closes the QuickView.
	 * On desktop or tablet, this method returns undefined.
	 * @returns {sap.ui.core.Control} The close button of the QuickView on phone or undefined on desktop and tablet.
	 * @private
	 */
	QuickView.prototype.getCloseButton = function() {
		if (!sap.ui.Device.system.phone) {
			return undefined;
		}

		var oPage = this._oNavContainer.getCurrentPage();
		var oButton = oPage.getCustomHeader().getContentRight()[0];

		return oButton;
	};

	/**
	 * The method sets placement position of the QuickView.
	 *
	 * @param {sap.m.PlacementType} sPlacement The side from which the QuickView appears relative to the control that opens it.
	 * @returns {sap.m.QuickView} Pointer to the control instance for chaining.
	 * @public
	 */
	QuickView.prototype.setPlacement = function (sPlacement) {
		this.setProperty("placement", sPlacement, true); // no re-rendering
		this._oPopover.setPlacement(sPlacement);

		return this;
	};

	/**
	 * The method sets the width of the QuickView.
	 * Works only on desktop or tablet.
	 * @param {sap.ui.core.CSSSize} sWidth The new width of the QuickView.
	 * @returns {sap.m.QuickView} Pointer to the control instance for chaining
	 * @public
	 */
	QuickView.prototype.setWidth = function (sWidth) {
		if (this._oNavContainer) {
			this._oNavContainer.setWidth(sWidth);
			this.setProperty('width', sWidth, true);
		}

		return this;
	};

	/**
	 * Opens the QuickView.
	 * @param {sap.ui.core.Control} oControl The control which opens the QuickView.
	 * @returns {sap.m.QuickView} Pointer to the control instance for chaining
	 * @public
	 */
	QuickView.prototype.openBy = function(oControl) {
		this._oPopover.openBy(oControl);

		return this;
	};

	["addStyleClass", "removeStyleClass", "toggleStyleClass", "hasStyleClass"].forEach(function(sName){
		QuickView.prototype[sName] = function() {
			if (this._oPopover && this._oPopover[sName]) {
				var res = this._oPopover[sName].apply(this._oPopover, arguments);
				return res === this._oPopover ? this : res;
			}
		};
	});

	["setModel", "bindAggregation", "setAggregation", "insertAggregation", "addAggregation",
		"removeAggregation", "removeAllAggregation", "destroyAggregation"].forEach(function (sFuncName) {
			QuickView.prototype["_" + sFuncName + "Old"] = QuickView.prototype[sFuncName];
			QuickView.prototype[sFuncName] = function () {
				var result = QuickView.prototype["_" + sFuncName + "Old"].apply(this, arguments);

				// Marks items aggregation as changed and invalidate popover to trigger rendering
				this._bItemsChanged = true;

				if (this._bRendered && this._oPopover) {
					this._oPopover.invalidate();
				}

				if (["removeAggregation", "removeAllAggregation"].indexOf(sFuncName) !== -1) {
					return result;
				}

				return this;
			};
		});

	return QuickView;

}, /* bExport= */true);
<|endoftext|>


<commit_before>import React from 'react';
import classNames from 'classnames';
import '../css/ConcludedIssue.css';

class ConcludedIssue extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      visibleAlternatives: false,
      majority: this.calculateMajority(props.alternatives, props.votes, props.majorityTreshold),
    }
    this.handleClick = this.handleClick.bind(this);
  }

  // Maps over alternatives to see if any of them got majority vote
  calculateMajority(alternatives, votes, majorityTreshold) {
    let majority = false;
    alternatives.map(function(alternative){
      if (votes
        .filter(vote => vote.alternative === alternative.id)
        .length / votes.length >= majorityTreshold) {
        majority = true
      }
    });
    return majority;
  }

  // CLicking the issue should show/hide the answers
  handleClick() {
    this.setState({
      visibleAlternatives: !this.state.visibleAlternatives,
    });
  }

  render() {
    console.log(this.state.visibleAlternatives)
    return (

{this.props.text}

          {this.props.alternatives.map(alternative => (

 vote.alternative === alternative.id)
                  .length / this.props.votes.length >= this.props.majorityTreshold,
              })}
            >
              {alternative.text}

          ))}

    )
  }
}

export default ConcludedIssue;
<commit_msg>move calculateMajority function out of component<commit_after>import React from 'react';
import classNames from 'classnames';
import '../css/ConcludedIssue.css';

// Maps over alternatives to see if any of them got majority vote
function calculateMajority(alternatives, votes, majorityTreshold) {
  let majority = false;
  alternatives.map(function(alternative){
    if (votes
      .filter(vote => vote.alternative === alternative.id)
      .length / votes.length >= majorityTreshold) {
      majority = true
    }
  });
  return majority;
}

class ConcludedIssue extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      visibleAlternatives: false,
      majority: calculateMajority(props.alternatives, props.votes, props.majorityTreshold),
    }
    this.handleClick = this.handleClick.bind(this);
  }

  // CLicking the issue should show/hide the answers
  handleClick() {
    this.setState({
      visibleAlternatives: !this.state.visibleAlternatives,
    });
  }

  render() {
    console.log(this.state.visibleAlternatives)
    return (

{this.props.text}

          {this.props.alternatives.map(alternative => (

 vote.alternative === alternative.id)
                  .length / this.props.votes.length >= this.props.majorityTreshold,
              })}
            >
              {alternative.text}

          ))}

    )
  }
}

export default ConcludedIssue;
<|endoftext|>