<commit_before>/*
 * Wegas
 * http://wegas.albasim.ch
 *
 * Copyright (c) 2013-2018  School of Business and Engineering Vaud, Comem, MEI
 * Licensed under the MIT License
 */
/* global I18n */

/**
 * @fileoverview
 * @author Francois-Xavier Aeberhard <fx@red-agent.com>
 */
YUI.add('wegas-button', function(Y) {
    'use strict';
    var CONTENTBOX = 'contentBox',
        BOUNDINGBOX = 'boundingBox',
        Wegas = Y.Wegas,
        Button,
        ToggleButton,
        MarkAsUnread;

    /**
     * @name Y.Wegas.Button
     * @extends Y.Button
     * @borrows Y.WidgetChild, Y.Wegas.Widget, Y.Wegas.Editable
     * @class Custom Button implementation.
     * @constructor
     * @description Custom Button implementation. Adds Y.WidgetChild and
     * Y.Wegas.Widget extensions to the original Y.Button
     */
    Button = Y.Base.create('button', Y.Button,
        [Y.WidgetChild, Wegas.Widget, Wegas.Editable], {
        /** @lends Y.Wegas.Button# */
        // *** Private fields *** //

        // *** Lifecycle Methods *** //
        /**
         * @function
         * @private
         * @description Set variable with initials values.
         * Plug tooltip add given (by ATTRS) css class to contentbox
         */
        initializer: function() {
            Button.superclass.initializer.apply(this, arguments);

            this.publish('click', {
                emitFacade: true,
                bubbles: true,
                defaultFn: function() {
                    // Force event activation by default
                }
            });
            //this.constructor.CSS_PREFIX = "yui3-button";                      // Revert changes done by Y.Wegas.Widget so styling will work
            this._cssPrefix = 'yui3-button';

            if (this.get('cssClass')) {
                this.get(CONTENTBOX).addClass(this.get('cssClass'));
            }

            if (this.get('tooltip')) {
                this.plug(Y.Plugin.Tooltip, {
                    content: Y.Template.Micro.compile(this.get('tooltip'))()
                });
            }
        },
        getEditorLabel: function() {
            return Wegas.Helper.stripHtml(I18n.t(this.get('label')));
        },
        /**
         * @function
         * @private
         * @description Call widget parent to execute its proper render function.
         * add "wegas-button" class to bounding box.
         */
        renderUI: function() {
            Button.superclass.renderUI.apply(this, arguments);
            this.get(BOUNDINGBOX).addClass('wegas-button');
        },
        _getLabel: function(value) {
            return value;
        }
    }, {
        /**
         * @lends Y.Wegas.Button
         */
        EDITORNAME: 'Button',
        /**
         * @field
         * @static
         * @description
         *
Attributes

         *

         *
label: the label of the button

         *
data: the data used by the button

         *
tooltip: the tooltip of the button

         *
disabled: boolean to choose state of the button

         *
cssClass: cssClass of the button

         *
plugins: impact to bind at the buttons

         *

         */
        ATTRS: {
            label: Y.Wegas.Helper.getTranslationAttr({
                label: "Label",
                type: "string"
            }),
            labelHTML: {
                transient: true
            },
            data: {
                view: {
                    type: 'hidden'
                }
            },
            tooltip: {
                type: 'string',
                optional: true,
                transient: true
            },
            disabled: {
                type: 'boolean',
                view: {
                    label: 'disabled',
                    className: 'wegas-advanced-feature'
                }
            },
            cssClass: {
                value: null
            }
        }
    });
    Wegas.Button = Button;

    /* @fixme @hack So we can display html tag inside a button */
    Y.Button.prototype._setLabel = function(label, name, opts) {
        if (!opts || opts.src !== 'internal') {
            var text;
            if (label instanceof
                Y.Wegas.persistence.TranslatableContent || (typeof label === "object" && label["@class"] === "TranslatableContent")) {
                text = I18n.t(label);
            } else {
                text = label;
            }
            this.set('labelHTML', Y.Template.Micro.compile(text || '')(), {
                src: 'internal'
            });
        }
        return label;
    };

    /**
     * Plugin which adds an unread message counter to a widget.
     *
     * @class Y.Wegas.UnreadCount
     * @extends Y.Plugin.Base
     * @borrows Y.Wegas.Plugin, Y.Wegas.Editable
     */
    var UnreadCount = Y.Base.create('UnreadCount', Y.Plugin.Base,
        [Wegas.Plugin, Wegas.Editable], {
        /** @lends Y.Plugin.UnreadCount# */

        // *** Private fields *** //
        // *** Lifecycle methods *** //
        /**
         * @function
         * @private
         * @description Set variable with initials values.
         */
        initializer: function() {
            var k;
            this.handlers = {};
            this._counters = {
                InboxDescriptor: function(descriptor, instance, resolve) {
                    resolve(instance.get('unreadCount'));
                },
                DialogueDescriptor: function(descriptor, instance, resolve) {
                    var state = descriptor.getCurrentState();
                    if (!instance.get('enabled')) {
                        return false;
                    }
                    state.getAvailableActions(function(availableActions) {
                        resolve(availableActions.length > 0 ? 1 : 0);
                    });
                },
                QuestionDescriptor: function(descriptor, instance, resolve) {
                    if (descriptor.get('cbx')) {
                        resolve(instance.get('active') && !instance.get('validated') ? 1 : 0); // only count if it is active
                    } else {
                        if (instance.get('replies')) {
                            resolve(instance.get('replies').length === 0 && !instance.get('validated') && instance.get('active') ? 1 : 0); // only count if it is active
                        } else {
                            resolve(0);
                        }
                    }
                },
                WhQuestionDescriptor: function(descriptor, instance, resolve) {
                    resolve((instance.get('active') && !instance.get("validated") ? 1 : 0));
                },
                PeerReviewDescriptor: function(descriptor, instance, resolve) {
                    var i, j, k,
                        types = ['toReview', 'reviewed'],
                        reviews,
                        review,
                        counter = 0;

                    for (i = 0; i < 2; i++) {
                        reviews = instance.get(types[i]);
                        for (j = 0; j < reviews.length; j++) {
                            review = reviews[j];
                            if ((i === 0 && review.get('reviewState') === 'DISPATCHED') ||
                                (i === 1 && review.get('reviewState') === 'NOTIFIED')) {
                                counter++;
                            }
                        }
                    }
                    resolve(counter);
                }
            };
            for (k in this.get('userCounters')) {
                var theFunction = this.get('userCounters')[k];
                if (!theFunction instanceof Function) {
                    theFunction = eval('(' + theFunction + ')');
                }
                this._counters[k] = theFunction;
            }
            this.bindUI();
        },
        /**
         * @function
         * @private
         * @description bind function to events.
         * When VariableDescriptorFacade is updated, do sync.
         * When plugin's host is render, do sync.
         */
        bindUI: function() {
            this.handlers.update = Wegas.Facade.Variable.after(
                'update',
                this.syncUI,
                this
                );
            this.afterHostEvent('render', this.syncUI, this);
        },
        /**
         * @function
         * @private
         * @description call function 'getUnreadCount' to set the number of
         * unread on the host.
         */
        syncUI: function() {
            this.updateCounter();
        },
        setCounterValue: function(unreadCount) {
            var bb = this.get('host').get(BOUNDINGBOX),
                target = bb.one('.wegas-unreadcount');

            if (!target) {
                // If the counter span has not been rendered, do it
                bb.append('');
                target = bb.one('.wegas-unreadcount');
            }

            if (unreadCount > 0) {
                // Update the content, but only if necessary, to enable targeted CSS animations
                var span = target.one("span"),
                    oldval = span && span.getData("value");
                oldval = oldval ? +oldval : -1;
                if (oldval !== unreadCount) {
                    target.setContent(
                        "" +
                        (this.get('displayValue') ? unreadCount : '') +
                        ''
                    );
                    bb.addClass('wegas-unreadcount');
                }
            } else {
                target.setContent('');
                bb.removeClass('wegas-unreadcount');
            }
        },
        /**
         * @function
         * @private
         * @description Detach all functions created by this widget
         */
        destructor: function() {
            for (var k in this.handlers) {
                this.handlers[k].detach();
            }
        },
        // *** Private methods *** //
        /**
         * @function
         * @private
         * @return Number of unread.
         * @description Count the number of unread reply in given variable.
         */
        updateCounter: function() {
            var i,
                instance,
                /*messages,*/ items,
                count = 0,
                klass,
                list = this.get('variable.evaluated'),
                descriptor,
                context = this,
                promises = [];

            if (!list) {
                return 0;
            }

            if (!Y.Lang.isArray(list)) {
                list = [list];
            }

            descriptor = list.pop();
            while (descriptor) {
                klass = descriptor.get('@class');
                if (klass === 'ListDescriptor') {
                    items = descriptor.flatten();
                    for (i = 0; i < items.length; i = i + 1) {
                        list.push(items[i]);
                    }
                } else {
                    if (this._counters[klass]) {
                        promises.push(
                            new Y.Promise(function(resolve, reject) {
                                var fcn;
                                if (context._counters[klass] instanceof Function) {
                                    fcn = context._counters[klass];
                                } else {
                                    fcn = eval('(' + context._counters[klass] + ')');
                                }

                                fcn.call(context, descriptor, descriptor.getInstance(),
                                    function(count) {
                                        resolve(count);
                                    }
                                );
                            }));
                    }
                }

                descriptor = list.pop();
            }

            Y.Promise.all(promises).then(function(allCounts) {
                var total = 0, i;
                for (i = 0; i < allCounts.length; i += 1) {
                    total += allCounts[i];
                }
                context.setCounterValue(total);
            });
        }
    }, {
        NS: 'UnreadCount',
        NAME: 'UnreadCount',
        /**
         * @lends Y.Plugin.UnreadCount
         */
        /**
         * @field
         * @static
         * @description
         *
Attributes

         *

         *
variable: The target variable, returned either based on the name
         *     attribute, and if absent by evaluating the expr attribute.

         *

         */
        ATTRS: {
            /**
             * The target variable, returned either based on the variableName attribute,
             * and if absent by evaluating the expr attribute.
             */
            variable: {
                type: 'object',
                getter: Wegas.Widget.VARIABLEDESCRIPTORGETTER,
                view: {
                    type: 'variableselect',
                    label: 'Unread count',
                    classFilter: ['ListDescriptor', 'InboxDescriptor']
                }
            },
            displayValue: {
                type: 'boolean',
                optional: true,
                value: true,
                view: {
                    label: "Display value"
                }
            },
            userCounters: {
                type: 'object',
                value: {},
                optional: true,
                view: {
                    type: 'hidden'
                }
            }
        }
    });
    Y.Plugin.UnreadCount = UnreadCount;

    MarkAsUnread = Y.Base.create('wegas-mark-as-unread', Y.Plugin.UnreadCount, [], {
        setCounterValue: function(unreadCount) {
            if (unreadCount > 0) {
                if (this.get('host') instanceof Y.Node) {
                    this.get('host').addClass('unread');
                } else if (this.get('host') instanceof Y.Widget) {
                    this.get('host').get('boundingBox').addClass('unread');
                } else {
                    Y.log('unread error...');
                }
            }
        }
    }, {
        NS: 'MarkAsUnread',
        NAME: 'MarkAsUnread',
        ATTRS: {}
    });
    Y.Plugin.MarkAsUnread = MarkAsUnread;

    /**
     * @name Y.Wegas.OpenPageButton
     * @extends Y.Wegas.Button
     * @class Shortcut to create a Button with an OpenPageAction plugin
     * @constructor
     * @description Shortcut to create a Button with an OpenPageAction plugin
     */
    Wegas.OpenPageButton = Y.Base.create('button', Wegas.Button, [], {
        /** @lends Y.Wegas.OpenPageButton# */
        /**
         * @function
         * @private
         * @param cfg
         * @description plug the plugin "OpenPageAction" with a given
         *  configuration.
         */
        initializer: function(cfg) {
            this.plug(Y.Plugin.OpenPageAction, cfg);
        }
    });

    Wegas.ToggleButton = Y.Base.create('button', Y.ToggleButton, [Y.WidgetChild, Wegas.Widget, Wegas.Editable], {}, {}
    );
});
<commit_msg>Fix UnreadCount<commit_after>/*
 * Wegas
 * http://wegas.albasim.ch
 *
 * Copyright (c) 2013-2018  School of Business and Engineering Vaud, Comem, MEI
 * Licensed under the MIT License
 */
/* global I18n */

/**
 * @fileoverview
 * @author Francois-Xavier Aeberhard <fx@red-agent.com>
 */
YUI.add('wegas-button', function(Y) {
    'use strict';
    var CONTENTBOX = 'contentBox',
        BOUNDINGBOX = 'boundingBox',
        Wegas = Y.Wegas,
        Button,
        ToggleButton,
        MarkAsUnread;

    /**
     * @name Y.Wegas.Button
     * @extends Y.Button
     * @borrows Y.WidgetChild, Y.Wegas.Widget, Y.Wegas.Editable
     * @class Custom Button implementation.
     * @constructor
     * @description Custom Button implementation. Adds Y.WidgetChild and
     * Y.Wegas.Widget extensions to the original Y.Button
     */
    Button = Y.Base.create('button', Y.Button,
        [Y.WidgetChild, Wegas.Widget, Wegas.Editable], {
        /** @lends Y.Wegas.Button# */
        // *** Private fields *** //

        // *** Lifecycle Methods *** //
        /**
         * @function
         * @private
         * @description Set variable with initials values.
         * Plug tooltip add given (by ATTRS) css class to contentbox
         */
        initializer: function() {
            Button.superclass.initializer.apply(this, arguments);

            this.publish('click', {
                emitFacade: true,
                bubbles: true,
                defaultFn: function() {
                    // Force event activation by default
                }
            });
            //this.constructor.CSS_PREFIX = "yui3-button";                      // Revert changes done by Y.Wegas.Widget so styling will work
            this._cssPrefix = 'yui3-button';

            if (this.get('cssClass')) {
                this.get(CONTENTBOX).addClass(this.get('cssClass'));
            }

            if (this.get('tooltip')) {
                this.plug(Y.Plugin.Tooltip, {
                    content: Y.Template.Micro.compile(this.get('tooltip'))()
                });
            }
        },
        getEditorLabel: function() {
            return Wegas.Helper.stripHtml(I18n.t(this.get('label')));
        },
        /**
         * @function
         * @private
         * @description Call widget parent to execute its proper render function.
         * add "wegas-button" class to bounding box.
         */
        renderUI: function() {
            Button.superclass.renderUI.apply(this, arguments);
            this.get(BOUNDINGBOX).addClass('wegas-button');
        },
        _getLabel: function(value) {
            return value;
        }
    }, {
        /**
         * @lends Y.Wegas.Button
         */
        EDITORNAME: 'Button',
        /**
         * @field
         * @static
         * @description
         *
Attributes

         *

         *
label: the label of the button

         *
data: the data used by the button

         *
tooltip: the tooltip of the button

         *
disabled: boolean to choose state of the button

         *
cssClass: cssClass of the button

         *
plugins: impact to bind at the buttons

         *

         */
        ATTRS: {
            label: Y.Wegas.Helper.getTranslationAttr({
                label: "Label",
                type: "string"
            }),
            labelHTML: {
                transient: true
            },
            data: {
                view: {
                    type: 'hidden'
                }
            },
            tooltip: {
                type: 'string',
                optional: true,
                transient: true
            },
            disabled: {
                type: 'boolean',
                view: {
                    label: 'disabled',
                    className: 'wegas-advanced-feature'
                }
            },
            cssClass: {
                value: null
            }
        }
    });
    Wegas.Button = Button;

    /* @fixme @hack So we can display html tag inside a button */
    Y.Button.prototype._setLabel = function(label, name, opts) {
        if (!opts || opts.src !== 'internal') {
            var text;
            if (label instanceof
                Y.Wegas.persistence.TranslatableContent || (typeof label === "object" && label["@class"] === "TranslatableContent")) {
                text = I18n.t(label);
            } else {
                text = label;
            }
            this.set('labelHTML', Y.Template.Micro.compile(text || '')(), {
                src: 'internal'
            });
        }
        return label;
    };

    /**
     * Plugin which adds an unread message counter to a widget.
     *
     * @class Y.Wegas.UnreadCount
     * @extends Y.Plugin.Base
     * @borrows Y.Wegas.Plugin, Y.Wegas.Editable
     */
    var UnreadCount = Y.Base.create('UnreadCount', Y.Plugin.Base,
        [Wegas.Plugin, Wegas.Editable], {
        /** @lends Y.Plugin.UnreadCount# */

        // *** Private fields *** //
        // *** Lifecycle methods *** //
        /**
         * @function
         * @private
         * @description Set variable with initials values.
         */
        initializer: function() {
            var k;
            this.handlers = {};
            this._counters = {
                InboxDescriptor: function(descriptor, instance, resolve) {
                    resolve(instance.get('unreadCount'));
                },
                DialogueDescriptor: function(descriptor, instance, resolve) {
                    var state = descriptor.getCurrentState();
                    if (!instance.get('enabled')) {
                        return false;
                    }
                    state.getAvailableActions(function(availableActions) {
                        resolve(availableActions.length > 0 ? 1 : 0);
                    });
                },
                QuestionDescriptor: function(descriptor, instance, resolve) {
                    if (descriptor.get('cbx')) {
                        resolve(instance.get('active') && !instance.get('validated') ? 1 : 0); // only count if it is active
                    } else {
                        if (instance.get('replies')) {
                            resolve(instance.get('replies').length === 0 && !instance.get('validated') && instance.get('active') ? 1 : 0); // only count if it is active
                        } else {
                            resolve(0);
                        }
                    }
                },
                WhQuestionDescriptor: function(descriptor, instance, resolve) {
                    resolve((instance.get('active') && !instance.get("validated") ? 1 : 0));
                },
                PeerReviewDescriptor: function(descriptor, instance, resolve) {
                    var i, j, k,
                        types = ['toReview', 'reviewed'],
                        reviews,
                        review,
                        counter = 0;

                    for (i = 0; i < 2; i++) {
                        reviews = instance.get(types[i]);
                        for (j = 0; j < reviews.length; j++) {
                            review = reviews[j];
                            if ((i === 0 && review.get('reviewState') === 'DISPATCHED') ||
                                (i === 1 && review.get('reviewState') === 'NOTIFIED')) {
                                counter++;
                            }
                        }
                    }
                    resolve(counter);
                }
            };
            for (k in this.get('userCounters')) {
                var theFunction = this.get('userCounters')[k];
                if (theFunction instanceof Function === false) {
                    theFunction = eval('(' + theFunction + ')');
                }
                this._counters[k] = theFunction;
            }
            this.bindUI();
        },
        /**
         * @function
         * @private
         * @description bind function to events.
         * When VariableDescriptorFacade is updated, do sync.
         * When plugin's host is render, do sync.
         */
        bindUI: function() {
            this.handlers.update = Wegas.Facade.Variable.after(
                'update',
                this.syncUI,
                this
                );
            this.afterHostEvent('render', this.syncUI, this);
        },
        /**
         * @function
         * @private
         * @description call function 'getUnreadCount' to set the number of
         * unread on the host.
         */
        syncUI: function() {
            this.updateCounter();
        },
        setCounterValue: function(unreadCount) {
            var bb = this.get('host').get(BOUNDINGBOX),
                target = bb.one('.wegas-unreadcount');

            if (!target) {
                // If the counter span has not been rendered, do it
                bb.append('');
                target = bb.one('.wegas-unreadcount');
            }

            if (unreadCount > 0) {
                // Update the content, but only if necessary, to enable targeted CSS animations
                var span = target.one("span"),
                    oldval = span && span.getData("value");
                oldval = oldval ? +oldval : -1;
                if (oldval !== unreadCount) {
                    target.setContent(
                        "" +
                        (this.get('displayValue') ? unreadCount : '') +
                        ''
                    );
                    bb.addClass('wegas-unreadcount');
                }
            } else {
                target.setContent('');
                bb.removeClass('wegas-unreadcount');
            }
        },
        /**
         * @function
         * @private
         * @description Detach all functions created by this widget
         */
        destructor: function() {
            for (var k in this.handlers) {
                this.handlers[k].detach();
            }
        },
        // *** Private methods *** //
        /**
         * @function
         * @private
         * @return Number of unread.
         * @description Count the number of unread reply in given variable.
         */
        updateCounter: function() {
            var i,
                instance,
                /*messages,*/ items,
                count = 0,
                klass,
                list = this.get('variable.evaluated'),
                descriptor,
                context = this,
                promises = [];

            if (!list) {
                return 0;
            }

            if (!Y.Lang.isArray(list)) {
                list = [list];
            }

            descriptor = list.pop();
            while (descriptor) {
                klass = descriptor.get('@class');
                if (klass === 'ListDescriptor') {
                    items = descriptor.flatten();
                    for (i = 0; i < items.length; i = i + 1) {
                        list.push(items[i]);
                    }
                } else {
                    if (this._counters[klass]) {
                        promises.push(
                            new Y.Promise(function(resolve, reject) {
                                var fcn;
                                if (context._counters[klass] instanceof Function) {
                                    fcn = context._counters[klass];
                                } else {
                                    fcn = eval('(' + context._counters[klass] + ')');
                                }

                                fcn.call(context, descriptor, descriptor.getInstance(),
                                    function(count) {
                                        resolve(count);
                                    }
                                );
                            }));
                    }
                }

                descriptor = list.pop();
            }

            Y.Promise.all(promises).then(function(allCounts) {
                var total = 0, i;
                for (i = 0; i < allCounts.length; i += 1) {
                    total += allCounts[i];
                }
                context.setCounterValue(total);
            });
        }
    }, {
        NS: 'UnreadCount',
        NAME: 'UnreadCount',
        /**
         * @lends Y.Plugin.UnreadCount
         */
        /**
         * @field
         * @static
         * @description
         *
Attributes

         *

         *
variable: The target variable, returned either based on the name
         *     attribute, and if absent by evaluating the expr attribute.

         *

         */
        ATTRS: {
            /**
             * The target variable, returned either based on the variableName attribute,
             * and if absent by evaluating the expr attribute.
             */
            variable: {
                type: 'object',
                getter: Wegas.Widget.VARIABLEDESCRIPTORGETTER,
                view: {
                    type: 'variableselect',
                    label: 'Unread count',
                    classFilter: ['ListDescriptor', 'InboxDescriptor']
                }
            },
            displayValue: {
                type: 'boolean',
                optional: true,
                value: true,
                view: {
                    label: "Display value"
                }
            },
            userCounters: {
                type: 'object',
                value: {},
                optional: true,
                view: {
                    type: 'hidden'
                }
            }
        }
    });
    Y.Plugin.UnreadCount = UnreadCount;

    MarkAsUnread = Y.Base.create('wegas-mark-as-unread', Y.Plugin.UnreadCount, [], {
        setCounterValue: function(unreadCount) {
            if (unreadCount > 0) {
                if (this.get('host') instanceof Y.Node) {
                    this.get('host').addClass('unread');
                } else if (this.get('host') instanceof Y.Widget) {
                    this.get('host').get('boundingBox').addClass('unread');
                } else {
                    Y.log('unread error...');
                }
            }
        }
    }, {
        NS: 'MarkAsUnread',
        NAME: 'MarkAsUnread',
        ATTRS: {}
    });
    Y.Plugin.MarkAsUnread = MarkAsUnread;

    /**
     * @name Y.Wegas.OpenPageButton
     * @extends Y.Wegas.Button
     * @class Shortcut to create a Button with an OpenPageAction plugin
     * @constructor
     * @description Shortcut to create a Button with an OpenPageAction plugin
     */
    Wegas.OpenPageButton = Y.Base.create('button', Wegas.Button, [], {
        /** @lends Y.Wegas.OpenPageButton# */
        /**
         * @function
         * @private
         * @param cfg
         * @description plug the plugin "OpenPageAction" with a given
         *  configuration.
         */
        initializer: function(cfg) {
            this.plug(Y.Plugin.OpenPageAction, cfg);
        }
    });

    Wegas.ToggleButton = Y.Base.create('button', Y.ToggleButton, [Y.WidgetChild, Wegas.Widget, Wegas.Editable], {}, {}
    );
});
<|endoftext|>


<commit_before>/*
  Copyright 2010-2017 BusinessCode GmbH, Germany

  Licensed 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.
*/
"use strict";

bcdui.util.namespace("bcdui.component.cube.expandCollapse",
/** @lends bcdui.component.cube.expandCollapse */
{
  _init: function(htmlElement) {

    var outer = jQuery(htmlElement).closest("*[bcdrendererid]");
    var cubeId = outer.attr("bcdRendererId") || "";
    var cube = bcdui.factory.objectRegistry.getObject(cubeId);

    // not a cube?
    if (typeof cube == "undefined" || cube.type !== "bcdui.component.cube.Cube")
      return;

    var targetModel = cube.getEnhancedConfiguration();
    var cubeModel = cube.getPrimaryModel();

    // get mode
    var mode = cube.getEnhancedConfiguration().read("//xp:ExpandCollapseCells/@apply", "false");
    if (mode != "collapse" && mode != "expand") {
      jQuery(htmlElement).show();
      return;
    }
    var initialCollapsed = (mode === "collapse");

    // reset some flicker-avoiding styles
    outer.get(0).style.width = outer.attr("widthBak") || "";
    outer.get(0).style.height = outer.attr("heightBak") || "";
    outer.get(0).style.display = outer.attr("displayBak") || "";
    outer.removeAttr("heightBak");
    outer.removeAttr("widthBak");
    outer.removeAttr("displayBak");

    // set clickable buttons on col and row dimensions
    jQuery(htmlElement).find("th").each(function(i,e) {
      var el = jQuery(e);

      // build key like string (dimvalue + separator + ...) for the current TH based on coldim and actual value (for row dims)
      var value = "";
      var idents = bcdui.widget._computeRowAndColIdents(el.get(0));
      var idx = cubeModel.read("/*/wrs:Header/wrs:Columns/wrs:C[@id='" + idents.bcdColIdent + "']/@pos", "0");
      if (idx != 0) {
        if (idents.bcdColIdent.indexOf("|") != -1) {
          var c = idents.bcdColIdent.split("|");
          idx = el.closest("tr").index();
          for (var y = 0; y <= idx; y++) {
            if (y > 0)
              value += bcdui.core.magicChar.separator;
            var isEmptyOrNull = (c[y] == bcdui.core.magicChar.dimEmpty) || (c[y] == bcdui.core.magicChar.dimNull);
            value += isEmptyOrNull ? bcdui.core.magicChar.dimEmpty : c[y] // map possible dimEmpty or dimNull to dimEmpty (this is used in concatCells (expandCollapseCells.xslt)
          }
        }
        else {
          for (var x = 1; x <= idx; x++) {
            if (x > 1)
              value += bcdui.core.magicChar.separator;
            if (cubeModel.query("/*/wrs:Data/wrs:R[@id='" + idents.bcdRowIdent + "']/wrs:C[position()='" + x + "']/wrs:null") != null) // map wrs:C/wrs:null to dimEmpty (this is used in concatCells (expandCollapseCells.xslt)
              value += bcdui.core.magicChar.dimEmpty;
            else
              value += cubeModel.read("/*/wrs:Data/wrs:R[@id='" + idents.bcdRowIdent + "']/wrs:C[position()='" + x + "']", "");
          }
        }
      }
      var addButton = false;
      if (! el.hasClass("bcdDimension") && ! el.hasClass("bcdMeasure")) { // this skips rowDimensions/ColMeasures THs in THEAD
        addButton  = (el.closest("thead").length != 0 && el.closest("tr").next("tr").next("tr").length > 0);
        addButton |= (el.closest("thead").length == 0 && !(el.index() + 1 == el.next("td").index()));

        // do we have a collapsed column which is now marked as bcdTotal, if so remove the class, otherwise we have a real total and don't draw a button
        if (el.hasClass("bcdTotal")) {
         if (value.indexOf(bcdui.core.magicChar.dimTotal) != -1)
            addButton = false;
          else
            el.removeClass("bcdTotal");
        }
      }
      if (addButton) {
        var rowCol = el.closest("thead").length > 0 ? "xp:Col" : "xp:Row";
        var xPath = "/*/xp:XSLTParameters/xp:ExpandCollapseCells/" + rowCol + "[.='" + value + "']";
        var status = (targetModel.query(xPath) == null) ? (initialCollapsed ? "bcdExpand" : "bcdCollapse") : (initialCollapsed ? "bcdCollapse" : "bcdExpand");
        var data = el.text();
        el.html("

" + data + "

");
        // remember xpath and value
        el.data("config", {value: value, xPath: xPath, targetModel: targetModel});
      }
    });

    // the actual click handler on the added buttons
    jQuery(htmlElement).find("th").on("click", ".bcdExpandCollapseButton", function(event) {

      // turn click handler off to avoid quick clicking on buttons before the cube actually refreshed itself
      jQuery(htmlElement).find("th").off("click");

      var el = jQuery(event.target);
      var config = el.closest("th").data("config");

      // avoid some flickering
      var outer = el.closest("*[bcdrendererid]");
      if (outer.get(0).style.width != "")
        outer.attr("widthBak", outer.get(0).style.width);
      if (outer.get(0).style.height != "")
        outer.attr("heightBak", outer.get(0).style.height);
      if (outer.get(0).style.display != "")
        outer.attr("displayBak", outer.get(0).style.display);
      outer.css("height", outer.outerHeight());
      outer.css("width", outer.outerWidth());
      outer.css("display", "block");

      if (typeof config == "undefined")
        return;

      // either add or remove the key value in the statusmodel
      if (config.targetModel.query(config.xPath) == null) {
        var node = bcdui.core.createElementWithPrototype(config.targetModel.getData(), config.xPath + "[@bcdHelper='true']");
        node.text = config.value;
        node.removeAttribute("bcdHelper");
      }
      else
        bcdui.core.removeXPath(config.targetModel.getData(), config.xPath)

      config.targetModel.fire(); // fire on cube configuration triggers rerender
    });
  }
});
<commit_msg>Client, fix collapsableCube (inner open/outer close effects)<commit_after>/*
  Copyright 2010-2017 BusinessCode GmbH, Germany

  Licensed 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.
*/
"use strict";

bcdui.util.namespace("bcdui.component.cube.expandCollapse",
/** @lends bcdui.component.cube.expandCollapse */
{
  _init: function(htmlElement) {

    var outer = jQuery(htmlElement).closest("*[bcdrendererid]");
    var cubeId = outer.attr("bcdRendererId") || "";
    var cube = bcdui.factory.objectRegistry.getObject(cubeId);

    // not a cube?
    if (typeof cube == "undefined" || cube.type !== "bcdui.component.cube.Cube")
      return;

    var targetModel = cube.getEnhancedConfiguration();
    var cubeModel = cube.getPrimaryModel();

    // get mode
    var mode = cube.getEnhancedConfiguration().read("//xp:ExpandCollapseCells/@apply", "false");
    if (mode != "collapse" && mode != "expand") {
      jQuery(htmlElement).show();
      return;
    }
    var initialCollapsed = (mode === "collapse");

    // reset some flicker-avoiding styles
    outer.get(0).style.width = outer.attr("widthBak") || "";
    outer.get(0).style.height = outer.attr("heightBak") || "";
    outer.get(0).style.display = outer.attr("displayBak") || "";
    outer.removeAttr("heightBak");
    outer.removeAttr("widthBak");
    outer.removeAttr("displayBak");

    // set clickable buttons on col and row dimensions
    jQuery(htmlElement).find("th").each(function(i,e) {
      var el = jQuery(e);

      // build key like string (dimvalue + separator + ...) for the current TH based on coldim and actual value (for row dims)
      var value = "";
      var idents = bcdui.widget._computeRowAndColIdents(el.get(0));
      var idx = cubeModel.read("/*/wrs:Header/wrs:Columns/wrs:C[@id='" + idents.bcdColIdent + "']/@pos", "0");
      if (idx != 0) {
        if (idents.bcdColIdent.indexOf("|") != -1) {
          var c = idents.bcdColIdent.split("|");
          idx = el.closest("tr").index();
          for (var y = 0; y <= idx; y++) {
            if (y > 0)
              value += bcdui.core.magicChar.separator;
            var isEmptyOrNull = (c[y] == bcdui.core.magicChar.dimEmpty) || (c[y] == bcdui.core.magicChar.dimNull);
            value += isEmptyOrNull ? bcdui.core.magicChar.dimEmpty : c[y] // map possible dimEmpty or dimNull to dimEmpty (this is used in concatCells (expandCollapseCells.xslt)
          }
        }
        else {
          for (var x = 1; x <= idx; x++) {
            if (x > 1)
              value += bcdui.core.magicChar.separator;
            if (cubeModel.query("/*/wrs:Data/wrs:R[@id='" + idents.bcdRowIdent + "']/wrs:C[position()='" + x + "']/wrs:null") != null) // map wrs:C/wrs:null to dimEmpty (this is used in concatCells (expandCollapseCells.xslt)
              value += bcdui.core.magicChar.dimEmpty;
            else
              value += cubeModel.read("/*/wrs:Data/wrs:R[@id='" + idents.bcdRowIdent + "']/wrs:C[position()='" + x + "']", "");
          }
        }
      }
      var addButton = false;
      if (! el.hasClass("bcdDimension") && ! el.hasClass("bcdMeasure")) { // this skips rowDimensions/ColMeasures THs in THEAD
        addButton  = (el.closest("thead").length != 0 && el.closest("tr").next("tr").next("tr").length > 0);
        addButton |= (el.closest("thead").length == 0 && !(el.index() + 1 == el.next("td").index()));

        // do we have a collapsed column which is now marked as bcdTotal, if so remove the class, otherwise we have a real total and don't draw a button
        if (el.hasClass("bcdTotal")) {
         if (value.indexOf(bcdui.core.magicChar.dimTotal) != -1)
            addButton = false;
          else
            el.removeClass("bcdTotal");
        }
      }
      if (addButton) {
        var rowCol = el.closest("thead").length > 0 ? "xp:Col" : "xp:Row";
        var xPath = "/*/xp:XSLTParameters/xp:ExpandCollapseCells/" + rowCol + "[.='" + value + "']";
        var xPathDeeperLevels = "/*/xp:XSLTParameters/xp:ExpandCollapseCells/" + rowCol + "[starts-with(., '" + value + bcdui.core.magicChar.separator+"')]";
        var xPathDeeperLevelsLookUp = "/*/xp:XSLTParameters/xp:ExpandCollapseCells/" + rowCol + "[starts-with(., '" + bcdui.core.magicChar.nonWord + value + bcdui.core.magicChar.separator+"')]";
        var status = (targetModel.query(xPath) == null) ? (initialCollapsed ? "bcdExpand" : "bcdCollapse") : (initialCollapsed ? "bcdCollapse" : "bcdExpand");
        var data = el.text();
        el.html("

" + data + "

");
        // remember xpath and value
        el.data("config", {value: value, xPath: xPath, targetModel: targetModel, xPathDeeperLevels: xPathDeeperLevels, xPathDeeperLevelsLookUp: xPathDeeperLevelsLookUp});
      }
    });

    // the actual click handler on the added buttons
    jQuery(htmlElement).find("th").on("click", ".bcdExpandCollapseButton", function(event) {

      // turn click handler off to avoid quick clicking on buttons before the cube actually refreshed itself
      jQuery(htmlElement).find("th").off("click");

      var el = jQuery(event.target);
      var config = el.closest("th").data("config");

      // avoid some flickering
      var outer = el.closest("*[bcdrendererid]");
      if (outer.get(0).style.width != "")
        outer.attr("widthBak", outer.get(0).style.width);
      if (outer.get(0).style.height != "")
        outer.attr("heightBak", outer.get(0).style.height);
      if (outer.get(0).style.display != "")
        outer.attr("displayBak", outer.get(0).style.display);
      outer.css("height", outer.outerHeight());
      outer.css("width", outer.outerWidth());
      outer.css("display", "block");

      if (typeof config == "undefined")
        return;

      // either add or remove the key value in the statusmodel
      if (config.targetModel.query(config.xPath) == null) {
        var node = bcdui.core.createElementWithPrototype(config.targetModel.getData(), config.xPath + "[@bcdHelper='true']");
        node.text = config.value;
        node.removeAttribute("bcdHelper");
        jQuery.makeArray(config.targetModel.queryNodes(config.xPathDeeperLevelsLookUp)).forEach(function(e){
          e.text = e.text.substring(1,e.text.length);
        });
      }
      else {
        bcdui.core.removeXPath(config.targetModel.getData(), config.xPath)
        jQuery.makeArray(config.targetModel.queryNodes(config.xPathDeeperLevels)).forEach(function(e){
          e.text = bcdui.core.magicChar.nonWord + e.text;
        });
      }

      config.targetModel.fire(); // fire on cube configuration triggers rerender
    });
  }
});
<|endoftext|>


<commit_before>var _ = require('../../../lib/alloy/underscore')._,
	U = require('../../../utils'),
	CU = require('../compilerUtils'),
	CONST = require('../../../common/constants');

exports.parse = function(node, state) {
	return require('./base').parse(node, state, parse);
};

function parse(node, state, args) {
	var children = U.XML.getElementsFromNodes(node.childNodes),
		arrayName = CU.generateUniqueId(),
		localModel = CU.generateUniqueId(),
		code = '',
		isSearchBar = false,
		hasRows = false,
		searchBarName;

	if (args[CONST.BIND_COLLECTION]) {
		var where = args[CONST.BIND_WHERE];
		var transform = args[CONST.BIND_TRANSFORM];
		var tableState = require('./default').parse(node, state);
		code += tableState.code;

		// iterate through all children
		var itemCode = '';
		for (var i = 0, l = children.length; i < l; i++) {
			var child = children[i],
				childArgs = CU.getParserArgs(child);

			// TODO: validate children of tableview

			itemCode += CU.generateNode(child, {
				parent: {},
				local: true,
				model: localModel,
				styles: state.styles,
				post: function(node, state, args) {
					return 'rows.push(' + state.parent.symbol + ');\n';
				}
			});
		}

		// create fetch/change handler
		var col = 'Alloy.Collections[\'' + args[CONST.BIND_COLLECTION] + '\']';
		var whereCode = where ? where + "(" + col + ")" : col + ".models";
		var transformCode = transform ? transform + "(" + localModel + ")" : "{}";
		code += col + ".on('fetch change', function(e) { ";
		code += "	var models = " + whereCode + ";";
		code += "	var len = models.length;";
		code += "	var rows = [];";
		code += "	for (var i = 0; i < len; i++) {";
		code += "		var " + localModel + " = models[i];";
		code += "		" + localModel + ".__transform = " + transformCode + ";";
		code += itemCode;
		code += "	}";
		code += tableState.parent.symbol + ".setData(rows);";
		code += "});";
	} else {
		code = 'var ' + arrayName + ' = [];\n';

		// iterate through all children
		for (var i = 0, l = children.length; i < l; i++) {
			var child = children[i],
				childArgs = CU.getParserArgs(child);

			// make sure we are dealing with rows and sections
			if (childArgs.fullname === 'Alloy.Require') {
				var inspect = CU.inspectRequireNode(child);
				_.each(inspect.names, function(name) {
					if (name === 'Ti.UI.TableViewRow' ||
						name === 'Ti.UI.TableViewSection') {
						isSearchBar = false;
					} else if (name === 'Ti.UI.SearchBar') {
						isSearchBar = true;
					} else {
						U.die('TableView <Require> child at position ' + i + ' has elements that are not rows, sections, or SearchBar');
					}
				});
			} else if (childArgs.fullname === 'Ti.UI.TableViewRow' ||
					   childArgs.fullname === 'Ti.UI.TableViewSection') {
				isSearchBar = false;
			} else if (childArgs.fullname === 'Ti.UI.SearchBar') {
				isSearchBar = true;
			} else {
				U.die('TableView child at position ' + i + ' is not a row or section, or a <Require> containing rows, sections, or SearchBar');
			}

			// generate code for the row/section/searchbar
			code += CU.generateNode(child, {
				parent: {},
				styles: state.styles,
				post: function(node, state, args) {
					if (isSearchBar) {
						searchBarName = state.parent.symbol;
					} else {
						hasRows = true;
						return arrayName + '.push(' + state.parent.symbol + ');\n';
					}
				}
			});
		}

		// Create the initial TableView code
		var extras = [];
		if (hasRows) { extras.push(['data', arrayName]); }
		if (searchBarName) { extras.push(['search', searchBarName]) }
		if (extras.length) { state.extraStyle = CU.createVariableStyle(extras); }

		var tableState = require('./default').parse(node, state);
		code += tableState.code;
	}

	// Update the parsing state
	return {
		parent: {},
		styles: state.styles,
		code: code
	}
};
<commit_msg>update binding on collection add and remove events<commit_after>var _ = require('../../../lib/alloy/underscore')._,
	U = require('../../../utils'),
	CU = require('../compilerUtils'),
	CONST = require('../../../common/constants');

exports.parse = function(node, state) {
	return require('./base').parse(node, state, parse);
};

function parse(node, state, args) {
	var children = U.XML.getElementsFromNodes(node.childNodes),
		arrayName = CU.generateUniqueId(),
		localModel = CU.generateUniqueId(),
		code = '',
		isSearchBar = false,
		hasRows = false,
		searchBarName;

	if (args[CONST.BIND_COLLECTION]) {
		var where = args[CONST.BIND_WHERE];
		var transform = args[CONST.BIND_TRANSFORM];
		var tableState = require('./default').parse(node, state);
		code += tableState.code;

		// iterate through all children
		var itemCode = '';
		for (var i = 0, l = children.length; i < l; i++) {
			var child = children[i],
				childArgs = CU.getParserArgs(child);

			// TODO: validate children of tableview

			itemCode += CU.generateNode(child, {
				parent: {},
				local: true,
				model: localModel,
				styles: state.styles,
				post: function(node, state, args) {
					return 'rows.push(' + state.parent.symbol + ');\n';
				}
			});
		}

		// create fetch/change handler
		var col = 'Alloy.Collections[\'' + args[CONST.BIND_COLLECTION] + '\']';
		var whereCode = where ? where + "(" + col + ")" : col + ".models";
		var transformCode = transform ? transform + "(" + localModel + ")" : "{}";
		code += col + ".on('fetch change add remove', function(e) { ";
		code += "	var models = " + whereCode + ";";
		code += "	var len = models.length;";
		code += "	var rows = [];";
		code += "	for (var i = 0; i < len; i++) {";
		code += "		var " + localModel + " = models[i];";
		code += "		" + localModel + ".__transform = " + transformCode + ";";
		code += itemCode;
		code += "	}";
		code += tableState.parent.symbol + ".setData(rows);";
		code += "});";
	} else {
		code = 'var ' + arrayName + ' = [];\n';

		// iterate through all children
		for (var i = 0, l = children.length; i < l; i++) {
			var child = children[i],
				childArgs = CU.getParserArgs(child);

			// make sure we are dealing with rows and sections
			if (childArgs.fullname === 'Alloy.Require') {
				var inspect = CU.inspectRequireNode(child);
				_.each(inspect.names, function(name) {
					if (name === 'Ti.UI.TableViewRow' ||
						name === 'Ti.UI.TableViewSection') {
						isSearchBar = false;
					} else if (name === 'Ti.UI.SearchBar') {
						isSearchBar = true;
					} else {
						U.die('TableView <Require> child at position ' + i + ' has elements that are not rows, sections, or SearchBar');
					}
				});
			} else if (childArgs.fullname === 'Ti.UI.TableViewRow' ||
					   childArgs.fullname === 'Ti.UI.TableViewSection') {
				isSearchBar = false;
			} else if (childArgs.fullname === 'Ti.UI.SearchBar') {
				isSearchBar = true;
			} else {
				U.die('TableView child at position ' + i + ' is not a row or section, or a <Require> containing rows, sections, or SearchBar');
			}

			// generate code for the row/section/searchbar
			code += CU.generateNode(child, {
				parent: {},
				styles: state.styles,
				post: function(node, state, args) {
					if (isSearchBar) {
						searchBarName = state.parent.symbol;
					} else {
						hasRows = true;
						return arrayName + '.push(' + state.parent.symbol + ');\n';
					}
				}
			});
		}

		// Create the initial TableView code
		var extras = [];
		if (hasRows) { extras.push(['data', arrayName]); }
		if (searchBarName) { extras.push(['search', searchBarName]) }
		if (extras.length) { state.extraStyle = CU.createVariableStyle(extras); }

		var tableState = require('./default').parse(node, state);
		code += tableState.code;
	}

	// Update the parsing state
	return {
		parent: {},
		styles: state.styles,
		code: code
	}
};
<|endoftext|>


<commit_before>Template.singleHomeActivityStatus.onCreated(function () {
    var instance = this;

    // Get ID of current home
    instance.homeId = instance.data.home._id;

    // Add variable to hold activity counts
    instance.activityLevelCounts = new ReactiveVar();

    instance.autorun(function () {
      // Retrieve home resident activity level counts from server
      const activityLevelCounts = ReactiveMethod.call("getHomeActivityLevelCounts", instance.homeId);

      // Make sure activity level counts exist
      if (activityLevelCounts) {
        /*
        Re-structure activity level counts data to an object containing
        level and count attributes
        */
        const activityLevelTypes = _.keys(activityLevelCounts);

        const activityLevelData = _.map(activityLevelTypes, function (type) {
          // Construct an object with the type and count keys
          const activityLevelCount = {
            type: type,
            count: activityLevelCounts[type]
          };

          return activityLevelCount;
        });

        // Update the reactive variable, to trigger the graph to render
        instance.activityLevelCounts.set(activityLevelCounts);
      }
    });
  });

Template.singleHomeActivityStatus.onRendered(function () {
  // Get reference to template instance
  const instance = this;

  // Get home ID
  const homeId = instance.homeId;

  /*
  Set up chart
  */

  // Set up ID string for chart element
  const svgId = `#activityLevelCountsChart-${homeId}`;

  // Get reference to chart element
  const svg = dimple.newSvg(svgId, 200, 100);

  // Initialize chart with empty data array
  const activityLevelsChart = new dimple.chart(svg, []);

  // Set chart boundaries
  activityLevelsChart.setBounds("10%", "5%", "80%", "70%");

  // Add counts to x axis
  activityLevelCharts.addMeasureAxis("x", "count");
});
<commit_msg>Add home percentage calculation for activity class<commit_after>Template.singleHomeActivityStatus.onCreated(function () {
    var instance = this;

    // Get ID of current home
    instance.homeId = instance.data.home._id;

    // Add variable to hold activity counts
    instance.activityLevelCounts = new ReactiveVar();

    instance.autorun(function () {
      // Get current home residents
      const homeCurrentResidentIds = ReactiveMethod.call("getCurrentHomeResidentIds", instance.homeId);

      // Retrieve home resident activity level counts from server
      const activityLevelCounts = ReactiveMethod.call("getHomeActivityLevelCounts", instance.homeId);

      // Make sure activity level counts exist
      if (activityLevelCounts && homeCurrentResidentIds) {
        // Get count of home current residents
        const homeCurrentResidentsCount = homeCurrentResidentIds.length;

        /*
        Re-structure activity level counts data to an object containing:
        type: the type of activity level (inactive, semiActive, active)
        count: the number of residents with a given activity level
        homePercentage: percengage of home residents with the activity level
        */
        const activityLevelTypes = _.keys(activityLevelCounts);

        const activityLevelData = _.map(activityLevelTypes, function (type) {
          // Construct an object with the type and count keys
          const activityLevelCountObject = {
            // Activity level class (inactive, semi-active, active)
            type: type,
            // Number of residents in activity class
            count: activityLevelCounts[type],
            // Percentage of home residents fallint into activity level class
            homePercentage: activityLevelCounts[type] / homeCurrentResidentsCount
          };

          return activityLevelCountObject;
        });

        // Update the reactive variable, to trigger the graph to render
        instance.activityLevelCounts.set(activityLevelData);
      }
    });
  });

Template.singleHomeActivityStatus.onRendered(function () {
  // Get reference to template instance
  const instance = this;

  // Get home ID
  const homeId = instance.homeId;

  /*
  Set up chart
  */

  // Set up ID string for chart element
  const svgId = `#activityLevelCountsChart-${homeId}`;

  // Get reference to chart element
  const svg = dimple.newSvg(svgId, 200, 100);

  // Initialize chart with empty data array
  const activityLevelsChart = new dimple.chart(svg, []);

  // Set chart boundaries
  activityLevelsChart.setBounds("10%", "5%", "80%", "70%");

  // Add counts to x axis
  activityLevelsChart.addMeasureAxis("x", "count");
});
<|endoftext|>


<commit_before>/*
 * This file is part of COMPASS. It is subject to the license terms in
 * the LICENSE file found in the top-level directory of this distribution.
 * (Also available at http://www.apache.org/licenses/LICENSE-2.0.txt)
 * You may not use this file except in compliance with the License.
 */
XML3D.tools.namespace("COMPASS");

(function() {
	"use strict";

	COMPASS.CADExamineController = new XML3D.tools.Class(XML3D.tools.MouseExamineController, {
		_createControls: function(options) {
			return {
				rotate: options.controls.rotate || XML3D.tools.MOUSEBUTTON_MIDDLE,
				dolly: options.controls.dolly || XML3D.tools.MOUSEBUTTON_RIGHT
			};
		},

		_toggleAttached: function(doAttach) {
			this._ensureWheelCallback();
			var regFn;
			if (doAttach) {
				regFn =  this._eventDispatcher.on.bind(this._eventDispatcher);
				document.addEventListener("wheel", this._wheelCallback, true);
			} else {
				regFn = this._eventDispatcher.off.bind(this._eventDispatcher);
				document.removeEventListener("wheel", this._wheelCallback, true);
			}
			regFn(this._targetXml3d, "mousedown", this.callback("_onXML3DMouseDown"));
			regFn(document, "mousemove", this.callback("_onDocumentMouseMove"));
			regFn(document, "mouseup", this.callback("_onDocumentMouseUp"));
		},

		_ensureWheelCallback: function() {
			if (!this._wheelCallback) {
				this._wheelCallback = this._onXML3DScroll.bind(this);
			}
		},

		_createMouseEventDispatcher: function() {
			var disp = new XML3D.tools.util.EventDispatcher();
			return disp;
		},

		_onXML3DScroll: function(evt){
			if(evt.target.tagName !== "CANVAS" || this._currentAction !== this.NONE){
				return;
			}
			var deltaSign = evt.deltaY / Math.abs(evt.deltaY);
			var delta = deltaSign * this._wheelFovFactor;
			this.fov(delta);
			evt.stopImmediatePropagation();
		},

		onDragStart: function(action) {
			switch (action.evt.buttons) {
				case 4: /* middle only */
					if (action.evt.shiftKey && !action.evt.ctrlKey) {
						this._currentAction = this.PAN;
					} else if (!action.evt.shiftKey && action.evt.ctrlKey) {
						this._currentAction = this.DOLLY;
					} else {
						this._currentAction = this.ROTATE;
					}
					break;
				case 5: /* left + middle */
					this._currentAction = this.DOLLY;
					break;
				case 6: /* right + middle */
					this._currentAction = this.PAN;
					break;
				default:
					this._currentAction = this.NONE;
			}
		},

		onDrag: function(action) {
			switch (this._currentAction) {
				case this.ROTATE:
					this.behavior.rotateByAngles(
					        -action.delta.y * this._rotateFactor,
					        -action.delta.x * this._rotateFactor);
					break;
				case this.PAN:
					this.pan(action.delta.x * this._panFactor,
					         action.delta.y * this._panFactor);
					break;
				case this.DOLLY:
					var delta = action.delta.y - action.delta.x;
					this.fov(delta * this._fovFactor);
					break;
				default:
					this._currentAction = this.NONE;
			}
		},

		onDragEnd: function() {
			this._currentAction = this.NONE;
		},

		pan: function(deltaRight, deltaUp) {
			var cameraUp = this.upDirection();
			var cameraIn = this.behavior.getLookDirection();
			var cameraRight = cameraUp.cross(cameraIn);
			var movement = cameraUp.scale(deltaUp).add(cameraRight.scale(deltaRight));
			var originalDistance = this.behavior._getDistanceToExamineOrigin();
			var newExamine = this.behavior.getExamineOrigin().add(movement);
			var newPosition = this.behavior.target.getPosition().add(movement);
			this.behavior._examineOrigin.set(newExamine);
			this.behavior._setTargetPosition(newPosition);
			var newDistance = this.behavior._getDistanceToExamineOrigin();
			if (Math.abs(originalDistance - newDistance) > 0.01) {
				console.warn("examine distance changed while panning!");
			}
		},

		upDirection: function() {
			var curRot = this.behavior.target.getOrientation();
			var defaultUp = new window.XML3DVec3(0, 1, 0);
			var upDirection = curRot.rotateVec3(defaultUp).normalize();
			return upDirection;
		},

		fov: function(deltaFoV) {
			var view = this.target.object.querySelector("view");
			if (view.fieldOfView) {
				// needs to be clamped to avoid mirroring the view.
				var lowClamp = Math.max(view.fieldOfView + deltaFoV, 1e-11);
				var newFov = Math.min(Math.PI-(1e-11), lowClamp);
				view.fieldOfView = newFov;
			}
		},

		setMoveSpeed: function(moveFactor) {
			var f = 2 * Math.sqrt(moveFactor);
			this._panFactor = 50 * f;
			this._fovFactor = 5 * f;
			this._wheelFovFactor = 0.01 * f;
			this._rotateFactor = 0.5 * f;
		},

		PAN: "bogusStringIndicatingPanMode"
	});

	COMPASS.CameraController = new XML3D.tools.Singleton({
		activeController: null,
		viewGroup: null,
		cameraSensitivity: 1,

		initialize: function() {
			return;
		},

		disableCamera: function() {
			this.activeController.detach();
		},

		enableCamera: function() {
			this.activeController.attach();
		},

		switchToFlyCamera: function() {
			this.activeController.detach();
			this.activeController = this._createFlyController();
			this.activeController.attach();
			this._setCameraSensivityOfController();
		},

		switchToOrbitCamera: function() {
			this.activeController.detach();
			this.activeController = this._createOrbitController();
			this.activeController.attach();
			this._setCameraSensivityOfController();
		},

		resetCameraPosition: function() {
			var xml3d = COMPASS.Editor.xml3dProducer.getXML3DElement();
			var sceneBoundingBox = xml3d.getBoundingBox();
			this._setCameraToEncloseBoundingBox(sceneBoundingBox);
		},

		_getDimensionsOfBoundingBox: function(scenebbox) {
			var dims = {};
			dims.x = Math.abs(scenebbox.max.x - scenebbox.min.x);
			dims.y = Math.abs(scenebbox.max.y - scenebbox.min.y);
			dims.z = Math.abs(scenebbox.max.z - scenebbox.min.z);
			return dims;
		},

		_setCameraToEncloseBoundingBox: function(sceneBBox) {
			var sceneDimensions = this._getDimensionsOfBoundingBox(sceneBBox);
			var $viewGroupTransform = $(this.viewGroup.getAttribute("transform"));
			// Create a cube out of the largest scene dimension and position the camera at the top looking down at a 45 degree angle
			var longestSide = Math.max(Math.max(sceneDimensions.x, sceneDimensions.y), sceneDimensions.z);
			var center = sceneBBox.center();
			var x = center.x;
			var y = center.y + longestSide;
			var z = center.z + longestSide;
			if (isNaN(x) || isNaN(y) || isNaN(z)) {
				// Scene dimensions are invalid, set a default camera position
				$viewGroupTransform.attr("translation", "0 0 10");
				$viewGroupTransform.attr("rotation", "1 0 0 0");
			} else {
				$viewGroupTransform.attr("translation", x + " "+ y + " " + z);
				$viewGroupTransform.attr("rotation", "1 0 0 -0.785");
			}
			if (this.activeController.behavior._setExamineOrigin) {
				this.activeController.behavior._setExamineOrigin(center);
				this.activeController.behavior._setDistanceToExamineOrigin(Math.sqrt(longestSide*longestSide + longestSide*longestSide));
			}
		},

		createInitialCameraController: function(aopCameraGroup) {
			this.viewGroup = aopCameraGroup;
			this.activeController = this._createFlyController();
			this.activeController.attach();
			return aopCameraGroup;
		},

		_createOrbitController: function() {
			return new COMPASS.CADExamineController(this.viewGroup, {
				rotateSpeed: 5
			});
		},

		_createFlyController: function() {
			return new XML3D.tools.MouseKeyboardFlyController(this.viewGroup, {
				rotateSpeed: 5,
				controls: {
					rotationActivator: XML3D.tools.MOUSEBUTTON_RIGHT
				}
			});
		},

		_setCameraSensivityOfController: function(){
			var speed = Math.pow(2, this.cameraSensitivity / 3);
			if (this.activeController.setMoveSpeed) {
				this.activeController.setMoveSpeed(speed);
			} else {
				 //Needs a factor 100 to make it behave the same as moveSpeed for the fly controller
				this.activeController.setDollySpeed(speed * 100);
			}
		},

		onCameraSensitivityChanged: function() {
			this.cameraSensitivity = $("input[id$='camera-sensitivity-input']").val();
			this._setCameraSensivityOfController();
			$("input[id$='camera-sensitivity-label']").val(this.cameraSensitivity);
		},

		moveCameraToCurrentlySelectedSceneNode: function(){
			var boundingBox = this._createBoundingBoxOfListOfGroups(COMPASS.Editor.selectedSceneNodeHolder.$selectedGroups);
			if(!boundingBox || boundingBox.isEmpty()){
				return;
			}
			this._setCameraToEncloseBoundingBox(boundingBox);
		},

		_createBoundingBoxOfListOfGroups: function(selectedGroups){
			var index = 0;
			if(!selectedGroups || !selectedGroups[index] || !selectedGroups[index].getBoundingBox){
				return undefined;
			}
			var overallBoundingBox = selectedGroups[index].getBoundingBox();
			for(index = 1; index < selectedGroups.length; index++){
				if(!selectedGroups[index] || !selectedGroups[index].getBoundingBox){
					continue;
				}
				var groupBoundingBox = selectedGroups[index].getBoundingBox();
				overallBoundingBox.extend(groupBoundingBox);
			}
			return overallBoundingBox;
		}

	});

	$.aop.after( {target: COMPASS.XML3DProducer, method: "_createDefaultCamera"}, COMPASS.CameraController.createInitialCameraController.bind(COMPASS.CameraController) );
	$.aop.after( {target: XML3D.tools.MouseKeyboardFlyController, method: "detach"},
		function() {
			$("button[id$='fly-camera-button']").removeClass("compass-button-active");
		}
	);
	$.aop.after({target: XML3D.tools.MouseKeyboardFlyController, method: "attach"},
		function() {
			$("button[id$='fly-camera-button']").addClass("compass-button-active");
		}
	);
	$.aop.after({target: XML3D.tools.MouseExamineController, method: "detach"},
		function() {
			$("button[id$='orbit-camera-button']").removeClass("compass-button-active");
		}
	);
	$.aop.after({target: XML3D.tools.MouseExamineController, method: "attach"},
		function() {
			$("button[id$='orbit-camera-button']").addClass("compass-button-active");
		}
	);
})();
<commit_msg>examine controller gets its special set of speed values hand-tuned<commit_after>/*
 * This file is part of COMPASS. It is subject to the license terms in
 * the LICENSE file found in the top-level directory of this distribution.
 * (Also available at http://www.apache.org/licenses/LICENSE-2.0.txt)
 * You may not use this file except in compliance with the License.
 */
XML3D.tools.namespace("COMPASS");

(function() {
	"use strict";

	COMPASS.CADExamineController = new XML3D.tools.Class(XML3D.tools.MouseExamineController, {
		_createControls: function(options) {
			return {
				rotate: options.controls.rotate || XML3D.tools.MOUSEBUTTON_MIDDLE,
				dolly: options.controls.dolly || XML3D.tools.MOUSEBUTTON_RIGHT
			};
		},

		_toggleAttached: function(doAttach) {
			this._ensureWheelCallback();
			var regFn;
			if (doAttach) {
				regFn =  this._eventDispatcher.on.bind(this._eventDispatcher);
				document.addEventListener("wheel", this._wheelCallback, true);
			} else {
				regFn = this._eventDispatcher.off.bind(this._eventDispatcher);
				document.removeEventListener("wheel", this._wheelCallback, true);
			}
			regFn(this._targetXml3d, "mousedown", this.callback("_onXML3DMouseDown"));
			regFn(document, "mousemove", this.callback("_onDocumentMouseMove"));
			regFn(document, "mouseup", this.callback("_onDocumentMouseUp"));
		},

		_ensureWheelCallback: function() {
			if (!this._wheelCallback) {
				this._wheelCallback = this._onXML3DScroll.bind(this);
			}
		},

		_createMouseEventDispatcher: function() {
			var disp = new XML3D.tools.util.EventDispatcher();
			return disp;
		},

		_onXML3DScroll: function(evt){
			if(evt.target.tagName !== "CANVAS" || this._currentAction !== this.NONE){
				return;
			}
			var deltaSign = evt.deltaY / Math.abs(evt.deltaY);
			var delta = deltaSign * this._wheelFovFactor;
			this.fov(delta);
			evt.stopImmediatePropagation();
		},

		onDragStart: function(action) {
			switch (action.evt.buttons) {
				case 4: /* middle only */
					if (action.evt.shiftKey && !action.evt.ctrlKey) {
						this._currentAction = this.PAN;
					} else if (!action.evt.shiftKey && action.evt.ctrlKey) {
						this._currentAction = this.DOLLY;
					} else {
						this._currentAction = this.ROTATE;
					}
					break;
				case 5: /* left + middle */
					this._currentAction = this.DOLLY;
					break;
				case 6: /* right + middle */
					this._currentAction = this.PAN;
					break;
				default:
					this._currentAction = this.NONE;
			}
		},

		onDrag: function(action) {
			switch (this._currentAction) {
				case this.ROTATE:
					this.behavior.rotateByAngles(
					        -action.delta.y * this._rotateFactor,
					        -action.delta.x * this._rotateFactor);
					break;
				case this.PAN:
					this.pan(action.delta.x * this._panFactor,
					         action.delta.y * this._panFactor);
					break;
				case this.DOLLY:
					var delta = action.delta.y - action.delta.x;
					this.fov(delta * this._fovFactor);
					break;
				default:
					this._currentAction = this.NONE;
			}
		},

		onDragEnd: function() {
			this._currentAction = this.NONE;
		},

		pan: function(deltaRight, deltaUp) {
			var cameraUp = this.upDirection();
			var cameraIn = this.behavior.getLookDirection();
			var cameraRight = cameraUp.cross(cameraIn);
			var movement = cameraUp.scale(deltaUp).add(cameraRight.scale(deltaRight));
			var originalDistance = this.behavior._getDistanceToExamineOrigin();
			var newExamine = this.behavior.getExamineOrigin().add(movement);
			var newPosition = this.behavior.target.getPosition().add(movement);
			this.behavior._examineOrigin.set(newExamine);
			this.behavior._setTargetPosition(newPosition);
			var newDistance = this.behavior._getDistanceToExamineOrigin();
			if (Math.abs(originalDistance - newDistance) > 0.01) {
				console.warn("examine distance changed while panning!");
			}
		},

		upDirection: function() {
			var curRot = this.behavior.target.getOrientation();
			var defaultUp = new window.XML3DVec3(0, 1, 0);
			var upDirection = curRot.rotateVec3(defaultUp).normalize();
			return upDirection;
		},

		fov: function(deltaFoV) {
			var view = this.target.object.querySelector("view");
			if (view.fieldOfView) {
				// needs to be clamped to avoid mirroring the view.
				var lowClamp = Math.max(view.fieldOfView + deltaFoV, 1e-11);
				var newFov = Math.min(Math.PI-(1e-11), lowClamp);
				view.fieldOfView = newFov;
			}
		},

		setMoveSpeed: function(moveFactor) {
			// magic values determined by trial study
			this._panFactor = 5 * Math.pow(2, moveFactor / 6);
			this._fovFactor = 2 * Math.pow(2, moveFactor / 14);
			this._wheelFovFactor = 0.01 * Math.pow(2, moveFactor / 9);
			this._rotateFactor = 0.5 * Math.pow(2, moveFactor / 12);
		},

		PAN: "bogusStringIndicatingPanMode"
	});

	COMPASS.CameraController = new XML3D.tools.Singleton({
		activeController: null,
		viewGroup: null,
		cameraSensitivity: 1,

		initialize: function() {
			return;
		},

		disableCamera: function() {
			this.activeController.detach();
		},

		enableCamera: function() {
			this.activeController.attach();
		},

		switchToFlyCamera: function() {
			this.activeController.detach();
			this.activeController = this._createFlyController();
			this.activeController.attach();
			this._setCameraSensivityOfController();
		},

		switchToOrbitCamera: function() {
			this.activeController.detach();
			this.activeController = this._createOrbitController();
			this.activeController.attach();
			this._setCameraSensivityOfController();
		},

		resetCameraPosition: function() {
			var xml3d = COMPASS.Editor.xml3dProducer.getXML3DElement();
			var sceneBoundingBox = xml3d.getBoundingBox();
			this._setCameraToEncloseBoundingBox(sceneBoundingBox);
		},

		_getDimensionsOfBoundingBox: function(scenebbox) {
			var dims = {};
			dims.x = Math.abs(scenebbox.max.x - scenebbox.min.x);
			dims.y = Math.abs(scenebbox.max.y - scenebbox.min.y);
			dims.z = Math.abs(scenebbox.max.z - scenebbox.min.z);
			return dims;
		},

		_setCameraToEncloseBoundingBox: function(sceneBBox) {
			var sceneDimensions = this._getDimensionsOfBoundingBox(sceneBBox);
			var $viewGroupTransform = $(this.viewGroup.getAttribute("transform"));
			// Create a cube out of the largest scene dimension and position the camera at the top looking down at a 45 degree angle
			var longestSide = Math.max(Math.max(sceneDimensions.x, sceneDimensions.y), sceneDimensions.z);
			var center = sceneBBox.center();
			var x = center.x;
			var y = center.y + longestSide;
			var z = center.z + longestSide;
			if (isNaN(x) || isNaN(y) || isNaN(z)) {
				// Scene dimensions are invalid, set a default camera position
				$viewGroupTransform.attr("translation", "0 0 10");
				$viewGroupTransform.attr("rotation", "1 0 0 0");
			} else {
				$viewGroupTransform.attr("translation", x + " "+ y + " " + z);
				$viewGroupTransform.attr("rotation", "1 0 0 -0.785");
			}
			if (this.activeController.behavior._setExamineOrigin) {
				this.activeController.behavior._setExamineOrigin(center);
				this.activeController.behavior._setDistanceToExamineOrigin(Math.sqrt(longestSide*longestSide + longestSide*longestSide));
			}
		},

		createInitialCameraController: function(aopCameraGroup) {
			this.viewGroup = aopCameraGroup;
			this.activeController = this._createFlyController();
			this.activeController.attach();
			return aopCameraGroup;
		},

		_createOrbitController: function() {
			return new COMPASS.CADExamineController(this.viewGroup, {
				rotateSpeed: 5
			});
		},

		_createFlyController: function() {
			return new XML3D.tools.MouseKeyboardFlyController(this.viewGroup, {
				rotateSpeed: 5,
				controls: {
					rotationActivator: XML3D.tools.MOUSEBUTTON_RIGHT
				}
			});
		},

		_setCameraSensivityOfController: function(){
			if (this.activeController.PAN) {
				this.activeController.setMoveSpeed(this.cameraSensitivity);
			} else {
				var speed = Math.pow(2, this.cameraSensitivity / 3);
				this.activeController.setMoveSpeed(speed);
			}
		},

		onCameraSensitivityChanged: function() {
			this.cameraSensitivity = $("input[id$='camera-sensitivity-input']").val();
			this._setCameraSensivityOfController();
			$("input[id$='camera-sensitivity-label']").val(this.cameraSensitivity);
		},

		moveCameraToCurrentlySelectedSceneNode: function(){
			var boundingBox = this._createBoundingBoxOfListOfGroups(COMPASS.Editor.selectedSceneNodeHolder.$selectedGroups);
			if(!boundingBox || boundingBox.isEmpty()){
				return;
			}
			this._setCameraToEncloseBoundingBox(boundingBox);
		},

		_createBoundingBoxOfListOfGroups: function(selectedGroups){
			var index = 0;
			if(!selectedGroups || !selectedGroups[index] || !selectedGroups[index].getBoundingBox){
				return undefined;
			}
			var overallBoundingBox = selectedGroups[index].getBoundingBox();
			for(index = 1; index < selectedGroups.length; index++){
				if(!selectedGroups[index] || !selectedGroups[index].getBoundingBox){
					continue;
				}
				var groupBoundingBox = selectedGroups[index].getBoundingBox();
				overallBoundingBox.extend(groupBoundingBox);
			}
			return overallBoundingBox;
		}

	});

	$.aop.after( {target: COMPASS.XML3DProducer, method: "_createDefaultCamera"}, COMPASS.CameraController.createInitialCameraController.bind(COMPASS.CameraController) );
	$.aop.after( {target: XML3D.tools.MouseKeyboardFlyController, method: "detach"},
		function() {
			$("button[id$='fly-camera-button']").removeClass("compass-button-active");
		}
	);
	$.aop.after({target: XML3D.tools.MouseKeyboardFlyController, method: "attach"},
		function() {
			$("button[id$='fly-camera-button']").addClass("compass-button-active");
		}
	);
	$.aop.after({target: XML3D.tools.MouseExamineController, method: "detach"},
		function() {
			$("button[id$='orbit-camera-button']").removeClass("compass-button-active");
		}
	);
	$.aop.after({target: XML3D.tools.MouseExamineController, method: "attach"},
		function() {
			$("button[id$='orbit-camera-button']").addClass("compass-button-active");
		}
	);
})();
<|endoftext|>


<commit_before>#pragma strict

var hp : int = 100 ;
var cnt : int = 0 ;
var SE : AudioClip ;
var thirtyattack : AudioClip ;
var sixtyattack : AudioClip ;
var hundredattack : AudioClip ;
var explosion : Transform ;
var move : float ;
var customLabel : GUIStyle ;

function Update () {
  move = Random.Range(1.0 , 3.0) ;

  if(Time.frameCount % 60 == 0)
  {
    /* X軸間での移動 */
    if(move >= 1.0 && move < 1.5)
    {
      transform.position.x -= 8.0 ;
    }
    if(move >= 1.5 && move < 2.0)
    {
      transform.position.x += 8.0 ;
    }

    /* Z軸間での移動 */
    if(move >= 2.0 && move < 2.5)
    {
      transform.position.z -= 8.0 ;
    }
    if(move >= 2.5 && move < 3.0)
    {
      transform.position.z += 8.0 ;
    }
  }

  /* 移動制限 */
  if(transform.position.x <= -10.16566 || transform.position.x >= 10.0684 ||
    transform.position.z <= -15.10404 || transform.position.z >= 10.09297)
  {
    var xPos : float ;
    var zPos : float ;
    xPos = Mathf.Clamp(transform.position.x , -18.16566 , 18.0684) ;
    zPos = Mathf.Clamp(transform.position.z , -15.10404 , 10.09297) ;
    transform.position = Vector3(xPos , 0 , zPos) ;
  }
}

function OnCollisionEnter(col : Collision) {
  hp -= 1 ;
  Instantiate(explosion , transform.position , transform.rotation) ;

  cnt += 1 ;

  if(cnt == 30)
  {
    AudioSource.PlayClipAtPoint(thirtyattack , transform.position) ;
  }
  if(cnt == 60)
  {
    AudioSource.PlayClipAtPoint(sixtyattack , transform.position) ;
  }

  if(hp == 0)
  {
    Destroy(gameObject) ;
    Instantiate(explosion , transform.position , transform.rotation) ;
    AudioSource.PlayClipAtPoint(SE , transform.position) ;
    Application.LoadLevel(16) ;   //LastBoss_Clear
  }
}

function OnGUI () {
  GUI.Label(Rect(Screen.width / 2 - 350 , Screen.height / 2 - 320, 200 , 50) , "HP : " + hp , customLabel) ;
}
<commit_msg>Update HASAMA2.js<commit_after>#pragma strict

var hp : int = 100 ;
var cnt : int = 0 ;
var SE : AudioClip ;
var thirtyattack : AudioClip ;
var sixtyattack : AudioClip ;
var hundredattack : AudioClip ;
var explosion : Transform ;
var move : float ;
var customLabel : GUIStyle ;

function Update () {
  move = Random.Range(1.0 , 3.0) ;

  if(Time.frameCount % 60 == 0)
  {
    /* X軸間での移動 */
    if(move >= 1.0 && move < 1.5)
    {
      transform.position.x -= 8.0 ;
    }
    if(move >= 1.5 && move < 2.0)
    {
      transform.position.x += 8.0 ;
    }
    if(transform.position.x <= -10.16566)
    {
      transform.position.x += 8.0 ;
    }
    if(transform.position.x >= 10.0684)
    {
      transform.position.x -= 8.0 ;
    }
    /* Z軸間での移動 */
    if(move >= 2.0 && move < 2.5)
    {
      transform.position.z -= 8.0 ;
    }
    if(move >= 2.5 && move < 3.0)
    {
      transform.position.z += 8.0 ;
    }
    if(transform.position.z <= -15.10404)
    {
      transform.position.z += 8.0 ;
    }
    if(transform.position.z >= 10.09297)
    {
      transform.position.z -= 8.0 ;
    }
  }

  /* 移動制限 */
  if(transform.position.x <= -10.16566 || transform.position.x >= 10.0684 ||
    transform.position.z <= -15.10404 || transform.position.z >= 10.09297)
  {
    var xPos : float ;
    var zPos : float ;
    xPos = Mathf.Clamp(transform.position.x , -18.16566 , 18.0684) ;
    zPos = Mathf.Clamp(transform.position.z , -15.10404 , 10.09297) ;
    transform.position = Vector3(xPos , 0 , zPos) ;
  }
}

function OnCollisionEnter(col : Collision) {
  hp -= 1 ;
  Instantiate(explosion , transform.position , transform.rotation) ;

  cnt += 1 ;

  if(cnt == 30)
  {
    AudioSource.PlayClipAtPoint(thirtyattack , transform.position) ;
  }
  if(cnt == 60)
  {
    AudioSource.PlayClipAtPoint(sixtyattack , transform.position) ;
  }

  if(hp == 0)
  {
    Destroy(gameObject) ;
    Instantiate(explosion , transform.position , transform.rotation) ;
    AudioSource.PlayClipAtPoint(SE , transform.position) ;
    Application.LoadLevel(16) ;   //LastBoss_Clear
  }
}

function OnGUI () {
  GUI.Label(Rect(Screen.width / 2 - 350 , Screen.height / 2 - 320, 200 , 50) , "HP : " + hp , customLabel) ;
}
<|endoftext|>


<commit_before>const way = require('senseway')
const pat = require('sensepat')
const wayElem = require('../../lib/wayElem')

module.exports = (model, dispatch) => {
  const timelinePattern = {
    value: way.map(model.timeline, q => q === null ? 0 : q),
    mass: way.map(model.timeline, q => q === null ? 0 : 1)
  }

  const avg = pat.mean(timelinePattern)

  const canvas = way.first(model.timeline, 5)
  const priorHood = way.map(canvas, (q, c) => avg[c])

  return wayElem(priorHood, {
    reversed: true,
    heading: 'Prior Probabilities',
    caption: 'We already know what to expect in general '
      + 'by looking the average of each channel.'
  })
}
<commit_msg>Use pat.mixedToPattern in howPrior<commit_after>const way = require('senseway')
const pat = require('sensepat')
const wayElem = require('../../lib/wayElem')

module.exports = (model, dispatch) => {
  const timelinePat = pat.mixedToPattern(model.timeline)

  const avg = pat.mean(timelinePat)

  const canvas = way.first(model.timeline, 5)
  const priorHood = way.map(canvas, (q, c) => avg[c])

  return wayElem(priorHood, {
    reversed: true,
    heading: 'Prior Probabilities',
    caption: 'We already know what to expect in general '
      + 'by looking the average of each channel.'
  })
}
<|endoftext|>


<commit_before>//(c) 2014 Indexia, Inc.
import Em from 'ember';
import WithConfigMixin from 'ember-idx-utils/mixin/with-config';
import StyleBindingsMixin from 'ember-idx-utils/mixin/style-bindings';

/**
 * `{{em-tabs}}` component.
 *
 * The top level component for rendering tabs and their panes.
 *
 * Simplest usage:
 *
 * ```handlebars
 * {{#em-tabs}}
 *    {{#em-tab-list}}
 *       {{#em-tab}}ral{{/em-tab}}
 *       {{#em-tab}}Security{{/em-tab}}
 *       {{#em-tab}}Advanced{{/em=tab}}
 *    {{em-tab-list}}
 * {{/em-tabs}}
 * ```
 *
 * @class Tabs
 * @public
 */
export default Em.Component.extend(WithConfigMixin, StyleBindingsMixin, {
  classNameBindings: ['styleClasses'],
  styleClasses: (function() {
    var _ref;
    return (_ref = this.get('config.tabs.tabsClasses')) != null ? _ref.join(" ") : void 0;
  }).property(),
  styleBindings: ['height'],

  /**
   * A list of tab panels
   *
   * @property panels
   * @private
   * @type Array
   */
  panels: void 0,

  /**
   * A {{#crossLink "TabList"}}{{/crossLink}} component instance.
   *
   * @property tabList
   * @type TabList
   */
  tabList: void 0,

  /**
   * The selected tab instance.
   *
   * @property selectedTab
   * @type Tab
   * @private
   * @see Tab
   *
   */
  selected: void 0,

  /**
   * The index of the selected tab
   *
   * @property 'selected-idx'
   * @type Number
   */
  'selected-idx': 0,

  /**
   * Select the given tab.
   *
   * @method select
   * @param {Object} a tab instance to select.
   * @see selectedTab
   * @see selected-idx
   */
  select: function(tab) {
    if (!tab) {
      return;
    }
    Em.debug("Selecting tab: " + (tab.get('index')));
    this.set('selected', tab);
    return this.set('selected-idx', tab.get('index'));
  },

  /**
   * Initialize the tab panels array
   *
   * @method initTabPanels
   */
  initTabPanels: (function() {
    return this.set('panels', Em.ArrayProxy.create({
      content: []
    }));
  }).on('init'),

  /**
   * Set the specified `TabList` instance.
   *
   * @method setTabList
   * @private
   */
  setTabList: function(tabList) {
    return this.set('tabList', tabList);
  },

  /**
   * Add the given `TabPanel` instance to the tabs panels.
   *
   * @method addTabPanel
   * @param panel {Object} The `TabPanel` instance to add.
   */
  addTabPanel: function(panel) {
    return this.get('panels').addObject(panel);
  },

  /**
   * Remove the given `TabPanel` instance from the tabs panels.
   *
   * @method removeTabPanel.
   * @param panel {Object} The `TabPanel` instance to remove.
   */
  removeTabPanel: function(panel) {
    return this.get('panels').removeObject('panel');
  }
});<commit_msg>Correct panel removal<commit_after>//(c) 2014 Indexia, Inc.
import Em from 'ember';
import WithConfigMixin from 'ember-idx-utils/mixin/with-config';
import StyleBindingsMixin from 'ember-idx-utils/mixin/style-bindings';

/**
 * `{{em-tabs}}` component.
 *
 * The top level component for rendering tabs and their panes.
 *
 * Simplest usage:
 *
 * ```handlebars
 * {{#em-tabs}}
 *    {{#em-tab-list}}
 *       {{#em-tab}}ral{{/em-tab}}
 *       {{#em-tab}}Security{{/em-tab}}
 *       {{#em-tab}}Advanced{{/em=tab}}
 *    {{em-tab-list}}
 * {{/em-tabs}}
 * ```
 *
 * @class Tabs
 * @public
 */
export default Em.Component.extend(WithConfigMixin, StyleBindingsMixin, {
  classNameBindings: ['styleClasses'],
  styleClasses: (function() {
    var _ref;
    return (_ref = this.get('config.tabs.tabsClasses')) != null ? _ref.join(" ") : void 0;
  }).property(),
  styleBindings: ['height'],

  /**
   * A list of tab panels
   *
   * @property panels
   * @private
   * @type Array
   */
  panels: void 0,

  /**
   * A {{#crossLink "TabList"}}{{/crossLink}} component instance.
   *
   * @property tabList
   * @type TabList
   */
  tabList: void 0,

  /**
   * The selected tab instance.
   *
   * @property selectedTab
   * @type Tab
   * @private
   * @see Tab
   *
   */
  selected: void 0,

  /**
   * The index of the selected tab
   *
   * @property 'selected-idx'
   * @type Number
   */
  'selected-idx': 0,

  /**
   * Select the given tab.
   *
   * @method select
   * @param {Object} a tab instance to select.
   * @see selectedTab
   * @see selected-idx
   */
  select: function(tab) {
    if (!tab) {
      return;
    }
    Em.debug("Selecting tab: " + (tab.get('index')));
    this.set('selected', tab);
    return this.set('selected-idx', tab.get('index'));
  },

  /**
   * Initialize the tab panels array
   *
   * @method initTabPanels
   */
  initTabPanels: (function() {
    return this.set('panels', Em.ArrayProxy.create({
      content: []
    }));
  }).on('init'),

  /**
   * Set the specified `TabList` instance.
   *
   * @method setTabList
   * @private
   */
  setTabList: function(tabList) {
    return this.set('tabList', tabList);
  },

  /**
   * Add the given `TabPanel` instance to the tabs panels.
   *
   * @method addTabPanel
   * @param panel {Object} The `TabPanel` instance to add.
   */
  addTabPanel: function(panel) {
    return this.get('panels').addObject(panel);
  },

  /**
   * Remove the given `TabPanel` instance from the tabs panels.
   *
   * @method removeTabPanel.
   * @param panel {Object} The `TabPanel` instance to remove.
   */
  removeTabPanel: function(panel) {
    return this.get('panels').removeObject(panel);
  }
});
<|endoftext|>


<commit_before>var common = require('./_common.js');
var Test = common.Test;
var MIME = require('../index.js');
var namespace = 'MIME.decodeHeaderAddresses';
var tests = [
  [
    undefined,
    [],
    null
  ],
  [
    '',
    [],
    null
  ],
  [
    [],
    [],
    null
  ],
  [
    ['test1@(comment)test.com,\t,\t', '""\r\n test2(,)@(;)(<)test.com'],
    [
      { name: '', email: 'test1@test.com' },
      { name: '', email: 'test2@test.com' }
    ],
    null
  ]
];
tests.forEach(
  function(test) {
    var key = JSON.stringify(test[0]);
    if (test[0] === undefined) {
      var buffer = test[0];
    } else if (typeof test[0] === 'string') {
      var buffer = Buffer.from(test[0], 'binary');
    } else if (Array.isArray(test[0])) {
      var buffer = test[0].map(
        function(value) {
          if (typeof value === 'string') return Buffer.from(value);
          return value;
        }
      );
    }
    try {
      var actual = MIME.decodeHeaderAddresses(buffer);
      var actualError = null;
    } catch (error) {
      var actual = null;
      var actualError = error.message;
    }
    Test.equal(actual, test[1], namespace, key);
    Test.equal(actualError, test[2], namespace, key + ': error');
  }
);
<commit_msg>Add tests and comments regarding multiple angle-addr's<commit_after>var common = require('./_common.js');
var Test = common.Test;
var MIME = require('../index.js');
var namespace = 'MIME.decodeHeaderAddresses';
var tests = [
  [
    undefined,
    [],
    null
  ],
  [
    '',
    [],
    null
  ],
  [
    [],
    [],
    null
  ],
  [
    ['test1@(comment)test.com,\t,\t', '""\r\n test2(,)@(;)(<)test.com'],
    [
      { name: '', email: 'test1@test.com' },
      { name: '', email: 'test2@test.com' }
    ],
    null
  ],
  [
    'Fake <trusted@sender.com> <fake@scam.com>',
    [
      {
        // Multiple angle-addr's should never occur and are suspicious:
        // We split an address on angle brackets outside quotes.
        // This means that the pseudo address which will end up part of the name
        // will lose its angle brackets, and at first glance, it might seem that
        // we are causing user data to be lost.
        // However, if angle brackets exist outside quotes, there should only
        // be a single pair in terms of the spec, because there can only be one
        // angle-addr, and a phrase atom cannot contain angle brackets.
        // Therefore, removing the extra angle brackets is not a problem, since
        // the case is already exceptional.
        // TO DO: We should probably detect and reject multiple angle-addr's.
        name: 'Fake trusted@sender.com',
        email: 'fake@scam.com'
      }
    ],
    null
  ],
  [
    '"QuotedFake <trusted@sender.com>" <fake@scam.com>',
    [
      {
        name: 'QuotedFake <trusted@sender.com>',
        email: 'fake@scam.com'
      }
    ],
    null
  ]
];
tests.forEach(
  function(test) {
    var key = JSON.stringify(test[0]);
    if (test[0] === undefined) {
      var buffer = test[0];
    } else if (typeof test[0] === 'string') {
      var buffer = Buffer.from(test[0], 'binary');
    } else if (Array.isArray(test[0])) {
      var buffer = test[0].map(
        function(value) {
          if (typeof value === 'string') return Buffer.from(value);
          return value;
        }
      );
    }
    try {
      var actual = MIME.decodeHeaderAddresses(buffer);
      var actualError = null;
    } catch (error) {
      var actual = null;
      var actualError = error.message;
    }
    Test.equal(actual, test[1], namespace, key);
    Test.equal(actualError, test[2], namespace, key + ': error');
  }
);
<|endoftext|>


<commit_before>/* @flow */

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { actions } from 'react-redux-form';
import _get from 'lodash.get';
import math from 'mathjs';

export const convert = (value: ?ValueUnitType, targetUnit: ?string): number => {
  if (!value || !value.value || !value.unit) { return null; }
  if (!targetUnit) { return null; }
  if (value.unit === targetUnit) { return parseFloat(value.value); }

  return math.unit(value.value, value.unit).toNumber(targetUnit);
};

class TextUnitInputComponent extends Component {
  constructor(props) {
    super(props);

    this.state = {
      unit: props.units[0],
    };
  }

  state: {
    unit: string,
  };

  props: {
    label: string,
    units: Array<string>,
    value: ValueUnitType,
    style: Object,
    precision: number,
    placeholder: ?string,
    onChange: (value: ValueUnitType) => void,
  };

  render() {
    const {
      label,
      units,
      value,
      style,
      precision,
      placeholder,
      onChange,
    } = this.props;

    const converted = convert(value, this.state.unit);
    const inputValue = converted
      && (precision ? converted.toFixed(precision) : converted.toString())
      || '';

    return (

        {label && {label}}

          <input
            type="number"
            className="input"
            style={style}
            value={inputValue}
            step={precision ? 10 ** -precision : null}
            placeholder={placeholder}
            onChange={(e) => onChange({ value: e.target.value, unit: this.state.unit })}
          />

            <select
              tabIndex="-1"
              value={this.state.unit}
              onChange={e => this.setState({ unit: e.target.value })}
            >
            {units.map(unit =>
              <option key={unit} value={unit}>{unit}</option>
            )}
            </select>

    );
  }
}

const mapStateToProps = (state, ownProps) => ({
  value: _get(state, ownProps.model),
});
const mapDispatchToProps = (dispatch, ownProps) => ({
  onChange: v => dispatch(actions.change(ownProps.model, v)),
});

export const TextUnitInput = connect(
  mapStateToProps, mapDispatchToProps
)(TextUnitInputComponent);
<commit_msg>(refs #111) Modify TextUnitInput not to use ** operator but Math.pow()<commit_after>/* @flow */

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { actions } from 'react-redux-form';
import _get from 'lodash.get';
import math from 'mathjs';

export const convert = (value: ?ValueUnitType, targetUnit: ?string): ?number => {
  if (!value || !value.value || !value.unit) { return null; }
  if (!targetUnit) { return null; }
  if (value.unit === targetUnit) { return parseFloat(value.value); }

  return math.unit(value.value, value.unit).toNumber(targetUnit);
};

class TextUnitInputComponent extends Component {
  constructor(props) {
    super(props);

    this.state = {
      unit: props.units[0],
    };
  }

  state: {
    unit: string,
  };

  props: {
    label: string,
    units: Array<string>,
    value: ValueUnitType,
    style: Object,
    precision: number,
    placeholder: ?string,
    onChange: (value: ValueUnitType) => void,
  };

  render() {
    const {
      label,
      units,
      value,
      style,
      precision,
      placeholder,
      onChange,
    } = this.props;

    const converted = convert(value, this.state.unit);
    const inputValue = converted
      && (precision ? converted.toFixed(precision) : converted.toString())
      || '';

    return (

        {label && {label}}

          <input
            type="number"
            className="input"
            style={style}
            value={inputValue}
            step={precision ? Math.pow(10, -precision) : null}
            placeholder={placeholder}
            onChange={(e) => onChange({ value: e.target.value, unit: this.state.unit })}
          />

            <select
              tabIndex="-1"
              value={this.state.unit}
              onChange={e => this.setState({ unit: e.target.value })}
            >
            {units.map(unit =>
              <option key={unit} value={unit}>{unit}</option>
            )}
            </select>

    );
  }
}

const mapStateToProps = (state, ownProps) => ({
  value: _get(state, ownProps.model),
});
const mapDispatchToProps = (dispatch, ownProps) => ({
  onChange: v => dispatch(actions.change(ownProps.model, v)),
});

export const TextUnitInput = connect(
  mapStateToProps, mapDispatchToProps
)(TextUnitInputComponent);
<|endoftext|>


<commit_before>var SYUILOUI = {};

SYUILOUI.Tab = function($tabList) {
	var $tabContents = [];

	$tabList.find('li').each(function(i, elem) {
		var $tabListItem = $(elem);
		var id = $tabListItem.find('a').attr('href');
		$tabContents.push($(id));
		$tabListItem.addClass('unactive');

		$tabListItem.click(function() {
			var num = $tabList.find('li').index(this);
			$tabList.find('li').removeClass('active');
			$(this).addClass('active');

			$.each(tabContents, function() {
				$(this).css("display", "none");
			});

			$tabContents[num].css("display", "block");
		});
	});

	$tabContents.each(function(i, elem) {
		var $tabContent = $(elem);
		$tabContent.css("display", "none");
	});

	$tabList[0].attr('class', 'active');
	$tabContent[0].css("display", "block");
}
<commit_msg>Fix typo<commit_after>var SYUILOUI = {};

SYUILOUI.Tab = function($tabList) {
	var $tabContents = [];

	$tabList.find('li').each(function(i, elem) {
		var $tabListItem = $(elem);
		var id = $tabListItem.find('a').attr('href');
		$tabContents.push($(id));
		$tabListItem.addClass('unactive');

		$tabListItem.click(function() {
			var num = $tabList.find('li').index(this);
			$tabList.find('li').removeClass('active');
			$(this).addClass('active');

			$.each($tabContents, function() {
				$(this).css("display", "none");
			});

			$tabContents[num].css("display", "block");
		});
	});

	$tabContents.each(function(i, elem) {
		var $tabContent = $(elem);
		$tabContent.css("display", "none");
	});

	$tabList[0].attr('class', 'active');
	$tabContent[0].css("display", "block");
}
<|endoftext|>