<commit_before>// ==========================================================================
// Project:   The M-Project - Mobile HTML5 Application Framework
// Copyright: (c) 2010 M-Way Solutions GmbH. All rights reserved.
// Creator:   Dominik
// Date:      02.12.2010
// License:   Dual licensed under the MIT or GPL Version 2 licenses.
//            http://github.com/mwaylabs/The-M-Project/blob/master/MIT-LICENSE
//            http://github.com/mwaylabs/The-M-Project/blob/master/GPL-LICENSE
// ==========================================================================

/**
 * A constant value for horizontal alignment.
 *
 * @type String
 */
M.HORIZONTAL = 'horizontal';

/**
 * A constant value for vertical alignment.
 *
 * @type String
 */
M.VERTICAL = 'vertical';

/**
 * @class
 *
 * A button group is a vertically or / and horizontally aligned group of buttons. There
 * are basically three different types of a button group:
 *
 * - horizontally aligned buttons
 *     1 - 2 - 3
 *
 * - vertically aligned buttons
 *     1
 *     |
 *     2
 *     |
 *     3
 *
 * - horizontally and vertically aligned buttons
 *     1 - 2
 *     |   |
 *     3 - 4
 *
 * @extends M.View
 */
M.ButtonGroupView = M.View.extend(
/** @scope M.ButtonGroupView.prototype */ {

    /**
     * The type of this object.
     *
     * @type String
     */
    type: 'M.ButtonGroupView',

    /**
     * This property determines whether to render the button group horizontally
     * or vertically. Default: horizontal.
     *
     * Possible values are:
     * - M.HORIZONTAL: horizontal
     * - M.VERTICAL: vertical
     *
     * @type String
     */
    direction: M.HORIZONTAL,

    /**
     * Determines whether to display the button group view 'inset' or at full width.
     *
     * @type Boolean
     */
    isInset: YES,

    /**
     * Determines whether to display the button group compact, i.e. without top/bottom
     * margin. This property only is relevant in combination with multiple lines of
     * buttons (c.p.: buttonsPerLine property).
     *
     * @type Boolean
     */
    isCompact: YES,

    /**
     * This property, if set, defines how many buttons are rendered per line. If there
     * are more buttons defined that fitting into one line, the following buttons are
     * rendered into a new line. Make sure, the number of your buttons is divisible by
     * the number of buttons per line, since only full lines are displayed. So if you
     * for example specify 5 buttons and 2 buttons per line, the fifth button won't be
     * visible.
     *
     * If e.g. 4 buttons are specified and this property is set to 2, the rendering will
     * be as follows:
     *
     *     1 -- 2
     *     3 -- 4
     *
     * @type Number
     */
    buttonsPerLine: null,

    /**
     * This property is used to internally store the number of lines that are necessary
     * to render all buttons according to the buttonsPerLine property.
     *
     * @private
     * @type Number
     */
    numberOfLines: null,

    /**
     * This property refers to the currently rendered line, if there is more than one.
     *
     * @private
     * @type Number
     */
    currentLine: null,

    /**
     * This property contains an array of html ids referring to the several lines of grouped
     * buttons, if there is more than one at all.
     *
     * @private
     * @type Array
     */
    lines: null,

    /**
     * This property contains a reference to the currently selected button.
     *
     * @private
     * @type Object
     */
    activeButton: null,

    /**
     * This property determines whether the buttons of this button group are selectable or not. If
     * set to YES, a click on one of the buttons will set this button as the currently active button
     * and automatically change its styling to visualize its selection.
     *
     * @type Boolean
     */
    isSelectable: YES,

    /**
     * This property specifies the recommended events for this type of view.
     *
     * @type Array
     */
    recommendedEvents: ['change'],

    /**
     * Renders a button group as a div container and calls the renderChildViews
     * method to render the included buttons.
     *
     * @private
     * @returns {String} The button group view's html representation.
     */
    render: function() {
        /* check if multiple lines are necessary before rendering */
        if(this.childViews) {
            var childViews = this.getChildViewsAsArray();
            if(this.buttonsPerLine && this.buttonsPerLine < childViews.length) {
                var numberOfButtons = 0;
                for(var i in childViews) {
                    if(this[childViews[i]] && this[childViews[i]].type === 'M.ButtonView') {
                        numberOfButtons = numberOfButtons + 1;
                    }
                }
                if(this.buttonsPerLine < numberOfButtons) {
                    this.numberOfLines = M.Math.round(numberOfButtons / this.buttonsPerLine, M.FLOOR);
                }
            }
        }

        /* if there are multiple lines, render multiple horizontally aligned button groups */
        if(this.numberOfLines) {
            /* set the direction to horizontally, no matter what it was set to before */
            this.direction = M.HORIZONTAL;

            /* this is a wrapper for the multiple button groups.
               if it is not inset, assign css class 'ui-listview' for clearing the padding of the surrounding element */
            this.html += '
';

            /* create a button group for every line */
            this.lines = [];
            for(var i = 0; i < this.numberOfLines; i++) {
                this.currentLine = i + 1;
                /* store current line in lines property for use in renderChildViews() */
                this.lines.push(this.id + '_' + i);

                this.html += '
 0 && i < this.numberOfLines - 1) {
                        this.html += this.isInset ? ' style="margin:0px 0px 0px 0px"' : ' style="margin:0px"';
                    } else if(i < this.numberOfLines) {
                        this.html += this.isInset ? ' style="margin-top:0px"' : ' style="margin:0px"';
                    }
                }

                this.html += '>';

                /* render the buttons for the current line */
                this.renderChildViews();

                this.html += '
';
            }
            this.html += '
';
        } else {
            this.html += '
';

            this.renderChildViews();

            this.html += '
';
        }

        return this.html;
    },

    /**
     * Triggers render() on all children of type M.ButtonGroupView.
     *
     * @private
     */
    renderChildViews: function() {
        if(this.childViews) {
            var childViews = this.getChildViewsAsArray();
            var currentButtonIndex = 0;

            for(var i in childViews) {
                if(this[childViews[i]] && this[childViews[i]].type === 'M.ButtonView') {
                    currentButtonIndex = currentButtonIndex + 1;

                    if(!this.numberOfLines || M.Math.round(currentButtonIndex / this.buttonsPerLine, M.CEIL) === this.currentLine) {

                        var button = this[childViews[i]];
                        /* reset buttons html, to make sure it doesn't get rendered twice if this is multi button group */
                        button.html = '';

                        button.parentView = this;
                        button.internalEvents = {
                            tap: {
                                target: this,
                                action: 'setActiveButton'
                            }
                        }

                        /* if the buttons are horizontally aligned, compute their width depending on the number of buttons
                           and set the right margin to '-2px' since the jQuery mobile default would cause an ugly gap to
                           the right of the button group */
                        if(this.direction === M.HORIZONTAL) {
                            button.cssStyle = 'margin-right:-2px;width:' + 100 / (this.numberOfLines ? this.buttonsPerLine : childViews.length) + '%';
                        }

                        /* set the button's _name property */
                        this[childViews[i]]._name = childViews[i];

                        /* finally render the button and add it to the button groups html */
                        this.html += this[childViews[i]].render();
                    }
                } else {
                    M.Logger.log('childview of button group is no button.', M.WARN);
                }
            }
        }
    },

    /**
     * This method themes the button group and activates one of the included buttons
     * if its isActive property is set.
     *
     * @private
     */
    theme: function() {
        /* if there are multiple lines of buttons, it's getting heavy */
        if(this.numberOfLines) {

            /* iterate through all lines */
            for(var line in this.lines) {
                line = parseInt(line);

                /* style the current line */
                $('#' + this.lines[line]).controlgroup();
                var childViews = this.getChildViewsAsArray();
                var currentButtonIndex = 0;

                /* if isCompact, iterate through all buttons */
                if(this.isCompact) {
                    for(var i in childViews) {
                        i = parseInt(i);
                        if(this[childViews[i]] && this[childViews[i]].type === 'M.ButtonView') {
                            currentButtonIndex = currentButtonIndex + 1;
                            var currentLine = M.Math.round(currentButtonIndex / this.buttonsPerLine, M.CEIL) - 1;
                            var button = this[childViews[i]];

                            /* if the button belongs to the current line adjust its styling according to its position,
                               e.g. the first button in the first row gets the css class 'ui-corner-tl' (top left). */
                            if(line === currentLine) {

                                /* first line */
                                if(line === 0 && this.numberOfLines > 1) {
                                    /* first button */
                                    if(currentButtonIndex === 1) {
                                        $('#' + button.id).removeClass('ui-corner-left');
                                        if(this.isInset) {
                                            $('#' + button.id).addClass('ui-corner-tl');
                                        }
                                    /* last button */
                                    } else if(currentButtonIndex === this.buttonsPerLine) {
                                        $('#' + button.id).removeClass('ui-corner-right');
                                        if(this.isInset) {
                                            $('#' + button.id).addClass('ui-corner-tr');
                                        }
                                    }
                                /* last line */
                                } else if(line === this.numberOfLines - 1) {
                                    /* first button */
                                    if(currentButtonIndex === (currentLine * this.buttonsPerLine) + 1) {
                                        $('#' + button.id).removeClass('ui-corner-left');
                                        $('#' + button.id).addClass('ui-corner-bl');
                                    /* last button */
                                    } else if(currentButtonIndex === ((currentLine + 1) * this.buttonsPerLine)) {
                                        $('#' + button.id).removeClass('ui-corner-right');
                                        $('#' + button.id).addClass('ui-corner-br');
                                    }
                                /* all other lines */
                                } else {
                                    /* first button */
                                    if(currentButtonIndex === (currentLine * this.buttonsPerLine) + 1) {
                                        $('#' + button.id).removeClass('ui-corner-left');
                                    /* last button */
                                    } else if(currentButtonIndex === ((currentLine + 1) * this.buttonsPerLine)) {
                                        $('#' + button.id).removeClass('ui-corner-right');
                                    }
                                }
                            }
                        }
                    }
                }
            }
        /* if there is only on row, simply style that button group */
        } else {
            $('#' + this.id).controlgroup();
        }

        /* iterate through all buttons and activate on of them, according to the button's isActive property */
        if(this.childViews) {
            var childViews = this.getChildViewsAsArray();
            for(var i in childViews) {
                if(this[childViews[i]] && this[childViews[i]].type === 'M.ButtonView') {
                    var button = this[childViews[i]];
                    if(button.isActive) {
                        this.setActiveButton(button.id);
                    }
                }
            }
        }
    },

    /**
     * This method returns the currently selected button of this button group. If no
     * button is selected, null is returned.
     *
     * @returns {M.ButtonView} The currently active button of this button group.
     */
    getActiveButton: function() {
        return this.activeButton;
    },

    /**
     * This method activates one button within the button group.
     *
     * @param {M.ButtonView, String} id The button to be set active or its id.
     */
    setActiveButton: function(id, event, nextEvent) {
        if(this.isSelectable) {
            if(this.activeButton) {
                this.activeButton.removeCssClass('ui-btn-active');
                this.activeButton.isActive = NO;
            }

            var button = M.ViewManager.getViewById(id);
            if(!button) {
                if(id && typeof(id) === 'object' && id.type === 'M.ButtonView') {
                    button = id;
                }
            }
            if(button) {
                button.addCssClass('ui-btn-active');
                button.isActive = YES;
                this.activeButton = button;
            }
        }

        /* trigger change event for the button group */
        $('#' + this.id).trigger('change');

        /* delegate event to external handler, if specified */
        if(nextEvent) {
            M.EventDispatcher.callHandler(nextEvent, event, YES);
        }
    },

    /**
     * Applies some style-attributes to the button group.
     *
     * @private
     * @returns {String} The button group's styling as html representation.
     */
    style: function() {
        var html = '';
        if(this.numberOfLines && this.isInset) {
            html += ' class="ui-listview';
        }
        if(this.cssClass) {
            html += html !== '' ? ' ' + this.cssClass : ' class="' + this.cssClass;
        }
        html += '"';
        return html;
    }

});<commit_msg>fixed a cosmetic/styling bug in style() (isInset was rendered as non-inset)<commit_after>// ==========================================================================
// Project:   The M-Project - Mobile HTML5 Application Framework
// Copyright: (c) 2010 M-Way Solutions GmbH. All rights reserved.
// Creator:   Dominik
// Date:      02.12.2010
// License:   Dual licensed under the MIT or GPL Version 2 licenses.
//            http://github.com/mwaylabs/The-M-Project/blob/master/MIT-LICENSE
//            http://github.com/mwaylabs/The-M-Project/blob/master/GPL-LICENSE
// ==========================================================================

/**
 * A constant value for horizontal alignment.
 *
 * @type String
 */
M.HORIZONTAL = 'horizontal';

/**
 * A constant value for vertical alignment.
 *
 * @type String
 */
M.VERTICAL = 'vertical';

/**
 * @class
 *
 * A button group is a vertically or / and horizontally aligned group of buttons. There
 * are basically three different types of a button group:
 *
 * - horizontally aligned buttons
 *     1 - 2 - 3
 *
 * - vertically aligned buttons
 *     1
 *     |
 *     2
 *     |
 *     3
 *
 * - horizontally and vertically aligned buttons
 *     1 - 2
 *     |   |
 *     3 - 4
 *
 * @extends M.View
 */
M.ButtonGroupView = M.View.extend(
/** @scope M.ButtonGroupView.prototype */ {

    /**
     * The type of this object.
     *
     * @type String
     */
    type: 'M.ButtonGroupView',

    /**
     * This property determines whether to render the button group horizontally
     * or vertically. Default: horizontal.
     *
     * Possible values are:
     * - M.HORIZONTAL: horizontal
     * - M.VERTICAL: vertical
     *
     * @type String
     */
    direction: M.HORIZONTAL,

    /**
     * Determines whether to display the button group view 'inset' or at full width.
     *
     * @type Boolean
     */
    isInset: YES,

    /**
     * Determines whether to display the button group compact, i.e. without top/bottom
     * margin. This property only is relevant in combination with multiple lines of
     * buttons (c.p.: buttonsPerLine property).
     *
     * @type Boolean
     */
    isCompact: YES,

    /**
     * This property, if set, defines how many buttons are rendered per line. If there
     * are more buttons defined that fitting into one line, the following buttons are
     * rendered into a new line. Make sure, the number of your buttons is divisible by
     * the number of buttons per line, since only full lines are displayed. So if you
     * for example specify 5 buttons and 2 buttons per line, the fifth button won't be
     * visible.
     *
     * If e.g. 4 buttons are specified and this property is set to 2, the rendering will
     * be as follows:
     *
     *     1 -- 2
     *     3 -- 4
     *
     * @type Number
     */
    buttonsPerLine: null,

    /**
     * This property is used to internally store the number of lines that are necessary
     * to render all buttons according to the buttonsPerLine property.
     *
     * @private
     * @type Number
     */
    numberOfLines: null,

    /**
     * This property refers to the currently rendered line, if there is more than one.
     *
     * @private
     * @type Number
     */
    currentLine: null,

    /**
     * This property contains an array of html ids referring to the several lines of grouped
     * buttons, if there is more than one at all.
     *
     * @private
     * @type Array
     */
    lines: null,

    /**
     * This property contains a reference to the currently selected button.
     *
     * @private
     * @type Object
     */
    activeButton: null,

    /**
     * This property determines whether the buttons of this button group are selectable or not. If
     * set to YES, a click on one of the buttons will set this button as the currently active button
     * and automatically change its styling to visualize its selection.
     *
     * @type Boolean
     */
    isSelectable: YES,

    /**
     * This property specifies the recommended events for this type of view.
     *
     * @type Array
     */
    recommendedEvents: ['change'],

    /**
     * Renders a button group as a div container and calls the renderChildViews
     * method to render the included buttons.
     *
     * @private
     * @returns {String} The button group view's html representation.
     */
    render: function() {
        /* check if multiple lines are necessary before rendering */
        if(this.childViews) {
            var childViews = this.getChildViewsAsArray();
            if(this.buttonsPerLine && this.buttonsPerLine < childViews.length) {
                var numberOfButtons = 0;
                for(var i in childViews) {
                    if(this[childViews[i]] && this[childViews[i]].type === 'M.ButtonView') {
                        numberOfButtons = numberOfButtons + 1;
                    }
                }
                if(this.buttonsPerLine < numberOfButtons) {
                    this.numberOfLines = M.Math.round(numberOfButtons / this.buttonsPerLine, M.FLOOR);
                }
            }
        }

        /* if there are multiple lines, render multiple horizontally aligned button groups */
        if(this.numberOfLines) {
            /* set the direction to horizontally, no matter what it was set to before */
            this.direction = M.HORIZONTAL;

            /* this is a wrapper for the multiple button groups.
               if it is not inset, assign css class 'ui-listview' for clearing the padding of the surrounding element */
            this.html += '
';

            /* create a button group for every line */
            this.lines = [];
            for(var i = 0; i < this.numberOfLines; i++) {
                this.currentLine = i + 1;
                /* store current line in lines property for use in renderChildViews() */
                this.lines.push(this.id + '_' + i);

                this.html += '
 0 && i < this.numberOfLines - 1) {
                        this.html += this.isInset ? ' style="margin:0px 0px 0px 0px"' : ' style="margin:0px"';
                    } else if(i < this.numberOfLines) {
                        this.html += this.isInset ? ' style="margin-top:0px"' : ' style="margin:0px"';
                    }
                }

                this.html += '>';

                /* render the buttons for the current line */
                this.renderChildViews();

                this.html += '
';
            }
            this.html += '
';
        } else {
            this.html += '
';

            this.renderChildViews();

            this.html += '
';
        }

        return this.html;
    },

    /**
     * Triggers render() on all children of type M.ButtonGroupView.
     *
     * @private
     */
    renderChildViews: function() {
        if(this.childViews) {
            var childViews = this.getChildViewsAsArray();
            var currentButtonIndex = 0;

            for(var i in childViews) {
                if(this[childViews[i]] && this[childViews[i]].type === 'M.ButtonView') {
                    currentButtonIndex = currentButtonIndex + 1;

                    if(!this.numberOfLines || M.Math.round(currentButtonIndex / this.buttonsPerLine, M.CEIL) === this.currentLine) {

                        var button = this[childViews[i]];
                        /* reset buttons html, to make sure it doesn't get rendered twice if this is multi button group */
                        button.html = '';

                        button.parentView = this;
                        button.internalEvents = {
                            tap: {
                                target: this,
                                action: 'setActiveButton'
                            }
                        }

                        /* if the buttons are horizontally aligned, compute their width depending on the number of buttons
                           and set the right margin to '-2px' since the jQuery mobile default would cause an ugly gap to
                           the right of the button group */
                        if(this.direction === M.HORIZONTAL) {
                            button.cssStyle = 'margin-right:-2px;width:' + 100 / (this.numberOfLines ? this.buttonsPerLine : childViews.length) + '%';
                        }

                        /* set the button's _name property */
                        this[childViews[i]]._name = childViews[i];

                        /* finally render the button and add it to the button groups html */
                        this.html += this[childViews[i]].render();
                    }
                } else {
                    M.Logger.log('childview of button group is no button.', M.WARN);
                }
            }
        }
    },

    /**
     * This method themes the button group and activates one of the included buttons
     * if its isActive property is set.
     *
     * @private
     */
    theme: function() {
        /* if there are multiple lines of buttons, it's getting heavy */
        if(this.numberOfLines) {

            /* iterate through all lines */
            for(var line in this.lines) {
                line = parseInt(line);

                /* style the current line */
                $('#' + this.lines[line]).controlgroup();
                var childViews = this.getChildViewsAsArray();
                var currentButtonIndex = 0;

                /* if isCompact, iterate through all buttons */
                if(this.isCompact) {
                    for(var i in childViews) {
                        i = parseInt(i);
                        if(this[childViews[i]] && this[childViews[i]].type === 'M.ButtonView') {
                            currentButtonIndex = currentButtonIndex + 1;
                            var currentLine = M.Math.round(currentButtonIndex / this.buttonsPerLine, M.CEIL) - 1;
                            var button = this[childViews[i]];

                            /* if the button belongs to the current line adjust its styling according to its position,
                               e.g. the first button in the first row gets the css class 'ui-corner-tl' (top left). */
                            if(line === currentLine) {

                                /* first line */
                                if(line === 0 && this.numberOfLines > 1) {
                                    /* first button */
                                    if(currentButtonIndex === 1) {
                                        $('#' + button.id).removeClass('ui-corner-left');
                                        if(this.isInset) {
                                            $('#' + button.id).addClass('ui-corner-tl');
                                        }
                                    /* last button */
                                    } else if(currentButtonIndex === this.buttonsPerLine) {
                                        $('#' + button.id).removeClass('ui-corner-right');
                                        if(this.isInset) {
                                            $('#' + button.id).addClass('ui-corner-tr');
                                        }
                                    }
                                /* last line */
                                } else if(line === this.numberOfLines - 1) {
                                    /* first button */
                                    if(currentButtonIndex === (currentLine * this.buttonsPerLine) + 1) {
                                        $('#' + button.id).removeClass('ui-corner-left');
                                        $('#' + button.id).addClass('ui-corner-bl');
                                    /* last button */
                                    } else if(currentButtonIndex === ((currentLine + 1) * this.buttonsPerLine)) {
                                        $('#' + button.id).removeClass('ui-corner-right');
                                        $('#' + button.id).addClass('ui-corner-br');
                                    }
                                /* all other lines */
                                } else {
                                    /* first button */
                                    if(currentButtonIndex === (currentLine * this.buttonsPerLine) + 1) {
                                        $('#' + button.id).removeClass('ui-corner-left');
                                    /* last button */
                                    } else if(currentButtonIndex === ((currentLine + 1) * this.buttonsPerLine)) {
                                        $('#' + button.id).removeClass('ui-corner-right');
                                    }
                                }
                            }
                        }
                    }
                }
            }
        /* if there is only on row, simply style that button group */
        } else {
            $('#' + this.id).controlgroup();
        }

        /* iterate through all buttons and activate on of them, according to the button's isActive property */
        if(this.childViews) {
            var childViews = this.getChildViewsAsArray();
            for(var i in childViews) {
                if(this[childViews[i]] && this[childViews[i]].type === 'M.ButtonView') {
                    var button = this[childViews[i]];
                    if(button.isActive) {
                        this.setActiveButton(button.id);
                    }
                }
            }
        }
    },

    /**
     * This method returns the currently selected button of this button group. If no
     * button is selected, null is returned.
     *
     * @returns {M.ButtonView} The currently active button of this button group.
     */
    getActiveButton: function() {
        return this.activeButton;
    },

    /**
     * This method activates one button within the button group.
     *
     * @param {M.ButtonView, String} id The button to be set active or its id.
     */
    setActiveButton: function(id, event, nextEvent) {
        if(this.isSelectable) {
            if(this.activeButton) {
                this.activeButton.removeCssClass('ui-btn-active');
                this.activeButton.isActive = NO;
            }

            var button = M.ViewManager.getViewById(id);
            if(!button) {
                if(id && typeof(id) === 'object' && id.type === 'M.ButtonView') {
                    button = id;
                }
            }
            if(button) {
                button.addCssClass('ui-btn-active');
                button.isActive = YES;
                this.activeButton = button;
            }
        }

        /* trigger change event for the button group */
        $('#' + this.id).trigger('change');

        /* delegate event to external handler, if specified */
        if(nextEvent) {
            M.EventDispatcher.callHandler(nextEvent, event, YES);
        }
    },

    /**
     * Applies some style-attributes to the button group.
     *
     * @private
     * @returns {String} The button group's styling as html representation.
     */
    style: function() {
        var html = '';
        if(this.numberOfLines && !this.isInset) {
            html += ' class="ui-listview';
        }
        if(this.cssClass) {
            html += html !== '' ? ' ' + this.cssClass : ' class="' + this.cssClass;
        }
        html += '"';
        return html;
    }

});<|endoftext|>


<commit_before>'use strict';

var _                   = require('mano').i18n.bind('Sections')
  , d                   = require('d')
  , db                  = require('mano').db
  , resolvePropertyPath = require('dbjs/_setup/utils/resolve-property-path')
  , ns = require('mano').domjs.ns;

require('./form-section-base');

module.exports = Object.defineProperty(db.FormEntitiesTable.prototype, 'toDOMForm',
	d(function (document/*, options */) {
		var self = this, options, url, customizeData, tableData;
		customizeData = {};
		url = ns.url;
		options = Object(arguments[1]);
		url = options.url || ns.url;
		tableData = resolvePropertyPath(this.master, this.constructor.propertyName).value;
		customizeData.arrayResult = [customizeData.container = ns.section(
			{ id: this.domId, class: ns._if(ns.eq(
				this._status,
				1
			), 'section-primary completed entities-overview', 'section-primary entities-overview') },
			ns._if(this._label,
				[ns.h2(this._label),
					ns.hr()]),
			options.prepend,
			ns.table(
				{ class: ns._if(ns.not(ns.eq(tableData._size, 0)),
						'entities-overview-table',
						'entities-overview-table entities-overview-table-empty') },
				ns.thead(
					ns.tr(ns.list(this.constructor.entities, function (entity) {
						return ns.th({ class: ns._if(entity._desktopOnly, 'desktop-only',
									ns._if(entity._mobileOnly, 'mobile-only')) },
							resolvePropertyPath(
								self.master.getDescriptor(self.constructor.propertyName).type.prototype,
								entity.propertyName
							).descriptor.label);
					}), ns.th(),
						ns.th())
				),
				ns.tbody({ onEmpty: ns.tr(ns.td({ colspan: this.constructor.entities.size + 2 },
							this.constructor.onEmptyMessage)
					) },
					tableData,
					function (entityObject) {
						return ns.tr(ns.list(self.constructor.entities, function (entity) {
							return ns.td({ class: ns._if(entity._desktopOnly, 'desktop-only',
										ns._if(entity._mobileOnly, 'mobile-only')) },
									ns.a({ href: url(self.constructor.baseUrl, entityObject.__id__) },
										resolvePropertyPath(entityObject, entity.propertyName).observable));
						}),
							ns.td({ class: ns._if(ns.eq(resolvePropertyPath(entityObject,
											self.constructor.sectionProperty + 'Status').observable, 1),
									'completed') },
								ns.span({ class: 'status-complete' }, "✓"),
								ns.span({ class: 'hint-optional hint-optional-left status-incomplete',
										'data-hint': _("Some required fields are not filled") },
										"!")),
							ns.td({ class: 'actions' },
								ns.a({ class: 'actions-edit',
										href: url(self.constructor.baseUrl, entityObject.__id__) },
									ns.span({ class: 'fa fa-edit' }, _("Edit"))),
								ns.postButton({ buttonClass: 'actions-delete',
										action: url(self.constructor.baseUrl,
										entityObject.__id__, 'delete'),
									value: ns.span({ class: 'fa fa-trash-o' },
										_("Delete")) })));
					}),
				this.constructor.generateFooter &&
					ns.tfoot(this.constructor.generateFooter(
						resolvePropertyPath(this.master, this.constructor.propertyName).value
					))
			),
			options.append,
			ns.p(
				customizeData.addButton = ns.a(
					{ class: 'button-main', href: url(this.constructor.baseUrl + '-add') },
					options.addButtonLabel || _("Add new")
				)
			),
			ns.p({ class: 'section-primary-scroll-top' },
				ns.a({ onclick: 'window.scroll(0, 0)' }, ns.span({ class: 'fa fa-arrow-up' },
					_("Back to top"))))
		)];
		if (typeof options.customize === 'function') {
			options.customize.call(this, customizeData);
		}
		return customizeData.arrayResult;
	}));
<commit_msg>#527 brought back options<commit_after>'use strict';

var _                   = require('mano').i18n.bind('Sections')
  , d                   = require('d')
  , db                  = require('mano').db
  , resolvePropertyPath = require('dbjs/_setup/utils/resolve-property-path')
  , ns = require('mano').domjs.ns;

require('./form-section-base');

module.exports = Object.defineProperty(db.FormEntitiesTable.prototype, 'toDOMForm',
	d(function (document/*, options */) {
		var self = this, options, url, customizeData, tableData;
		customizeData = {};
		url = ns.url;
		options = Object(arguments[1]);
		url = options.url || ns.url;
		tableData = resolvePropertyPath(this.master, this.constructor.propertyName).value;
		customizeData.arrayResult = [customizeData.container = ns.section(
			{ id: this.domId, class: ns._if(ns.eq(
				this._status,
				1
			), 'section-primary completed entities-overview', 'section-primary entities-overview') },
			ns._if(this._label,
				[ns.h2(this._label),
					ns.hr()]),
			options.prepend,
			ns.table(
				{ class: ns._if(ns.not(ns.eq(tableData._size, 0)),
						'entities-overview-table',
						'entities-overview-table entities-overview-table-empty') },
				ns.thead(
					ns.tr(ns.list(this.constructor.entities, function (entity) {
						return ns.th({ class: ns._if(entity._desktopOnly, 'desktop-only',
									ns._if(entity._mobileOnly, 'mobile-only')) },
							resolvePropertyPath(
								self.master.getDescriptor(self.constructor.propertyName).type.prototype,
								entity.propertyName
							).descriptor.label);
					}), ns.th(),
						ns.th({ class: 'actions' }))
				),
				ns.tbody({ onEmpty: ns.tr(ns.td({ colspan: this.constructor.entities.size + 2 },
							this.constructor.onEmptyMessage)
					) },
					tableData,
					function (entityObject) {
						return ns.tr(ns.list(self.constructor.entities, function (entity) {
							return ns.td({ class: ns._if(entity._desktopOnly, 'desktop-only',
										ns._if(entity._mobileOnly, 'mobile-only')) },
									ns.a({ href: url(self.constructor.baseUrl, entityObject.__id__) },
										resolvePropertyPath(entityObject, entity.propertyName).observable));
						}),
							ns.td({ class: ns._if(ns.eq(resolvePropertyPath(entityObject,
											self.constructor.sectionProperty + 'Status').observable, 1),
									'completed') },
								ns.span({ class: 'status-complete' }, "✓"),
								ns.span({ class: 'hint-optional hint-optional-left status-incomplete',
										'data-hint': _("Some required fields are not filled") },
										"!")),
							ns.td({ class: 'actions' },
								ns.a({ class: 'actions-edit',
										href: url(self.constructor.baseUrl, entityObject.__id__) },
									ns.span({ class: 'fa fa-edit' }, _("Edit"))),
								ns.postButton({ buttonClass: 'actions-delete',
										action: url(self.constructor.baseUrl,
										entityObject.__id__, 'delete'),
									value: ns.span({ class: 'fa fa-trash-o' },
										_("Delete")) })));
					}),
				this.constructor.generateFooter &&
					ns.tfoot(this.constructor.generateFooter(
						resolvePropertyPath(this.master, this.constructor.propertyName).value
					))
			),
			options.append,
			ns.p(
				customizeData.addButton = ns.a(
					{ class: 'button-main', href: url(this.constructor.baseUrl + '-add') },
					options.addButtonLabel || _("Add new")
				)
			),
			ns.p({ class: 'section-primary-scroll-top' },
				ns.a({ onclick: 'window.scroll(0, 0)' }, ns.span({ class: 'fa fa-arrow-up' },
					_("Back to top"))))
		)];
		if (typeof options.customize === 'function') {
			options.customize.call(this, customizeData);
		}
		return customizeData.arrayResult;
	}));
<|endoftext|>


<commit_before>const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { GenerateSW } = require('workbox-webpack-plugin')
const CopyPlugin = require('copy-webpack-plugin')
const brResources = require('./src/site/locales/br/app.json')
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

const stylusLoaderConfig = {
  loader: 'stylus-loader',
  options: {
    import: [
      path.resolve(__dirname, './src/site/styles/settings/_variables.styl'),
      path.resolve(__dirname, './src/site/styles/helpers/index.styl')
    ]
  }
}

const miniCSSLoaderConfig = {
  loader: MiniCssExtractPlugin.loader,
  options: {
    esModule: true,
  }
}

const postCSSLoaderConfig = {
  loader: 'postcss-loader',
  options: {
    sourceMap: true,
    plugins: (loader) => [
      require('postcss-preset-env')({
        stage: 3,
      }),
      require('postcss-combine-media-query')(),
      require('cssnano')(),
    ]
  }
}

module.exports = {
  mode: 'production',
  entry: {
    index: [
      'core-js/modules/esnext.global-this.js',
      'core-js/modules/es.number.is-nan.js',
      './src/site/index.tsx'
    ],
    shared: 'react'
  },
  output: {
    filename: '[name].[contenthash].js',
    chunkFilename: '[name].[contenthash].bundle.js',
    path: path.resolve(__dirname, 'website')
  },
  optimization: {
    minimize: true,
    splitChunks: {
      chunks: 'all',
      cacheGroups: {
        vendors: {
          test: /node_modules/,
          chunks: 'all',
          enforce: true
        },
        styles: {
          name: 'styles',
          test: /\.css$/,
          chunks: 'all',
          enforce: true,
        },
      }
    },
  },
  module: {
    rules: [
      {
        test: /\.(jsx?|tsx?)$/,
        exclude: /node_modules/,
        loader: 'babel-loader'
      },
      {
        test: /\.module\.styl$/,
        loader: [miniCSSLoaderConfig, {
          loader: 'css-loader',
          options: {
            importLoaders: 2,
            modules: {
              localIdentName: '[local]--[hash:base64:7]',
            },
            esModule: true,
            localsConvention: 'camelCaseOnly'
          }
        }, postCSSLoaderConfig, stylusLoaderConfig]
      },
      {
        test: /\.styl$/,
        exclude: /\.module\.styl$/,
        loader: [miniCSSLoaderConfig, 'css-loader', postCSSLoaderConfig, stylusLoaderConfig]
      },
      {
        test: /\.css$/,
        loader: [miniCSSLoaderConfig, 'css-loader', postCSSLoaderConfig]
      },
      {
        test: /\.(png|jpe?g|gif|svg)$/,
        loader: 'file-loader',
        options: {
          outputPath: 'img',
        },
      },
      {
        test: /app\.json$/,
        use: [
          {
            loader: path.resolve('loader/generate-mappings.js')
          }
        ]
      }
    ]
  },
  resolve: {
    extensions: ['.tsx', '.ts', '.js', '.jsx'],
    alias: {
      '@i18nResources': path.join(__dirname, './src/site/locales/resources.json')
    }
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: '[name].[contenthash].css'
    }),
    new CopyPlugin(['public']),
    new HtmlWebpackPlugin({
      favicon: './public/favicon.ico',
      template: './src/site/index.ejs',
      meta: {
        description: brResources.app.description,
        keywords: brResources.app.keywords,
      },
      templateParameters: {
        title: brResources.app.title,
        lang: 'pt-BR'
      }
    }),
    new GenerateSW({
      clientsClaim: true,
      skipWaiting: true,
    })
  ]
}
<commit_msg>Add map polyfill<commit_after>const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { GenerateSW } = require('workbox-webpack-plugin')
const CopyPlugin = require('copy-webpack-plugin')
const brResources = require('./src/site/locales/br/app.json')
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

const stylusLoaderConfig = {
  loader: 'stylus-loader',
  options: {
    import: [
      path.resolve(__dirname, './src/site/styles/settings/_variables.styl'),
      path.resolve(__dirname, './src/site/styles/helpers/index.styl')
    ]
  }
}

const miniCSSLoaderConfig = {
  loader: MiniCssExtractPlugin.loader,
  options: {
    esModule: true,
  }
}

const postCSSLoaderConfig = {
  loader: 'postcss-loader',
  options: {
    sourceMap: true,
    plugins: (loader) => [
      require('postcss-preset-env')({
        stage: 3,
      }),
      require('postcss-combine-media-query')(),
      require('cssnano')(),
    ]
  }
}

module.exports = {
  mode: 'production',
  entry: {
    index: [
      'core-js/modules/esnext.global-this.js',
      'core-js/modules/es.number.is-nan.js',
      'core-js/modules/es.map.js',
      './src/site/index.tsx'
    ],
    shared: 'react'
  },
  output: {
    filename: '[name].[contenthash].js',
    chunkFilename: '[name].[contenthash].bundle.js',
    path: path.resolve(__dirname, 'website')
  },
  optimization: {
    minimize: true,
    splitChunks: {
      chunks: 'all',
      cacheGroups: {
        vendors: {
          test: /node_modules/,
          chunks: 'all',
          enforce: true
        },
        styles: {
          name: 'styles',
          test: /\.css$/,
          chunks: 'all',
          enforce: true,
        },
      }
    },
  },
  module: {
    rules: [
      {
        test: /\.(jsx?|tsx?)$/,
        exclude: /node_modules/,
        loader: 'babel-loader'
      },
      {
        test: /\.module\.styl$/,
        loader: [miniCSSLoaderConfig, {
          loader: 'css-loader',
          options: {
            importLoaders: 2,
            modules: {
              localIdentName: '[local]--[hash:base64:7]',
            },
            esModule: true,
            localsConvention: 'camelCaseOnly'
          }
        }, postCSSLoaderConfig, stylusLoaderConfig]
      },
      {
        test: /\.styl$/,
        exclude: /\.module\.styl$/,
        loader: [miniCSSLoaderConfig, 'css-loader', postCSSLoaderConfig, stylusLoaderConfig]
      },
      {
        test: /\.css$/,
        loader: [miniCSSLoaderConfig, 'css-loader', postCSSLoaderConfig]
      },
      {
        test: /\.(png|jpe?g|gif|svg)$/,
        loader: 'file-loader',
        options: {
          outputPath: 'img',
        },
      },
      {
        test: /app\.json$/,
        use: [
          {
            loader: path.resolve('loader/generate-mappings.js')
          }
        ]
      }
    ]
  },
  resolve: {
    extensions: ['.tsx', '.ts', '.js', '.jsx'],
    alias: {
      '@i18nResources': path.join(__dirname, './src/site/locales/resources.json')
    }
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: '[name].[contenthash].css'
    }),
    new CopyPlugin(['public']),
    new HtmlWebpackPlugin({
      favicon: './public/favicon.ico',
      template: './src/site/index.ejs',
      meta: {
        description: brResources.app.description,
        keywords: brResources.app.keywords,
      },
      templateParameters: {
        title: brResources.app.title,
        lang: 'pt-BR'
      }
    }),
    new GenerateSW({
      clientsClaim: true,
      skipWaiting: true,
    })
  ]
}
<|endoftext|>


<commit_before>var express = require('express')
var router = express.Router()

router.post('/', function(req, res){
	var models = req.app.get('models')
	var  groups = []
	var userfbId = req.body.id
	models.User.findOne({
	    where: {
	      facebookId: userfbId
	    }
	}).then(user => {
		var userId = user.id
		models.UserGroup.findAll()
		.then(groups => {
			res.send(groups)
			//	groups.forEach(group){
			//		if(group.userId )
			//}
		})
	})
	var queried_group = models.Group
})

router.get('/:id', function(req, res){
	console.log('get group with id '+ req.params.id)
	var models = req.app.get('models')
	var groupid = req.params.id
	var group = models.Group
		.findById(groupid)
		.then(group => {
			if(group == null)
				res.send('group does not exist')
			else {
					res.send(group)
			}
		}, function(error){
			res.send(error)
		})
})

router.get('/:id/photos', function(req, res){
	var models = req.app.get('models')
	var groupPhotos = []
	var groupid = req.params.id
	models.Photo.findAll()
		.then(function(photos){
			photos.forEach(function(photo){
				if(photo.groupId == groupid)
					groupPhotos.push(photo)
			})
			res.send(groupPhotos)
		})
})

router.post('/:id/changeName', function(req, res){
	console.log('changing name of group with id '+ req.body.id)
	var models = req.app.get('models')
	var groupid = req.params.id
	var group = models.Group
	.findById(groupid)
	.then(group => {
		group.updateAttributes({
			name: req.body.name
		}).then(function(){
			res.send('success changing name')
		}, function(error){
			console.log(error)
			res.send('error changing name')
		})
	})
})

router.post('/', function(req, res){
	console.log('new group')
	var models = req.app.get('models')
	var owner;
	models.User.findOne({
	    where: {
	      facebookId: req.body.owner
	    }
	}).then(user => {
    	owner = user.id
		models.Group.create({
			name: req.body.name,
			owner: owner
		}).then(group =>{
			console.log("success adding new group")
			res.send(group)
		},function(error){
			console.log(error)
			res.send('error adding new group')
		})
	})
})

router.post('/addUser', function(req, res){
	console.log('add user')
	var groupId = req.body.groupId
	var userId = req.body.userId
	var models = req.app.get('models')
	models.User.findOne({
	    where: {
	      facebookId: userId
	    }
	}).then(user => {
    	userId = user.id
		models.User.findById(userId).then(user => {
		   models.Group.findById(groupId).then(group => {
	    	 if(user == null || group == null)
	    	 	res.send('error adding user to group')
	    	 else{
	    	 	user.setGroups([group]).
	    	 	then(function(){
	    	 		res.send('user added to group')
	    	 	})
	    	 }
	   		})
	 	})
	})
})

router.post('/:id/publish', function(req, res){
	res.send('publish photos of group with id '+ req.params.id)
})

module.exports = router<commit_msg>number of votes with photos<commit_after>var express = require('express')
var router = express.Router()

router.post('/', function(req, res){
	var models = req.app.get('models')
	var  groups = []
	var userfbId = req.body.id
	models.User.findOne({
	    where: {
	      facebookId: userfbId
	    }
	}).then(user => {
		var userId = user.id
		models.UserGroup.findAll()
		.then(groups => {
			res.send(groups)
			//	groups.forEach(group){
			//		if(group.userId )
			//}
		})
	})
	var queried_group = models.Group
})

router.get('/:id', function(req, res){
	console.log('get group with id '+ req.params.id)
	var models = req.app.get('models')
	var groupid = req.params.id
	var group = models.Group
		.findById(groupid)
		.then(group => {
			if(group == null)
				res.send('group does not exist')
			else {
					res.send(group)
			}
		}, function(error){
			res.send(error)
		})
})

router.get('/:id/photos', function(req, res){
	var models = req.app.get('models')
	var groupPhotos = []
	var groupid = req.params.id
	models.Photo.findAll()
		.then(function(photos){
			photos.forEach(function(photo1){
				if(photo1.groupId == groupid){
					var photo =JSON.parse(JSON.stringify(photo1))
					photo.votes = 0
					models.Vote.findAll()
					.then(function(votes){
						votes.forEach(function(vote){
							if(vote.photoId == photo.id && vote.isValid)
								photo.votes++
						})
					})
					groupPhotos.push(photo)
				}
			})
			res.send(groupPhotos)
		})
})

router.post('/:id/changeName', function(req, res){
	console.log('changing name of group with id '+ req.body.id)
	var models = req.app.get('models')
	var groupid = req.params.id
	var group = models.Group
	.findById(groupid)
	.then(group => {
		group.updateAttributes({
			name: req.body.name
		}).then(function(){
			res.send('success changing name')
		}, function(error){
			console.log(error)
			res.send('error changing name')
		})
	})
})

router.post('/', function(req, res){
	console.log('new group')
	var models = req.app.get('models')
	var owner;
	models.User.findOne({
	    where: {
	      facebookId: req.body.owner
	    }
	}).then(user => {
    	owner = user.id
		models.Group.create({
			name: req.body.name,
			owner: owner
		}).then(group =>{
			console.log("success adding new group")
			res.send(group)
		},function(error){
			console.log(error)
			res.send('error adding new group')
		})
	})
})

router.post('/addUser', function(req, res){
	console.log('add user')
	var groupId = req.body.groupId
	var userId = req.body.userId
	var models = req.app.get('models')
	models.User.findOne({
	    where: {
	      facebookId: userId
	    }
	}).then(user => {
    	userId = user.id
		models.User.findById(userId).then(user => {
		   models.Group.findById(groupId).then(group => {
	    	 if(user == null || group == null)
	    	 	res.send('error adding user to group')
	    	 else{
	    	 	user.setGroups([group]).
	    	 	then(function(){
	    	 		res.send('user added to group')
	    	 	})
	    	 }
	   		})
	 	})
	})
})

router.post('/:id/publish', function(req, res){
	res.send('publish photos of group with id '+ req.params.id)
})

module.exports = router<|endoftext|>


<commit_before>'use strict'

var _ = require('lodash')
var d3 = require('d3')

var qualitativeAxis = require('./qualitative-axis')

var defaults = {
  domain: _.constant([0, 1]),
  fontSize: 10,
  lineHeight: 1.2,
  padding: 0,
  scale: d3.scale.linear,
  thresholds: [],
  targets: [],
  format: String,

  margin: {
    top: 0,
    right: 0,
    bottom: 0,
    left: 0
  }
}

function BulletChart () {
}

_.extend(BulletChart.prototype, {
  defaults: defaults,

  initialize: function (el, data, options) {
    options = this._options = _.defaults({}, options, defaults)

    var n = Math.max(data.length, 1)
    var height = options.fontSize * n * options.lineHeight +
      options.fontSize * options.padding * (n - 1) +
      options.margin.top +
      options.margin.bottom

    this._width = el.clientWidth

    var svg = this._svg = d3.select(el).append('svg')
      .attr({
        'viewBox': '0 0 ' + this._width + ' ' + height,
        'width': this._width,
        'height': height
      })

    // Append the x-axis container and a blank background
    svg.append('g').attr('class', 'x axis')

    // Append a data layer
    svg.append('g')
      .attr({
        'class': 'data',
        'transform': 'translate(' + options.margin.left + ', ' + options.margin.top + ')'
      })

    this.update(data)
  },

  update: function (data, options) {
    options = _.assign(this._options, options)

    var margin = options.margin
    var svg = this._svg

    var n = Math.max(data.length, 1)
    var h = options.fontSize * n * options.lineHeight + options.fontSize * options.padding * (n - 1)
    var w = this._width - margin.left - margin.right

    var yScale = d3.scale.ordinal()
      .domain(_(data).flatten().map(options.y).uniq().value())
      .rangeRoundBands([h, 0])

    var y = _.flow(options.y, yScale)

    var xScale = options.scale()
      .domain(options.domain(data))
      .range([0, w])

    var x = _.flow(options.marker, xScale)
    var width = _.flow(options.value, xScale)

    var isEmpty = !_(data).map(options.value).all(_.isFinite)

    // Draw qualitative ranges
    if (!(isEmpty || _.isEmpty(options.thresholds) || _.isEmpty(options.targets))) {
      var tick = svg.select('.x.axis').selectAll('.tick').data(data)

      tick.enter()
        .append('g')
        .attr('class', 'tick')
        .style('fill', options.axisFill)
      tick.exit().remove()

      var rect = tick.selectAll('rect').data(function (d) {
        return isEmpty ? [] : [d]
      })
      rect.enter().append('rect')
        .style('fill', 'inherit')

      rect
        .attr({
          'height': h + margin.top + margin.bottom,
          'width': w
        })
    } else {
      svg.select('.x.axis')
        .call(qualitativeAxis()
          .height(h + margin.top + margin.bottom)
          .width(w)
          .scale(xScale)
          .threshold(d3.scale.threshold()
            .domain([])
            .range([''])
        )
          .colors(['#F2F2F2', '#F2F2F2'])
      )
    }

    svg.attr({
      'viewBox': '0 0 ' + w + ' ' + (h + margin.top + margin.bottom),
      'width': w,
      'height': h + margin.top + margin.bottom
    })

    svg.select('.data').
      call(qualitativeAxis()
        .height(h + margin.top + margin.bottom)
        .scale(xScale)
        .threshold(d3.scale.threshold()
          .domain(options.thresholds)
          .range(options.targets)
      )
    )

    var g = svg.select('.data')
      .attr('transform', 'translate(' + margin.left + ', ' + margin.top + ')')

    // Draw value
    var bar = g.selectAll('.bar').data(data)

    bar.enter().append('g')
    bar
      .attr({
        'class': 'bar',
        'y': y
      })
      .style('fill', options.dataFill)
    bar.exit().remove()

    var value = bar.selectAll('.value').data(function (d) {
      return isEmpty ? [] : [d]
    })

    var valueAttr = {
      'class': 'value',
      'height': yScale.rangeBand()
    }

    value.enter()
      .append('rect')
      .attr(valueAttr)
      .style('fill', 'inherit')

    value.attr(valueAttr)
      .transition()
      .duration(500)
      .attr('width', width)
    value.exit().remove()

     // Draw comparitive measure
    var measure = bar.selectAll('.comparative-measure')
      .data(function (d) {
        var v = options.value(d)
        var m = options.marker(d)
        return _.isFinite(v) && _.isFinite(m) ? [d] : []
      })

    var measureHeight = yScale.rangeBand() * 0.5

    var initAttr = {
      'class': 'comparative-measure',
      'width': 3,
      'height': yScale.rangeBand() + measureHeight,
      'y': -measureHeight / 2
    }

    measure.enter().append('rect').attr(initAttr)
      .style('fill', 'inherit')
    measure.attr(initAttr).attr('x', x)
    measure.exit().remove()

    var label = bar.selectAll('.label')
      .data(function (d) {
        var v = options.value(d)
        return _.isFinite(v) ? [v] : []
      })

    label.enter()
      .append('text')
      .attr({
        'class': 'label'
      })

    label
      .attr({
        'x': w,
        'y': -15,
        'text-anchor': 'end',
        'dy': (options.lineHeight / 4) + 'em',
        'transform': 'translate(0, ' + (h / 2) + ')',
        'fill': 'inherit'
      })
      .style('font-size', options.fontSize)
      .text(options.format)
    label.exit().remove()

    var compareValue = bar.selectAll('.comparative-text')
      .data(function (d) {
        var v = options.value(d)
        return [options.valueText(v)]
      })

    compareValue.enter().append('text')
      .attr('class', 'comparative-text')

    compareValue
      .attr({
        'x': 0,
        'y': 0,
        'text-anchor': 'start',
        'dy': (options.lineHeight / 4) + 'em',
        'transform': 'translate(0, ' + (h / 2) + ')',
        'fill': '#FFFFFF'
      })
      .style('font-size', options.fontSize - 2)
      .text(function (d) {
        return d
      })
    compareValue.exit().remove()
  },

  resize: function (el) {}
})

module.exports = BulletChart
<commit_msg>#440 fixed bullet-chart border is circular.<commit_after>'use strict'

var _ = require('lodash')
var d3 = require('d3')

var qualitativeAxis = require('./qualitative-axis')

var defaults = {
  domain: _.constant([0, 1]),
  fontSize: 10,
  lineHeight: 1.2,
  padding: 0,
  scale: d3.scale.linear,
  thresholds: [],
  targets: [],
  format: String,

  margin: {
    top: 0,
    right: 0,
    bottom: 0,
    left: 0
  }
}

function BulletChart () {
}

_.extend(BulletChart.prototype, {
  defaults: defaults,

  initialize: function (el, data, options) {
    options = this._options = _.defaults({}, options, defaults)

    var n = Math.max(data.length, 1)
    var height = options.fontSize * n * options.lineHeight +
      options.fontSize * options.padding * (n - 1) +
      options.margin.top +
      options.margin.bottom

    this._width = el.clientWidth

    var svg = this._svg = d3.select(el).append('svg')
      .attr({
        'viewBox': '0 0 ' + this._width + ' ' + height,
        'width': this._width,
        'height': height,
        'style': 'border-radius: 30px;'
      })

    // Append the x-axis container and a blank background
    svg.append('g').attr('class', 'x axis')

    // Append a data layer
    svg.append('g')
      .attr({
        'class': 'data',
        'transform': 'translate(' + options.margin.left + ', ' + options.margin.top + ')'
      })

    this.update(data)
  },

  update: function (data, options) {
    options = _.assign(this._options, options)

    var margin = options.margin
    var svg = this._svg

    var n = Math.max(data.length, 1)
    var h = options.fontSize * n * options.lineHeight + options.fontSize * options.padding * (n - 1)
    var w = this._width - margin.left - margin.right

    var yScale = d3.scale.ordinal()
      .domain(_(data).flatten().map(options.y).uniq().value())
      .rangeRoundBands([h, 0])

    var y = _.flow(options.y, yScale)

    var xScale = options.scale()
      .domain(options.domain(data))
      .range([0, w])

    var x = _.flow(options.marker, xScale)
    var width = _.flow(options.value, xScale)

    var isEmpty = !_(data).map(options.value).all(_.isFinite)

    // Draw qualitative ranges
    if (!(isEmpty || _.isEmpty(options.thresholds) || _.isEmpty(options.targets))) {
      var tick = svg.select('.x.axis').selectAll('.tick').data(data)

      tick.enter()
        .append('g')
        .attr('class', 'tick')
        .style('fill', options.axisFill)
      tick.exit().remove()

      var rect = tick.selectAll('rect').data(function (d) {
        return isEmpty ? [] : [d]
      })
      rect.enter().append('rect')
        .style('fill', 'inherit')

      rect
        .attr({
          'height': h + margin.top + margin.bottom,
          'width': w
        })
    } else {
      svg.select('.x.axis')
        .call(qualitativeAxis()
          .height(h + margin.top + margin.bottom)
          .width(w)
          .scale(xScale)
          .threshold(d3.scale.threshold()
            .domain([])
            .range([''])
        )
          .colors(['#F2F2F2', '#F2F2F2'])
      )
    }

    svg.attr({
      'viewBox': '0 0 ' + w + ' ' + (h + margin.top + margin.bottom),
      'width': w,
      'height': h + margin.top + margin.bottom
    })

    svg.select('.data').
      call(qualitativeAxis()
        .height(h + margin.top + margin.bottom)
        .scale(xScale)
        .threshold(d3.scale.threshold()
          .domain(options.thresholds)
          .range(options.targets)
      )
    )

    var g = svg.select('.data')
      .attr('transform', 'translate(' + margin.left + ', ' + margin.top + ')')

    // Draw value
    var bar = g.selectAll('.bar').data(data)

    bar.enter().append('g')
    bar
      .attr({
        'class': 'bar',
        'y': y
      })
      .style('fill', options.dataFill)
    bar.exit().remove()

    var value = bar.selectAll('.value').data(function (d) {
      return isEmpty ? [] : [d]
    })

    var valueAttr = {
      'class': 'value',
      'height': yScale.rangeBand()
    }

    value.enter()
      .append('rect')
      .attr(valueAttr)
      .style('fill', 'inherit')

    value.attr(valueAttr)
      .transition()
      .duration(500)
      .attr('width', width)
    value.exit().remove()

     // Draw comparitive measure
    var measure = bar.selectAll('.comparative-measure')
      .data(function (d) {
        var v = options.value(d)
        var m = options.marker(d)
        return _.isFinite(v) && _.isFinite(m) ? [d] : []
      })

    var measureHeight = yScale.rangeBand() * 0.5

    var initAttr = {
      'class': 'comparative-measure',
      'width': 3,
      'height': yScale.rangeBand() + measureHeight,
      'y': -measureHeight / 2
    }

    measure.enter().append('rect').attr(initAttr)
      .style('fill', 'inherit')
    measure.attr(initAttr).attr('x', x)
    measure.exit().remove()

    var label = bar.selectAll('.label')
      .data(function (d) {
        var v = options.value(d)
        return _.isFinite(v) ? [v] : []
      })

    label.enter()
      .append('text')
      .attr({
        'class': 'label'
      })

    label
      .attr({
        'x': w,
        'y': -15,
        'text-anchor': 'end',
        'dy': (options.lineHeight / 4) + 'em',
        'transform': 'translate(0, ' + (h / 2) + ')',
        'fill': 'inherit'
      })
      .style('font-size', options.fontSize)
      .text(options.format)
    label.exit().remove()

    var compareValue = bar.selectAll('.comparative-text')
      .data(function (d) {
        var v = options.value(d)
        return [options.valueText(v)]
      })

    compareValue.enter().append('text')
      .attr('class', 'comparative-text')

    compareValue
      .attr({
        'x': 2,
        'y': 0,
        'text-anchor': 'start',
        'dy': (options.lineHeight / 4) + 'em',
        'transform': 'translate(0, ' + (h / 2) + ')',
        'fill': '#FFFFFF'
      })
      .style('font-size', options.fontSize - 2)
      .text(function (d) {
        return d
      })
    compareValue.exit().remove()
  },

  resize: function (el) {}
})

module.exports = BulletChart
<|endoftext|>


<commit_before>import React, { PropTypes, Component } from 'react'
import Biro from 'biro'
import RaisedButton from 'material-ui/RaisedButton'
import Chip from 'material-ui/Chip'
import {pinkA700} from 'material-ui/styles/colors'
import RefreshIndicator from 'material-ui/RefreshIndicator'
import library from 'biro-material-ui'
import layout from 'biro-material-ui/layout'

const blockStyle = {
  marginTop: '20px',
}

const errorChipStyle = {
  margin:'4px',
  marginTop:'10px'
}

const errorLabelStyle = {
  color:'white'
}

const refreshStyle = {
  display: 'inline-block',
  position: 'relative'
}

class Form extends Component {

  submit() {
    this.props.submit && this.props.submit(this.props.data, this.props.meta)
  }

  render() {

    const merged_library = Object.assign({}, library, this.props.library)

    const errorDiv = this.props.error && !this.props.loading ? (
      <Chip
        backgroundColor={pinkA700}
        labelStyle={errorLabelStyle}
        style={errorChipStyle}
      >
        {this.props.error}
      </Chip>
    ) : null

    const submitButton = this.props.loading ? (
      <RefreshIndicator
        size={40}
        left={10}
        top={0}
        status="loading"
        style={refreshStyle}
      />
    ) : (
      <RaisedButton
        label={this.props.title || 'Submit'}
        primary={true}
        onClick={this.submit.bind(this)}
      />
    )

    return (

        <Biro
          data={this.props.data}
          meta={this.props.meta}
          library={merged_library}
          layout={layout}
          schema={this.props.schema}
          validate={this.props.validate}
          update={this.props.update}
        />

          {submitButton}

          {errorDiv}

        {this.props.children}

    )
  }

}

export default Form<commit_msg>point into /lib<commit_after>import React, { PropTypes, Component } from 'react'
import Biro from 'biro'
import RaisedButton from 'material-ui/RaisedButton'
import Chip from 'material-ui/Chip'
import {pinkA700} from 'material-ui/styles/colors'
import RefreshIndicator from 'material-ui/RefreshIndicator'
import library from 'biro-material-ui'
import layout from 'biro-material-ui/lib/layout'

const blockStyle = {
  marginTop: '20px',
}

const errorChipStyle = {
  margin:'4px',
  marginTop:'10px'
}

const errorLabelStyle = {
  color:'white'
}

const refreshStyle = {
  display: 'inline-block',
  position: 'relative'
}

class Form extends Component {

  submit() {
    this.props.submit && this.props.submit(this.props.data, this.props.meta)
  }

  render() {

    const merged_library = Object.assign({}, library, this.props.library)

    const errorDiv = this.props.error && !this.props.loading ? (
      <Chip
        backgroundColor={pinkA700}
        labelStyle={errorLabelStyle}
        style={errorChipStyle}
      >
        {this.props.error}
      </Chip>
    ) : null

    const submitButton = this.props.loading ? (
      <RefreshIndicator
        size={40}
        left={10}
        top={0}
        status="loading"
        style={refreshStyle}
      />
    ) : (
      <RaisedButton
        label={this.props.title || 'Submit'}
        primary={true}
        onClick={this.submit.bind(this)}
      />
    )

    return (

        <Biro
          data={this.props.data}
          meta={this.props.meta}
          library={merged_library}
          layout={layout}
          schema={this.props.schema}
          validate={this.props.validate}
          update={this.props.update}
        />

          {submitButton}

          {errorDiv}

        {this.props.children}

    )
  }

}

export default Form<|endoftext|>


<commit_before>/**
 * Created by shaibenvalid on 1/20/17.
 */

var gameOptions = {
    gameWidth: 960,    // game width, in pixels
    gameHeight: 600,   // game height, in pixels
    tileSize: 60,     // tile size, in pixels
    colors: [0xff0000, 0x00ff00, 0x0000ff, 0xffff00] // tile colors
};

var gameLevelObj = new GameLevel();

var gameLevelData = gameLevelObj.getData();
var gameLevelParams = gameLevelObj.getParams();
var CompletedData;

var agents = [];

var obsticles = [];
var houses = [];
var mosques = [];
var roads = [];

window.onload = function () {

    //  Note that this html file is set to pull down Phaser 2.5.0 from the JS Delivr CDN.
    //  Although it will work fine with this tutorial, it's almost certainly not the most current version.
    //  Be sure to replace it with an updated version before you start experimenting with adding your own code.

    this.game = new Phaser.Game(960, 600, Phaser.AUTO, '', {
        preload: PreLoader.preload,
        create: create,
        update: update
    });
    var gameContext = this;
    this.game.getEntityFromTile = getEntityFromTile;

    this.game.waitingToStart = true;
    this.game.gameStarted = false;
    this.game.gameEnded = false;

    this.game.levelState = {
        emittedAgents: 0,
        lostAgents: 0,
        convertedAgents: 0
    };

    function update() {
        if (this.game.waitingToStart) {
            if (this.game.input.keyboard.isDown(Phaser.Keyboard.SPACEBAR)) {
                this.game.initialDialog.kill();
                this.game.waitingToStart = false;
                this.game.gameStarted = true;
                this.game.timer.start();
            }
        } else {
            if (!this.game.gameEnded) {
                updateBuldings();
                updateAgents();
                updateCounters();
                checkIfGameEnded();
            }
        }
    }

    function checkIfGameEnded() {
        var totalAgentNumber = gameLevelParams.totalAgentNumber;
        var convertTarget = gameLevelParams.convertTarget;
        var lostAgents = this.game.levelState.lostAgents;
        var convertedAgents = this.game.levelState.convertedAgents;
        if (this.game.timer.isTimeOver() || lostAgents > totalAgentNumber - convertTarget) {
            this.endGameAsLose();
        }
        if (convertedAgents > convertTarget) {
            this.endGameAsWin();
        }
    }
    ;

    function endGameAsLose() {
        this.game.gameEnded = true;
        this.game.add.sprite(480, 300, 'you_lost');
    };

    function endGameAsWin() {
        this.game.gameEnded = true;
        this.game.add.sprite(480, 300, 'you_won');
    };

    function create() {
        this.game.physics.startSystem(Phaser.Physics.ARCADE);

        drawBoard(gameLevelData);
        CompletedData = gameLevelObj.getCompleteData();
        BankFactory.init(this.game, CompletedData);
        ExitFactory.init(this.game);
        createAgents();

        this.game.initialDialog = new ImageEntity(this.game, 480, 300, "initial_dialog");
        this.game.add.existing(this.game.initialDialog);

        this.game.timer = new Timer(this.game, 870, 570, {
            minutes: gameLevelParams.time.minutes,
            seconds: gameLevelParams.time.seconds
        });
        this.game.add.existing(this.game.timer);

        var style = {font: "16pt Arial", fill: "#C0EAFF", align: "center"};
        game.add.text(600, 565, "Emitted Agents", style);
        game.add.text(400, 565, "Converted Agents", style);
        game.add.text(250, 565, "Lost Agents", style);

        this.game.emittedAgentsText = game.add.text(670, 540, String(this.game.levelState.emittedAgents), style);
        this.game.convertedAgentsText = game.add.text(490, 540, String(this.game.levelState.convertedAgents), style);
        this.game.lostAgentsText = game.add.text(300, 540, String(this.game.levelState.lostAgents), style);
    }

    function drawBoard(board) {
        for (var i = 0; i < board.length; i++) {
            var row = board[i];
            for (var j = 0; j < row.length; j++) {
                var tileType = row[j];
                var x = j * gameOptions.tileSize;
                var y = (i + 1) * gameOptions.tileSize;
                if (tileType == 0) {
                    var assetName = 'block';
                }
                else {
                    var assetName = gameLevelObj.getAssetNameById(tileType - 1);
                    var tileObject = gameLevelObj.getObjectTypeByTileType(tileType);
                    var entity = null;
                    if (tileObject) { //TODO: fix this
                        switch (tileObject) {
                            case "Obsticle":
                                entity = new Obsticle(this.game, x, y, assetName);
                                obsticles.push(entity);
                                break;
                            case "House":
                                entity = new House(this.game, x, y, assetName, agents);
                                houses.push(entity);
                                break;
                            case "Mosque":
                                entity = new Mosque(this.game, x, y, assetName);
                                mosques.push(entity);
                                break;
                            case "Road":
                                entity = new Road(this.game, x, y, assetName, tileType, j, i);
                                roads.push(entity);
                                break;
                        }
                    }
                    if (entity) {
                        entity.anchor.set(0, 1);
                        this.game.add.existing(entity);
                    } else {
                        var sprite = this.game.add.sprite(x, y, assetName);
                        sprite.anchor.set(0, 1);
                    }
                }
            }
        }
    }

    /*
     TODO: will move to emitter
     */
    function createAgents() {
        var agent = new Agent(this.game, 300 + 30, 10, 2, 0, 1);
        this.game.add.existing(agent);
        agents.push(agent);
    }

    function updateBuldings() {
        var buildings = mosques.concat(houses);
        for (var i = 0; i < buildings.length; i++) {
            var building = buildings[i];
            building.doTick(new Date());
        }
    }

    function updateAgents() {
        for (var i = 0; i < agents.length; i++) {
            agents[i].update();
        }

    }

    function updateCounters() {
        this.game.emittedAgentsText.setText(String(this.game.levelState.emittedAgents));
        this.game.convertedAgentsText.setText(String(this.game.levelState.convertedAgents));
        this.game.lostAgentsText.setText(String(this.game.levelState.lostAgents));
    }

    function getEntityFromTile(type, row, col) {
        var collection = [];
        if (type == 'road') {
            collection = roads;
        }
        if (type == 'mosque') {
            collection = mosques;
        }
        if (type == 'agent') {
            collection = agents;
        }
        for (var i = 0; i < collection.length; i++) {
            var entity = collection[i];
            if (entity.row == row && entity.col == col) {
                return entity;
            }
        }
        return null;
    }

};
<commit_msg>fix road<commit_after>/**
 * Created by shaibenvalid on 1/20/17.
 */

var gameOptions = {
    gameWidth: 960,    // game width, in pixels
    gameHeight: 600,   // game height, in pixels
    tileSize: 60,     // tile size, in pixels
    colors: [0xff0000, 0x00ff00, 0x0000ff, 0xffff00] // tile colors
};

var gameLevelObj = new GameLevel();

var gameLevelData = gameLevelObj.getData();
var gameLevelParams = gameLevelObj.getParams();
var CompletedData;

var agents = [];

var obsticles = [];
var houses = [];
var mosques = [];
var roads = [];

window.onload = function () {

    //  Note that this html file is set to pull down Phaser 2.5.0 from the JS Delivr CDN.
    //  Although it will work fine with this tutorial, it's almost certainly not the most current version.
    //  Be sure to replace it with an updated version before you start experimenting with adding your own code.

    this.game = new Phaser.Game(960, 600, Phaser.AUTO, '', {
        preload: PreLoader.preload,
        create: create,
        update: update
    });
    var gameContext = this;
    this.game.getEntityFromTile = getEntityFromTile;

    this.game.waitingToStart = true;
    this.game.gameStarted = false;
    this.game.gameEnded = false;

    this.game.levelState = {
        emittedAgents: 0,
        lostAgents: 0,
        convertedAgents: 0
    };

    function update() {
        if (this.game.waitingToStart) {
            if (this.game.input.keyboard.isDown(Phaser.Keyboard.SPACEBAR)) {
                this.game.initialDialog.kill();
                this.game.waitingToStart = false;
                this.game.gameStarted = true;
                this.game.timer.start();
            }
        } else {
            if (!this.game.gameEnded) {
                updateBuldings();
                updateAgents();
                updateCounters();
                checkIfGameEnded();
            }
        }
    }

    function checkIfGameEnded() {
        var totalAgentNumber = gameLevelParams.totalAgentNumber;
        var convertTarget = gameLevelParams.convertTarget;
        var lostAgents = this.game.levelState.lostAgents;
        var convertedAgents = this.game.levelState.convertedAgents;
        if (this.game.timer.isTimeOver() || lostAgents > totalAgentNumber - convertTarget) {
            this.endGameAsLose();
        }
        if (convertedAgents > convertTarget) {
            this.endGameAsWin();
        }
    }
    ;

    function endGameAsLose() {
        this.game.gameEnded = true;
        this.game.add.sprite(480, 300, 'you_lost');
    };

    function endGameAsWin() {
        this.game.gameEnded = true;
        this.game.add.sprite(480, 300, 'you_won');
    };

    function create() {
        this.game.physics.startSystem(Phaser.Physics.ARCADE);

        drawBoard(gameLevelData);
        CompletedData = gameLevelObj.getCompleteData();
        BankFactory.init(this.game, CompletedData);
        ExitFactory.init(this.game);
        createAgents();

        this.game.initialDialog = new ImageEntity(this.game, 480, 300, "initial_dialog");
        this.game.add.existing(this.game.initialDialog);

        this.game.timer = new Timer(this.game, 870, 570, {
            minutes: gameLevelParams.time.minutes,
            seconds: gameLevelParams.time.seconds
        });
        this.game.add.existing(this.game.timer);

        var style = {font: "16pt Arial", fill: "#C0EAFF", align: "center"};
        game.add.text(600, 565, "Emitted Agents", style);
        game.add.text(400, 565, "Converted Agents", style);
        game.add.text(250, 565, "Lost Agents", style);

        this.game.emittedAgentsText = game.add.text(670, 540, String(this.game.levelState.emittedAgents), style);
        this.game.convertedAgentsText = game.add.text(490, 540, String(this.game.levelState.convertedAgents), style);
        this.game.lostAgentsText = game.add.text(300, 540, String(this.game.levelState.lostAgents), style);
    }

    function drawBoard(board) {
        for (var i = 0; i < board.length; i++) {
            var row = board[i];
            for (var j = 0; j < row.length; j++) {
                var tileType = row[j];
                var x = j * gameOptions.tileSize;
                var y = (i + 1) * gameOptions.tileSize;
                if (tileType == 0) {
                    var assetName = 'block';
                }
                else {
                    var assetName = gameLevelObj.getAssetNameById(tileType - 1);
                    var tileObject = gameLevelObj.getObjectTypeByTileType(tileType);
                    var entity = null;
                    if (tileObject) { //TODO: fix this
                        switch (tileObject) {
                            case "Obsticle":
                                entity = new Obsticle(this.game, x, y, assetName);
                                obsticles.push(entity);
                                break;
                            case "House":
                                entity = new House(this.game, x, y, assetName, agents);
                                houses.push(entity);
                                break;
                            case "Mosque":
                                entity = new Mosque(this.game, x, y, assetName);
                                mosques.push(entity);
                                break;
                            case "Road":
                                entity = new Road(this.game, x, y, assetName, tileType, i, j);
                                roads.push(entity);
                                break;
                        }
                    }
                    if (entity) {
                        entity.anchor.set(0, 1);
                        this.game.add.existing(entity);
                    } else {
                        var sprite = this.game.add.sprite(x, y, assetName);
                        sprite.anchor.set(0, 1);
                    }
                }
            }
        }
    }

    /*
     TODO: will move to emitter
     */
    function createAgents() {
        var agent = new Agent(this.game, 300 + 30, 10, 2, 0, 1);
        this.game.add.existing(agent);
        agents.push(agent);
    }

    function updateBuldings() {
        var buildings = mosques.concat(houses);
        for (var i = 0; i < buildings.length; i++) {
            var building = buildings[i];
            building.doTick(new Date());
        }
    }

    function updateAgents() {
        for (var i = 0; i < agents.length; i++) {
            agents[i].update();
        }

    }

    function updateCounters() {
        this.game.emittedAgentsText.setText(String(this.game.levelState.emittedAgents));
        this.game.convertedAgentsText.setText(String(this.game.levelState.convertedAgents));
        this.game.lostAgentsText.setText(String(this.game.levelState.lostAgents));
    }

    function getEntityFromTile(type, row, col) {
        var collection = [];
        if (type == 'road') {
            collection = roads;
        }
        if (type == 'mosque') {
            collection = mosques;
        }
        if (type == 'agent') {
            collection = agents;
        }
        for (var i = 0; i < collection.length; i++) {
            var entity = collection[i];
            if (entity.row == row && entity.col == col) {
                return entity;
            }
        }
        return null;
    }

};
<|endoftext|>


<commit_before>angular.module('queup.factory', [])

.factory('queupFactory', function($http){

  var addNewClass = function(newClassName){
    console.log(newClassName)
    var token = window.localStorage.getItem('clientToken');

    return $http({
      method: 'POST',
      url: 'http://localhost:8000/api/teachers/addClass',
      headers: {
        user_role: 'teacher',
        access_token: token
      },
      dataType: 'JSON',
      data:{
        classTitle: newClassName
      }
    })
    .success(function(data){
      console.dir('success data below:');
      console.dir(data);
    })
    .error(function(data){
      console.dir('error data below:');
      console.dir(data);
    })
  };

  var teacherGetClassList = function(){
    var token = window.localStorage.getItem('clientToken');
    // return new Promise(function(resolve, reject) {
      return $http({
        method: 'GET',
        url: 'http://localhost:8000/api/teachers/getClassList',
        headers: {
          user_role: 'teacher',
          access_token: token
        }
      })
  };

  var teacherGetStudentList = function(class_ID){
    console.log("class_ID value inside services: ", class_ID);

    var token = window.localStorage.getItem('clientToken');

    return $http({
      method: 'GET',
      url: 'http://localhost:8000/api/teachers/getStudentList?classid='+ class_ID,
      headers: {
        user_role: 'teacher',
        access_token: token
      }
    })
  };

  return {
    addNewClass: addNewClass,
    teacherGetClassList: teacherGetClassList,
    teacherGetStudentList: teacherGetStudentList
  }
});

// Socket Factory
// --------------
angular.module('socket.io', [])
.factory('socket', function($rootScope) {

  // Create connection with server that is within the
  // factory (maintains connection across different views)
  var socketio = io.connect('http://localhost:8000');

  // Wrapped socket.IO methods (on, emit, removeListener(s))
  // so that they can be handled correctly within view scopes
  return {
    on: function(event, cb) {
      socketio.on(event, function() {
        var args = arguments;
        $rootScope.$apply(function() {
          cb.apply(socketio,args);
        })
      });
    },

    emit: function(event, data, cb) {
      if(typeof cb === 'function') {
        socketio.emit(event, data, function() {
          var args = arguments;
          $rootScope.$apply(function() {
            cb.apply(socketio, args);
          })
        })
      } else {
        socketio.emit(event, data);
      }
    },

    off: function(event, cb) {
      if(typeof cb === 'function') {
        socketio.removeListener(event, cb);
      } else {
        socketio.removeAllListeners(event);
      }
    }
  }

});

<commit_msg>change serverURL<commit_after>angular.module('queup.factory', [])

.factory('queupFactory', function($http, $rootScope){

  $rootScope.serverURL = 'http://queup.io';

  var addNewClass = function(newClassName){
    console.log(newClassName)
    var token = window.localStorage.getItem('clientToken');

    return $http({
      method: 'POST',
      url: $rootScope.serverURL + '/api/teachers/addClass',
      headers: {
        user_role: 'teacher',
        access_token: token
      },
      dataType: 'JSON',
      data:{
        classTitle: newClassName
      }
    })
    .success(function(data){
      console.dir('success data below:');
      console.dir(data);
    })
    .error(function(data){
      console.dir('error data below:');
      console.dir(data);
    })
  };

  var teacherGetClassList = function(){
    var token = window.localStorage.getItem('clientToken');
    // return new Promise(function(resolve, reject) {
      return $http({
        method: 'GET',
        url: $rootScope.serverURL + '/api/teachers/getClassList',
        headers: {
          user_role: 'teacher',
          access_token: token
        }
      })
  };

  var teacherGetStudentList = function(class_ID){
    console.log("class_ID value inside services: ", class_ID);

    var token = window.localStorage.getItem('clientToken');

    return $http({
      method: 'GET',
      url: $rootScope.serverURL + '/api/teachers/getStudentList?classid='+ class_ID,
      headers: {
        user_role: 'teacher',
        access_token: token
      }
    })
  };

  return {
    addNewClass: addNewClass,
    teacherGetClassList: teacherGetClassList,
    teacherGetStudentList: teacherGetStudentList
  }
});

// Socket Factory
// --------------
angular.module('socket.io', [])
.factory('socket', function($rootScope) {

  // Create connection with server that is within the
  // factory (maintains connection across different views)
  var socketio = io.connect( $rootScope.serverURL);

  // Wrapped socket.IO methods (on, emit, removeListener(s))
  // so that they can be handled correctly within view scopes
  return {
    on: function(event, cb) {
      socketio.on(event, function() {
        var args = arguments;
        $rootScope.$apply(function() {
          cb.apply(socketio,args);
        })
      });
    },

    emit: function(event, data, cb) {
      if(typeof cb === 'function') {
        socketio.emit(event, data, function() {
          var args = arguments;
          $rootScope.$apply(function() {
            cb.apply(socketio, args);
          })
        })
      } else {
        socketio.emit(event, data);
      }
    },

    off: function(event, cb) {
      if(typeof cb === 'function') {
        socketio.removeListener(event, cb);
      } else {
        socketio.removeAllListeners(event);
      }
    }
  }

});

<|endoftext|>