<commit_before>/**
 *  @namespace
 *  @description
 *  dynamically create forms using a json description of form fields.
 *  Forms are added to the DOM programatically - no html required.
 *  New form field types incl. validation can be added easily.
 **/
schnipp.dynforms = {}

/**
 * @constructor
 * @description
 * the schnippform - give it a schema and some data and it`ll be your form
 *
 * @param {schnipp.dynforms.schema} schema the schema of the form.
 * @param {data} data object in the format defined by schema
 **/
schnipp.dynforms.form = function(schema, data) {

    var self = {}

    /**
     * @name schnipp.dynforms.form#schema
     * @type {schnipp.dynforms.schema}
     **/
    self.schema = schema
    self.data = data || {}
    self.fields = {}
    self.field_schemata = {}
    self.dom = {}

    /**
     * @name schnipp.dynforms.form#render_fieldset
     * @param {object} fieldset obj
     **/
    self.render_fieldset = function(fieldset) {

        var classes = fieldset.classes.join(' ')
        if (classes) {
            classes = ' class="' + classes + '"'
        }
        var res = $('

')
        var holder = res
        if (fieldset.label) {
            res.append($('
' + fieldset.label + '
'))
            holder = $('

')
            res.append(holder)
        }
        holder.append(self.render_fields(fieldset.fields_display))

        return res
    }

    /**
     * @name schnipp.dynforms.form#render_fieldsets
     * @param {object} fieldset obj
     **/
    self.render_fieldsets = function(fieldsets) {
        var res = $('

')
        for (var i = 0; i < fieldsets.length; i++) {
            var fieldset = fieldsets[i]
            res.append(self.render_fieldset(fieldset))
        }
        return res
    }

    /**
     * @name schnipp.dynforms.form#render_fields
     * @param {object} fieldset obj
     **/
    self.render_fields = function(field_tree) {
        var res = $('

')
        for (var i = 0; i < field_tree.length;   i++) {
            var entry = field_tree[i]
            if ($.isArray(entry)) {
                var row = $('

')
                for (var j = 0; j < entry.length; j++) {
                    var col = entry[j]
                    var field_schema = self.field_schemata[col]
                    var field = self.fields[field_schema.name]
                    var rendered = field.render()
                    rendered.css({
                        'display': 'inline-block',
                        'float': 'left'
                    })
                    row.append(rendered)
                }
                res.append(row)
                res.append($('

'))
            } else {
                var field_schema = self.field_schemata[entry]
                var field = self.fields[field_schema.name]
                res.append(field.render())
            }
        }
        return res
    }

    /**
     * render the form
     *
     * @returns {jquery.nodelist} html of rendered form as
     * jquery nodelist ready for dom insertion
     * @name schnipp.dynforms.form#render
     **/
    self.render = function() {
        self.fields = {}
        self.field_schemata = {}
        for (var i = 0; i < self.schema.fields.length; i++) {
            var field_schema = self.schema.fields[i]
            var field = schnipp.dynforms.fields[field_schema.type](field_schema, self.data[field_schema.name])
            self.field_schemata[field_schema.name] = field_schema
            self.fields[field_schema.name] = field
        }
        var res = $('<form class="schnippforms-form"></form>')
        if (self.schema.label) {
             res.append($('
' + self.schema.label + '
'))
        }
        var holder = $('

')
        res.append(holder)

        if (self.schema['fieldsets'] != undefined) {
            holder.append(self.render_fieldsets(schema.fieldsets))
        } else if (self.schema['fields_display'] != undefined) {
            holder.append(self.render_fields(schema.fields_display))
        } else {
            for (var i = 0; i < schema.fields.length; i++) {
                var field_schema = schema.fields[i]
                var field = self.fields[field_schema.name]
                holder.append(field.render())
            }
        }

        self.dom.main = res

        self.dom.main.submit(function() {
            self.show_spinner()
            self.onsubmit(self)
            return false
        })

        return res
    }

    /**
     * @name schnipp.dynforms.form#render_with_submit
     * render the form including a submit button.
     *
     * @returns {jquery.nodelist} html of rendered form as
     * jquery nodelist ready for dom insertion
     **/
    self.render_with_submit = function(value) {
        var submit_row = $('
')
        var submit = $('<input type="submit"/>', {'value': value})
        submit_row.append(submit)

        self.dom.main = self.render()
        self.dom.main.append($(submit_row))

        return self.dom.main
    }

    self.onsubmit = function() {}

    self.show_spinner = function() {
        self.dom.main.addClass('schnappdocs-spinner')
    }

    self.hide_spinner = function() {
        self.dom.main.removeClass('schnappdocs-spinner')
    }

    /**
     * get current form data as object according to the form`s schema.
     * @returns {object} form data
     * @name schnipp.dynforms.form#get_data
     **/
    self.get_data = function() {
        var data = {}
        for (var i = 0; i < self.schema.fields.length; i++) {
            var field_schema = schema.fields[i]
            var field = self.fields[field_schema.name]
            data[field_schema.name] = field.get_data()
        }
        return data
    }

    /**
     * run form validation
     * @returns {object} validation results contain a boolean property <tt>valid</tt>
     * and a property <tt>fields</tt> that contains a mapping of
     * fieldname to list of errors of that field.
     * @name schnipp.dynforms.form#do_validate
     **/
    self.do_validate = function() {
        var data = {
            valid: true,
            fields: {}
        }
        for (var i = 0; i < self.schema.fields.length; i++) {
            var field_schema = schema.fields[i]
            var field = self.fields[field_schema.name]
            var result = field.do_validate()
            if (!result.valid) {
                data.valid = false
            }
            data.fields[field_schema.name] = result
        }
        return data
    }

    /**
     * run form validation
     * @returns {boolean} true if form data contains no errors, false otherwise.
     * @name schnipp.dynforms.form#is_valid
     **/
    self.is_valid = function() {
        return self.do_validate().valid
    }

    /**
     * set data of the form
     * @param {object} data form data in format defined by schema.
     * @name schnipp.dynforms.form#set_data
     **/
    self.set_data = function(data) {
        for (var i = 0; i < self.schema.fields.length; i++) {
            var field_schema = self.schema.fields[i]
            var field = self.fields[field_schema.name]
            field.set_data(data[field_schema.name] || field_schema.default_value)
        }
    }

    /**
     * initialize the form after rendering it
     * @name schnipp.dynforms.form#initialize
     **/
    self.initialize = function(data) {
        /* initialize fields */
        for (var i = 0; i < self.schema.fields.length; i++) {
            var field_schema = schema.fields[i]
            var field = self.fields[field_schema.name]
            field.initialize()
        }
        /* form funkyness */
        self.dom.main.children('div').children('div').children('.collapse').children('h3').click(function() {
            var self = $(this)
            self.parent().toggleClass('collapsed')
            self.parent().children('div').slideToggle()
        })
        self.dom.main.children('div').children('div').children('.collapse').children('div').hide()
        self.dom.main.children('div').children('div').children('.collapse').addClass('collapsed')
    }

    /**
     * iterate the fields - pass in a function
     * @param {Function} visitor function that is called for every field <tt>f</tt> of the form
     * with the arguments <tt>[i, f]</tt>, where <tt>i</tt> is the index of the respective field.
     * @name schnipp.dynforms.form#iter_fields
     **/
    self.iter_fields = function(visitor) {
        for (var i = 0; i < self.schema.fields.length; i++) {
            var field_schema = schema.fields[i]
            var field = self.fields[field_schema.name]
            visitor(i, field)
        }
    }

    /**
     * get the schema of a field
     * @param name name of the field
     * @returns {object} schema of field
     * @name schnipp.dynforms.form#get_field_schema
     **/
    self.get_field_schema = function(name) {
        for (var i = 0; i < self.schema.fields.length; i++) {
            var field_schema = schema.fields[i]
            if (field_schema.name == name)
                return field_schema
        }
    }

    /**
     * update view to display validation errors
     * @param {object} errors object that contains list of errors per fieldname.
     * @name schnipp.dynforms.form#render_errors
     **/
    self.render_errors = function(errors) {
        for (key in errors) {
            self.fields[key].render_errors(errors[key])
        }
    }

    return self
}

/**
 * @constructor
 * @extends schnipp.dynforms.form
 * @description
 * Modelform which additionally takes an entity_type instance.
 * Provides a save method.
 *
 * @param {schnipp.models.entity} entity_type
 * @param {schnipp.dynforms.schema} schema
 * @param {object} instance
 **/
schnipp.dynforms.modelform = function(entity_type, schema, instance) {

    var data = {}
    if(instance != undefined) {
        data = instance.get_data()
    } else {
        instance = entity_type(null, {})
    }

    var self = schnipp.dynforms.form(schema, data)
    self.instance = instance

    self.save = function(commit) {
        self.instance.update(self.get_data())
        if (commit == undefined || commit != undefined && commit != false) {
            // only pass the error callback
            self.instance.save(null, function(instance, errors) {
                self.render_errors(response.result)
            })
        }
        return self.instance
    }

    self.onsubmit = function(form) {
        if (form.is_valid())
            return form.save()
    }

    return self
}

/**
*   Factory for modelforms. Takes the schema, the entity_type and a
*   modifier which allows to patch the form instance.
*/
schnipp.dynforms.get_modelform = function(entity_type, schema, self_modifier) {

    self_modifier = self_modifier || function(self) {}

    return function(instance) {
        var form = schnipp.dynforms.modelform(entity_type, schema, instance)
        if (self_modifier != undefined) {
            var nform = self_modifier(form)
            if (nform != undefined) {
                form = nform
            }
        }
        return form
    }
}

/**
 * creates a form factory. Takes the schema and a modifier which
 * is used to patch the created form instances.
 * @param {schnipp.dynforms.schema} schema created forms will use this schema
 * @param {schnipp.dynforms.form# -> schnipp.dynforms.form#} instance_modifier -optional- function that is applied
 * to created forms before returning them. Can be used to wrap or patch created form instances.
 * @returns {data -> schnipp.dynforms.form#} factory function that accepts initial form data as object and returns a form instance with
 * the optional instance_modifier applied.
 **/
schnipp.dynforms.get_form_factory = function(schema, instance_modifier) {

    self_modifier = self_modifier || function(self) {}

    return function(data) {
        var form = schnipp.dynforms.form(schema, data)
        if (instance_modifier != undefined) {
            var nform = instance_modifier(form)
            if (nform != undefined) {
                form = nform
            }
        }
        return form
    }
}

/**
 * Shortcut to render a form and initialize it.
 *   Instantiates <formclass> with <instance> and inserts it into <target>.
 *   Can be used with both schnipp.dynforms.form and schnipp.dynforms.modelforms.
 */
schnipp.dynforms.insert_form = function(target, formclass, instance) {
    var form = formclass(instance)
    $(target).append(form.render_with_submit('Speichern'))
    form.initialize()
}

/**
 *renders a field in a container div with label and stuff.
 *@param {object} field_descriptor the field`s schema
 **/
schnipp.dynforms.render_field = function(field_descriptor, rendered_field, errorlist) {

    var holder = $('

')

    if (field_descriptor.label != undefined || field_descriptor.label != null) {
        var label = '' + field_descriptor.label + ' : '
        holder.append(label)
    }

    holder.append(rendered_field)

    if (errorlist != undefined)
        rendered_field.after(errorlist)

    return holder
}

<commit_msg>consistently access dynform.schema using self<commit_after>/**
 *  @namespace
 *  @description
 *  dynamically create forms using a json description of form fields.
 *  Forms are added to the DOM programatically - no html required.
 *  New form field types incl. validation can be added easily.
 **/
schnipp.dynforms = {}

/**
 * @constructor
 * @description
 * the schnippform - give it a schema and some data and it`ll be your form
 *
 * @param {schnipp.dynforms.schema} schema the schema of the form.
 * @param {data} data object in the format defined by schema
 **/
schnipp.dynforms.form = function(schema, data) {

    var self = {}

    /**
     * @name schnipp.dynforms.form#schema
     * @type {schnipp.dynforms.schema}
     **/
    self.schema = schema
    self.data = data || {}
    self.fields = {}
    self.field_schemata = {}
    self.dom = {}

    /**
     * @name schnipp.dynforms.form#render_fieldset
     * @param {object} fieldset obj
     **/
    self.render_fieldset = function(fieldset) {

        var classes = fieldset.classes.join(' ')
        if (classes) {
            classes = ' class="' + classes + '"'
        }
        var res = $('

')
        var holder = res
        if (fieldset.label) {
            res.append($('
' + fieldset.label + '
'))
            holder = $('

')
            res.append(holder)
        }
        holder.append(self.render_fields(fieldset.fields_display))

        return res
    }

    /**
     * @name schnipp.dynforms.form#render_fieldsets
     * @param {object} fieldset obj
     **/
    self.render_fieldsets = function(fieldsets) {
        var res = $('

')
        for (var i = 0; i < fieldsets.length; i++) {
            var fieldset = fieldsets[i]
            res.append(self.render_fieldset(fieldset))
        }
        return res
    }

    /**
     * @name schnipp.dynforms.form#render_fields
     * @param {object} fieldset obj
     **/
    self.render_fields = function(field_tree) {
        var res = $('

')
        for (var i = 0; i < field_tree.length;   i++) {
            var entry = field_tree[i]
            if ($.isArray(entry)) {
                var row = $('

')
                for (var j = 0; j < entry.length; j++) {
                    var col = entry[j]
                    var field_schema = self.field_schemata[col]
                    var field = self.fields[field_schema.name]
                    var rendered = field.render()
                    rendered.css({
                        'display': 'inline-block',
                        'float': 'left'
                    })
                    row.append(rendered)
                }
                res.append(row)
                res.append($('

'))
            } else {
                var field_schema = self.field_schemata[entry]
                var field = self.fields[field_schema.name]
                res.append(field.render())
            }
        }
        return res
    }

    /**
     * render the form
     *
     * @returns {jquery.nodelist} html of rendered form as
     * jquery nodelist ready for dom insertion
     * @name schnipp.dynforms.form#render
     **/
    self.render = function() {
        self.fields = {}
        self.field_schemata = {}
        for (var i = 0; i < self.schema.fields.length; i++) {
            var field_schema = self.schema.fields[i]
            var field = schnipp.dynforms.fields[field_schema.type](field_schema, self.data[field_schema.name])
            self.field_schemata[field_schema.name] = field_schema
            self.fields[field_schema.name] = field
        }
        var res = $('<form class="schnippforms-form"></form>')
        if (self.schema.label) {
             res.append($('
' + self.schema.label + '
'))
        }
        var holder = $('

')
        res.append(holder)

        if (self.schema['fieldsets'] != undefined) {
            holder.append(self.render_fieldsets(self.schema.fieldsets))
        } else if (self.schema['fields_display'] != undefined) {
            holder.append(self.render_fields(self.schema.fields_display))
        } else {
            for (var i = 0; i < self.schema.fields.length; i++) {
                var field_schema = self.schema.fields[i]
                var field = self.fields[field_schema.name]
                holder.append(field.render())
            }
        }

        self.dom.main = res

        self.dom.main.submit(function() {
            self.show_spinner()
            self.onsubmit(self)
            return false
        })

        return res
    }

    /**
     * @name schnipp.dynforms.form#render_with_submit
     * render the form including a submit button.
     *
     * @returns {jquery.nodelist} html of rendered form as
     * jquery nodelist ready for dom insertion
     **/
    self.render_with_submit = function(value) {
        var submit_row = $('
')
        var submit = $('<input type="submit"/>', {'value': value})
        submit_row.append(submit)

        self.dom.main = self.render()
        self.dom.main.append($(submit_row))

        return self.dom.main
    }

    self.onsubmit = function() {}

    self.show_spinner = function() {
        self.dom.main.addClass('schnappdocs-spinner')
    }

    self.hide_spinner = function() {
        self.dom.main.removeClass('schnappdocs-spinner')
    }

    /**
     * get current form data as object according to the form`s schema.
     * @returns {object} form data
     * @name schnipp.dynforms.form#get_data
     **/
    self.get_data = function() {
        var data = {}
        for (var i = 0; i < self.schema.fields.length; i++) {
            var field_schema = self.schema.fields[i]
            var field = self.fields[field_schema.name]
            data[field_schema.name] = field.get_data()
        }
        return data
    }

    /**
     * run form validation
     * @returns {object} validation results contain a boolean property <tt>valid</tt>
     * and a property <tt>fields</tt> that contains a mapping of
     * fieldname to list of errors of that field.
     * @name schnipp.dynforms.form#do_validate
     **/
    self.do_validate = function() {
        var data = {
            valid: true,
            fields: {}
        }
        for (var i = 0; i < self.schema.fields.length; i++) {
            var field_schema = self.schema.fields[i]
            var field = self.fields[field_schema.name]
            var result = field.do_validate()
            if (!result.valid) {
                data.valid = false
            }
            data.fields[field_schema.name] = result
        }
        return data
    }

    /**
     * run form validation
     * @returns {boolean} true if form data contains no errors, false otherwise.
     * @name schnipp.dynforms.form#is_valid
     **/
    self.is_valid = function() {
        return self.do_validate().valid
    }

    /**
     * set data of the form
     * @param {object} data form data in format defined by schema.
     * @name schnipp.dynforms.form#set_data
     **/
    self.set_data = function(data) {
        for (var i = 0; i < self.schema.fields.length; i++) {
            var field_schema = self.schema.fields[i]
            var field = self.fields[field_schema.name]
            field.set_data(data[field_schema.name] || field_schema.default_value)
        }
    }

    /**
     * initialize the form after rendering it
     * @name schnipp.dynforms.form#initialize
     **/
    self.initialize = function(data) {
        /* initialize fields */
        for (var i = 0; i < self.schema.fields.length; i++) {
            var field_schema = self.schema.fields[i]
            var field = self.fields[field_schema.name]
            field.initialize()
        }
        /* form funkyness */
        self.dom.main.children('div').children('div').children('.collapse').children('h3').click(function() {
            var self = $(this)
            self.parent().toggleClass('collapsed')
            self.parent().children('div').slideToggle()
        })
        self.dom.main.children('div').children('div').children('.collapse').children('div').hide()
        self.dom.main.children('div').children('div').children('.collapse').addClass('collapsed')
    }

    /**
     * iterate the fields - pass in a function
     * @param {Function} visitor function that is called for every field <tt>f</tt> of the form
     * with the arguments <tt>[i, f]</tt>, where <tt>i</tt> is the index of the respective field.
     * @name schnipp.dynforms.form#iter_fields
     **/
    self.iter_fields = function(visitor) {
        for (var i = 0; i < self.schema.fields.length; i++) {
            var field_schema = self.schema.fields[i]
            var field = self.fields[field_schema.name]
            visitor(i, field)
        }
    }

    /**
     * get the schema of a field
     * @param name name of the field
     * @returns {object} schema of field
     * @name schnipp.dynforms.form#get_field_schema
     **/
    self.get_field_schema = function(name) {
        for (var i = 0; i < self.schema.fields.length; i++) {
            var field_schema = self.schema.fields[i]
            if (field_schema.name == name)
                return field_schema
        }
    }

    /**
     * update view to display validation errors
     * @param {object} errors object that contains list of errors per fieldname.
     * @name schnipp.dynforms.form#render_errors
     **/
    self.render_errors = function(errors) {
        for (key in errors) {
            self.fields[key].render_errors(errors[key])
        }
    }

    return self
}

/**
 * @constructor
 * @extends schnipp.dynforms.form
 * @description
 * Modelform which additionally takes an entity_type instance.
 * Provides a save method.
 *
 * @param {schnipp.models.entity} entity_type
 * @param {schnipp.dynforms.schema} schema
 * @param {object} instance
 **/
schnipp.dynforms.modelform = function(entity_type, schema, instance) {

    var data = {}
    if(instance != undefined) {
        data = instance.get_data()
    } else {
        instance = entity_type(null, {})
    }

    var self = schnipp.dynforms.form(schema, data)
    self.instance = instance

    self.save = function(commit) {
        self.instance.update(self.get_data())
        if (commit == undefined || commit != undefined && commit != false) {
            // only pass the error callback
            self.instance.save(null, function(instance, errors) {
                self.render_errors(response.result)
            })
        }
        return self.instance
    }

    self.onsubmit = function(form) {
        if (form.is_valid())
            return form.save()
    }

    return self
}

/**
*   Factory for modelforms. Takes the schema, the entity_type and a
*   modifier which allows to patch the form instance.
*/
schnipp.dynforms.get_modelform = function(entity_type, schema, self_modifier) {

    self_modifier = self_modifier || function(self) {}

    return function(instance) {
        var form = schnipp.dynforms.modelform(entity_type, schema, instance)
        if (self_modifier != undefined) {
            var nform = self_modifier(form)
            if (nform != undefined) {
                form = nform
            }
        }
        return form
    }
}

/**
 * creates a form factory. Takes the schema and a modifier which
 * is used to patch the created form instances.
 * @param {schnipp.dynforms.schema} schema created forms will use this schema
 * @param {schnipp.dynforms.form# -> schnipp.dynforms.form#} instance_modifier -optional- function that is applied
 * to created forms before returning them. Can be used to wrap or patch created form instances.
 * @returns {data -> schnipp.dynforms.form#} factory function that accepts initial form data as object and returns a form instance with
 * the optional instance_modifier applied.
 **/
schnipp.dynforms.get_form_factory = function(schema, instance_modifier) {

    self_modifier = self_modifier || function(self) {}

    return function(data) {
        var form = schnipp.dynforms.form(schema, data)
        if (instance_modifier != undefined) {
            var nform = instance_modifier(form)
            if (nform != undefined) {
                form = nform
            }
        }
        return form
    }
}

/**
 * Shortcut to render a form and initialize it.
 *   Instantiates <formclass> with <instance> and inserts it into <target>.
 *   Can be used with both schnipp.dynforms.form and schnipp.dynforms.modelforms.
 */
schnipp.dynforms.insert_form = function(target, formclass, instance) {
    var form = formclass(instance)
    $(target).append(form.render_with_submit('Speichern'))
    form.initialize()
}

/**
 *renders a field in a container div with label and stuff.
 *@param {object} field_descriptor the field`s schema
 **/
schnipp.dynforms.render_field = function(field_descriptor, rendered_field, errorlist) {

    var holder = $('

')

    if (field_descriptor.label != undefined || field_descriptor.label != null) {
        var label = '' + field_descriptor.label + ' : '
        holder.append(label)
    }

    holder.append(rendered_field)

    if (errorlist != undefined)
        rendered_field.after(errorlist)

    return holder
}

<|endoftext|>


<commit_before>/*
 * Copyright 2014, Gregg Tavares.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Gregg Tavares. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
"use strict";

define(function() {

  /**
   * @constructor
   * @param {!HTMLElement} element Element to turn into progress
   *        bar.
   */
  var ProgressBar = function(element) {
    var progressBar = document.createElement("div");
    element.appendChild(progressBar);

    /**
     * Sets the progress bar size.
     * @param {number} amount The amount of progress where 0 = no
     *        progress and 1 = completed. 0.5 = half completed.
     */
    this.set = function(amount) {
      progressBar.style.width = (Math.max(0, Math.min(1, amount)) * 100 | 0) + "%";
    };

    this.set(0);
  };

  return ProgressBar;
});

<commit_msg>add show to progress<commit_after>/*
 * Copyright 2014, Gregg Tavares.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Gregg Tavares. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
"use strict";

define(function() {

  /**
   * @constructor
   * @param {!HTMLElement} element Element to turn into progress
   *        bar.
   */
  var ProgressBar = function(element) {
    var progressBar = document.createElement("div");
    element.appendChild(progressBar);

    /**
     * Sets the progress bar size.
     * @param {number} amount The amount of progress where 0 = no
     *        progress and 1 = completed. 0.5 = half completed.
     */
    this.set = function(amount) {
      progressBar.style.width = (Math.max(0, Math.min(1, amount)) * 100 | 0) + "%";
    };

    this.set(0);

    this.show = function(show) {
      element.style.display = show ? "block" : "none";
    };
  };

  return ProgressBar;
});

<|endoftext|>


<commit_before>import React from 'react';
import { match } from 'react-router';

import renderApp from './renderApp';
import createStore from '../createStore';
import prefetchData from './prefetchData';

export default (req, res, options) => {

    const { routes, reducers, routesFetchersMap } = options;

    match({ routes, location: req.path }, (error, redirectLocation, renderProps) => {
        if (error) {
          console.log(error);
          return res.status(500).end('Internal server error');
        }
        if (redirectLocation) {
          return res.status(301).redirect(redirectLocation.pathname);
        }
        if (! renderProps) {
          return res.status(404).end('Not found'); // TODO: render 404 on client?
        }

        const store = createStore(reducers);

        prefetchData(routesFetchersMap, renderProps.location.pathname, store)
            .then(() => renderApp(renderProps, store, options))
            .then(html => res.send(html))
            .catch(err => res.send(`Error: ${err.stack}`));
    });
}
<commit_msg>accept initialState as option<commit_after>import React from 'react';
import { match } from 'react-router';

import renderApp from './renderApp';
import createStore from '../createStore';
import prefetchData from './prefetchData';

export default (req, res, options) => {

    const { routes, reducers, initialState, routesFetchersMap } = options;

    match({ routes, location: req.path }, (error, redirectLocation, renderProps) => {
        if (error) {
          console.log(error);
          return res.status(500).end('Internal server error');
        }
        if (redirectLocation) {
          return res.status(301).redirect(redirectLocation.pathname);
        }
        if (! renderProps) {
          return res.status(404).end('Not found'); // TODO: render 404 on client?
        }

        const store = createStore(reducers, initialState);

        prefetchData(routesFetchersMap, renderProps.location.pathname, store)
            .then(() => renderApp(renderProps, store, options))
            .then(html => res.send(html))
            .catch(err => res.send(`Error: ${err.stack}`));
    });
}
<|endoftext|>


<commit_before>//////////////////////////////
// Server-Side Sandbox     //
/////////////////////////////

// var firmata = require('firmata');
// var gamma   = require('./gamma.js')

// var board = new firmata.Board('/dev/cu.usbmodem1421', function(err){
//   if (err) {
//     throw new Error(err);
//   }

//   console.log('going');

//   board.pinMode(9, board.MODES.PWM);
//   board.pinMode(10, board.MODES.PWM);
//   board.pinMode(11, board.MODES.PWM);

//   board.analogWrite(11, gamma[255]);

//   // setTimeout(function(){
//   //   board.analogWrite(10, 255);
//   // }, 1000);

//   // setTimeout(function(){
//   //   board.analogWrite(11, 255);
//   // }, 2000);

//   // board.pinMode(9, board.MODES.PWM);
//   // board.analogWrite(9, 0);

// });

//////////////////////////////
// Client-Side Sandbox     //
/////////////////////////////

console.log('quicktest');
// p5.board('/dev/cu.usbmodem1421', 'arduino');

//////////////////////
// Example Scripts //
//////////////////////

// // Board setup — obviously you may need to change the port
// p5.board('/dev/cu.usbmodem1421', 'arduino');

// // Test digital write
// var p = p5.pin(9, 'DIGITAL', 'OUTPUT');
// p.write('HIGH');

// Test PWM write
// var p = p5.pin(9, 'PWM', 'OUTPUT');
// p.write(80);

// Test digital read -- only uncomment one p.read() at a time
// var p = p5.pin(9, 'DIGITAL', 'INPUT');
// p.read(function(val){console.log(val);});
// p.read();
// setInterval(function() { console.log(p.val) }, 500);

// // Test analog read -- only uncomment one p.read() at a time
// var p = p5.pin(0, 'ANALOG', 'INPUT');
// p.read(function(val){console.log(val);});
// p.read();
// setInterval(function() { console.log(p.val) }, 500);

// // Draw ellipses with a button -- these work on the same
// // setup as the pin reads

// var p;

// function setup() {

//   p5.board('/dev/cu.usbmodem1421', 'arduino');
//   p = p5.pin(9, 'DIGITAL', 'INPUT');
//   p.read();

//   createCanvas(1200, 500);
//   noStroke();
// }

// function draw() {
//   if (p.val) {
//     fill(Math.random() * 255, Math.random() * 255, Math.random() * 255);
//     ellipse(Math.random() * width, Math.random() * height, 60, 60);
//   }
// }

// Click the circle to light the LED -- this works on the same
// setup as the pin writes
// var pin;

// function setup() {
//   createCanvas(400, 400);
//   noStroke();
//   fill(62, 0, 255);
//   ellipse(width/2, height/2, 100, 100);

//   p5.board('/dev/cu.usbmodem1421', 'arduino');
//   pin = p5.pin(9, 'DIGITAL', 'OUTPUT');
// }

// function mousePressed() {
//   var d = dist(width/2, height/2, mouseX, mouseY);
//   if (d < 100) {
//     pin.write('HIGH');
//   }
// }

// function mouseReleased() {
//   pin.write('LOW');
// }

// // Click a button to light the LED -- this works on the same
// // setup as the pin writes & uses the p5.dom lib

// function setup() {
//   createCanvas(400, 400);

//   p5.board('/dev/cu.usbmodem1421', 'arduino');
//   var pin = p5.pin(9, 'DIGITAL', 'OUTPUT');

//   var button = createButton('LIGHT THE LED!!');
//   button.position(width/2, height/2);
//   button.mousePressed(function(){
//     pin.write('HIGH');
//   });

//   button.mouseReleased(function(){
//     pin.write('LOW');
//   });
// }

// PWM Slider -- Same setup as above

// var slider, pin;

// function setup() {
//   slider = createSlider(0, 255, 150);
//   slider.position = (10, 10);

//   p5.board('/dev/cu.usbmodem1421', 'arduino');
//   pin = p5.pin(9, 'PWM', 'OUTPUT');

// }

// function draw() {
//   var val = slider.value();
//   pin.write(val);
// }

// // LED On & Off -- Same setup as above

// var led;

// function setup() {
//   p5.board('/dev/cu.usbmodem1421', 'arduino');
//   led = p5.pin(9, 'LED');
//   console.log(led);
// }

// function keyPressed() {
//   if (keyCode === LEFT_ARROW){
//     led.on();
//   } else if (keyCode === RIGHT_ARROW) {
//     led.off();
//   } else if (keyCode === UP_ARROW){
//     led.blink();
//   } else if (keyCode === DOWN_ARROW) {
//     led.noBlink();
//   }
// }

// // LED Fade on Key -- Same setup as above

// var led;

// function setup() {
//   p5.board('/dev/cu.usbmodem1421', 'arduino');
//   led = p5.pin(9, 'LED');
// }

// function keyPressed(){
//  if (keyCode === DOWN_ARROW) {
//   led.write(200);
//   led.fade(200, 0);
//  }
// }

// // LED Fade in Setup -- Same setup as above [tests queueing]

// function setup() {
//   p5.board('/dev/cu.usbmodem1421', 'arduino');
//   var led = p5.pin(9, 'LED');
//   led.write(200);
//   led.fade(200, 0);
// }
//

// // RGB LED Write -- Breadboard with common-cathode RGB LED
// plugged into pins 9, 10, 11

// function setup() {
//   p5.board('/dev/cu.usbmodem1421', 'arduino');
//   var rgb = p5.pin({r: 9, g: 10, b: 11}, 'RGBLED');
//   var c = color(65);
//   rgb.write(c);
//   fill(c);
//   noStroke();
//   ellipse(80, 80, 40, 40);
// }

// // RGB LED Read -- Same as above

// var rgb, c;

// function setup() {
//   p5.board('/dev/cu.usbmodem1421', 'arduino');
//   rgb = p5.pin({r: 9, g: 10, b: 11}, 'RGBLED');
//   c = color(Math.floor(Math.random() * 255), Math.floor(Math.random() * 255), Math.floor(Math.random() * 255));
//   rgb.write(c);
//   fill(c);
//   noStroke();
//   ellipse(80, 80, 40, 40);
// }

// function keyPressed(){
//   rgb.read(function(val){ console.log(val.toString()); });
// }

// // RGB LED On/Off/Blink -- Same as above
// var rgb, c;

// function setup() {
//   p5.board('/dev/cu.usbmodem1421', 'arduino');
//   rgb = p5.pin({r: 9, g: 10, b: 11}, 'RGBLED');
//   c = color(Math.floor(Math.random() * 255), Math.floor(Math.random() * 255), Math.floor(Math.random() * 255));
//   rgb.write(c);
//   fill(c);
//   noStroke();
//   ellipse(80, 80, 40, 40);
// }

// function keyPressed() {
//   if (keyCode === LEFT_ARROW){
//     rgb.on();
//   } else if (keyCode === RIGHT_ARROW) {
//     rgb.off();
//   } else if (keyCode === UP_ARROW){
//     rgb.blink();
//   } else if (keyCode === DOWN_ARROW) {
//     rgb.noBlink();
//   }
// }

// RGB LED Fade on Key -- Same setup as above

// var rgb;

// function setup() {
//   p5.board('/dev/cu.usbmodem1421', 'arduino');
//   rgb = p5.pin({r: 9, g: 10, b: 11}, 'RGBLED');
//   var c = color(Math.floor(Math.random() * 255), Math.floor(Math.random() * 255), Math.floor(Math.random() * 255));
//   rgb.write(c);
//   fill(c);
//   noStroke();
//   ellipse(80, 80, 40, 40);
// }

// function keyPressed(){
//  if (keyCode === DOWN_ARROW) {
//   rgb.write([200, 200, 200]);
//   rgb.fade([200, 0, 3000], [200, 0, 5000, 500], [200, 0, 1000, 50]);
//  }
// }

// // Motor tests -- Breadboard with motor power keyed to pin 9

// var motor;

// function setup() {
//   p5.board('/dev/cu.usbmodem1421', 'arduino');
//   motor = p5.pin(9, 'MOTOR');
// }

// function keyPressed() {
//   if (keyCode === LEFT_ARROW){
//     motor.on();
//   } else if (keyCode === RIGHT_ARROW) {
//     console.log('motor off called');
//     motor.off();
//   } else if (keyCode === UP_ARROW){
//     motor.write(100);
//   }
// }

// Servo Tests -- Servo plugged directly into board and pin 9

// var servo;

// function setup() {
//   p5.board('/dev/cu.usbmodem1421', 'arduino');
//   servo = p5.pin(9, 'SERVO');
//   servo.range([0, 60]);
// }

// function keyPressed() {
//    if (keyCode === LEFT_ARROW) {
//      console.log('l')
//      servo.write(15);
//    } else if (keyCode === RIGHT_ARROW) {
//      console.log('r')
//      servo.write(45);
//    } else if (keyCode === UP_ARROW) {
//      console.log('u')
//      servo.sweep();
//    } else if (keyCode === DOWN_ARROW) {
//      console.log('d')
//      servo.noSweep();
//    }
// }

// // Button tests -- Same as digital and analog read above

// var button;

// function setup() {

//   createCanvas(600, 200);

//   p5.board('/dev/cu.usbmodem1421', 'arduino');
//   button = p5.pin(9, 'BUTTON');

//   function redEllipse() {
//     console.log('pressed');
//     clear();
//     noStroke();
//     fill(255, 0, 0);
//     ellipse(100, 100, 40, 40);
//   }

//   function blueEllipse() {
//     console.log('released');
//     clear();
//     noStroke();
//     fill(0, 0, 255);
//     ellipse(200, 100, 40, 40);
//   }

//   function greenEllipse() {
//     console.log('held')
//     clear();
//     noStroke();
//     fill(0, 255, 136);
//     ellipse(300, 100, 40, 40);
//   }

//   button.read();
//   button.pressed(redEllipse);
//   button.released(blueEllipse);
//   button.held(greenEllipse, 3000);

// }
//
// // Variable Resistor Tests -- Potentiometer hooked up to A0
// var pmeter;

// function setup() {
//   p5.board('/dev/cu.usbmodem1421', 'arduino');
//   pmeter = p5.pin(0, 'VRES');

//   pmeter.read(function(val){ console.log('pmeter read', val)});
//   pmeter.range([10, 400]);
//   pmeter.threshold(600);
// }

// function keyPressed() {
//   console.log('is over?', pmeter.val, pmeter.overThreshold());
// }

// Temp Tests -- Temp sensor in A2

// var thermo;

// function setup() {
//   p5.board('/dev/cu.usbmodem1421', 'arduino');
//   thermo = p5.pin({ pin: 0, voltsIn: 5 }, 'TEMP');
//   thermo.read();
// }

// function keyPressed() {
//   if (keyCode === LEFT_ARROW) {
//     console.log('f');
//     console.log(thermo.F);
//   } else if (keyCode === RIGHT_ARROW) {
//     console.log('c');
//     console.log(thermo.C);
//   } else if (keyCode === UP_ARROW) {
//     console.log('v');
//     console.log(thermo);
//   } else if (keyCode === DOWN_ARROW) {
//     console.log('k')
//     console.log(thermo.K);
//   }
// }

// // Tone Test -- Piezo in pin 8 and ground

// var t;

// function setup() {
//   p5.board('/dev/cu.usbmodem1421', 'arduino');
//   t = p5.pin(8, 'TONE'); // Can also set mode to 'PIEZO'
// }

// function keyPressed() {
//   if (keyCode === LEFT_ARROW) {
//     console.log('note');
//     t.tone('e7', 10000)
//   } else if (keyCode === RIGHT_ARROW) {
//     console.log('freq');
//     t.tone(600, 400);
//   } else if (keyCode === UP_ARROW) {
//     console.log('up does nothing!!');
//     console.log(t);
//   } else if (keyCode === DOWN_ARROW) {
//     console.log('nT')
//     t.noTone();
//   }
// }

// // Knock Test -- Piezo in A0 and ground

// var k;

// function setup() {
//  p5.board('/dev/cu.usbmodem1421', 'arduino');
//  k = p5.pin(0, 'KNOCK'); // Can also set mode to 'PIEZO'
//  k.threshold(200);
//  k.read();
// }

// function draw() {
//   console.log(k.val, k.threshold, k.overThreshold());
// }

// // Serial Tests

// var serial;

// function setup() {
//   serial = p5.serial();
//   serial.list();

//   // serial.connect('/dev/cu.usbmodem1421');
//   // serial.read(function(data){ console.log(data); })
// }  <commit_msg>Update quicktest for board/pin refactor<commit_after>//////////////////////////////
// Server-Side Sandbox     //
/////////////////////////////

// var firmata = require('firmata');
// var gamma   = require('./gamma.js')

// var board = new firmata.Board('/dev/cu.usbmodem1421', function(err){
//   if (err) {
//     throw new Error(err);
//   }

//   console.log('going');

//   board.pinMode(9, board.MODES.PWM);
//   board.pinMode(10, board.MODES.PWM);
//   board.pinMode(11, board.MODES.PWM);

//   board.analogWrite(11, gamma[255]);

//   // setTimeout(function(){
//   //   board.analogWrite(10, 255);
//   // }, 1000);

//   // setTimeout(function(){
//   //   board.analogWrite(11, 255);
//   // }, 2000);

//   // board.pinMode(9, board.MODES.PWM);
//   // board.analogWrite(9, 0);

// });

//////////////////////////////
// Client-Side Sandbox     //
/////////////////////////////

console.log('quicktest');

//////////////////////
// Example Scripts //
//////////////////////

// // Board setup for all funcs — obviously you may need to change the port
var b = p5.board('/dev/cu.usbmodem1421', 'arduino');

// // Test digital write
// var p = b.pin(9, 'DIGITAL', 'OUTPUT');
// p.write('HIGH');

// Test PWM write
// var p = b.pin(9, 'PWM', 'OUTPUT');
// p.write(80);

// Test digital read -- only uncomment one p.read() at a time
// var p = b.pin(9, 'DIGITAL', 'INPUT');
// p.read(function(val){console.log(val);});
// p.read();
// setInterval(function() { console.log(p.val) }, 500);

// // Test analog read -- only uncomment one p.read() at a time
// var p = b.pin(0, 'ANALOG', 'INPUT');
// p.read(function(val){console.log(val);});
// p.read();
// setInterval(function() { console.log(p.val) }, 500);

// // Draw ellipses with a button -- these work on the same
// // setup as the pin reads

// var p;

// function setup() {
//   p = b.pin(9, 'DIGITAL', 'INPUT');
//   p.read();

//   createCanvas(1200, 500);
//   noStroke();
// }

// function draw() {
//   if (p.val) {
//     fill(Math.random() * 255, Math.random() * 255, Math.random() * 255);
//     ellipse(Math.random() * width, Math.random() * height, 60, 60);
//   }
// }

// Click the circle to light the LED -- this works on the same
// setup as the pin writes
// var pin;

// function setup() {
//   createCanvas(400, 400);
//   noStroke();
//   fill(62, 0, 255);
//   ellipse(width/2, height/2, 100, 100);
//   pin = b.pin(9, 'DIGITAL', 'OUTPUT');
// }

// function mousePressed() {
//   var d = dist(width/2, height/2, mouseX, mouseY);
//   if (d < 100) {
//     pin.write('HIGH');
//   }
// }

// function mouseReleased() {
//   pin.write('LOW');
// }

// // Click a button to light the LED -- this works on the same
// // setup as the pin writes & uses the p5.dom lib

// function setup() {
//   createCanvas(400, 400);
//   var pin = b.pin(9, 'DIGITAL', 'OUTPUT');

//   var button = createButton('LIGHT THE LED!!');
//   button.position(width/2, height/2);
//   button.mousePressed(function(){
//     pin.write('HIGH');
//   });

//   button.mouseReleased(function(){
//     pin.write('LOW');
//   });
// }

// PWM Slider -- Same setup as above

// var slider, pin;

// function setup() {
//   slider = createSlider(0, 255, 150);
//   slider.position = (10, 10);
//   pin = b.pin(9, 'PWM', 'OUTPUT');

// }

// function draw() {
//   var val = slider.value();
//   pin.write(val);
// }

// // LED On & Off -- Same setup as above

// var led;

// function setup() {
//   led = b.pin(9, 'LED');
//   console.log(led);
// }

// function keyPressed() {
//   if (keyCode === LEFT_ARROW){
//     led.on();
//   } else if (keyCode === RIGHT_ARROW) {
//     led.off();
//   } else if (keyCode === UP_ARROW){
//     led.blink();
//   } else if (keyCode === DOWN_ARROW) {
//     led.noBlink();
//   }
// }

// // LED Fade on Key -- Same setup as above

// var led;

// function setup() {
//   led = b.pin(9, 'LED');
// }

// function keyPressed(){
//  if (keyCode === DOWN_ARROW) {
//   led.write(200);
//   led.fade(200, 0);
//  }
// }

// // LED Fade in Setup -- Same setup as above [tests queueing]

// function setup() {
//   var led = b.pin(9, 'LED');
//   led.write(200);
//   led.fade(200, 0);
// }
//

// // RGB LED Write -- Breadboard with common-cathode RGB LED
// plugged into pins 9, 10, 11

// function setup() {
//   var rgb = b.pin({r: 9, g: 10, b: 11}, 'RGBLED');
//   var c = color(65);
//   rgb.write(c);
//   fill(c);
//   noStroke();
//   ellipse(80, 80, 40, 40);
// }

// // RGB LED Read -- Same as above

// var rgb, c;

// function setup() {
//
//   rgb = b.pin({r: 9, g: 10, b: 11}, 'RGBLED');
//   c = color(Math.floor(Math.random() * 255), Math.floor(Math.random() * 255), Math.floor(Math.random() * 255));
//   rgb.write(c);
//   fill(c);
//   noStroke();
//   ellipse(80, 80, 40, 40);
// }

// function keyPressed(){
//   rgb.read(function(val){ console.log(val.toString()); });
// }

// RGB LED On/Off/Blink -- Same as above
var rgb, c;

function setup() {
  rgb = b.pin({r: 9, g: 10, b: 11}, b.RGBLED);
  c = color(Math.floor(Math.random() * 255), Math.floor(Math.random() * 255), Math.floor(Math.random() * 255));
  rgb.write(c);
  fill(c);
  noStroke();
  ellipse(80, 80, 40, 40);
}

function keyPressed() {
  if (keyCode === LEFT_ARROW){
    rgb.on();
  } else if (keyCode === RIGHT_ARROW) {
    rgb.off();
  } else if (keyCode === UP_ARROW){
    rgb.blink();
  } else if (keyCode === DOWN_ARROW) {
    rgb.noBlink();
  }
}

// RGB LED Fade on Key -- Same setup as above

// var rgb;

// function setup() {
//   rgb = b.pin({r: 9, g: 10, b: 11}, 'RGBLED');
//   var c = color(Math.floor(Math.random() * 255), Math.floor(Math.random() * 255), Math.floor(Math.random() * 255));
//   rgb.write(c);
//   fill(c);
//   noStroke();
//   ellipse(80, 80, 40, 40);
// }

// function keyPressed(){
//  if (keyCode === DOWN_ARROW) {
//   rgb.write([200, 200, 200]);
//   rgb.fade([200, 0, 3000], [200, 0, 5000, 500], [200, 0, 1000, 50]);
//  }
// }

// // Motor tests -- Breadboard with motor power keyed to pin 9

// var motor;

// function setup() {
//   motor = b.pin(9, 'MOTOR');
// }

// function keyPressed() {
//   if (keyCode === LEFT_ARROW){
//     motor.on();
//   } else if (keyCode === RIGHT_ARROW) {
//     console.log('motor off called');
//     motor.off();
//   } else if (keyCode === UP_ARROW){
//     motor.write(100);
//   }
// }

// Servo Tests -- Servo plugged directly into board and pin 9

// var servo;

// function setup() {
//   servo = b.pin(9, 'SERVO');
//   servo.range([0, 60]);
// }

// function keyPressed() {
//    if (keyCode === LEFT_ARROW) {
//      console.log('l')
//      servo.write(15);
//    } else if (keyCode === RIGHT_ARROW) {
//      console.log('r')
//      servo.write(45);
//    } else if (keyCode === UP_ARROW) {
//      console.log('u')
//      servo.sweep();
//    } else if (keyCode === DOWN_ARROW) {
//      console.log('d')
//      servo.noSweep();
//    }
// }

// // Button tests -- Same as digital and analog read above

// var button;

// function setup() {
//   createCanvas(600, 200);
//   button = b.pin(9, 'BUTTON');

//   function redEllipse() {
//     console.log('pressed');
//     clear();
//     noStroke();
//     fill(255, 0, 0);
//     ellipse(100, 100, 40, 40);
//   }

//   function blueEllipse() {
//     console.log('released');
//     clear();
//     noStroke();
//     fill(0, 0, 255);
//     ellipse(200, 100, 40, 40);
//   }

//   function greenEllipse() {
//     console.log('held')
//     clear();
//     noStroke();
//     fill(0, 255, 136);
//     ellipse(300, 100, 40, 40);
//   }

//   button.read();
//   button.pressed(redEllipse);
//   button.released(blueEllipse);
//   button.held(greenEllipse, 3000);

// }
//
// // Variable Resistor Tests -- Potentiometer hooked up to A0
// var pmeter;

// function setup() {
//   pmeter = b.pin(0, 'VRES');
//   pmeter.read(function(val){ console.log('pmeter read', val)});
//   pmeter.range([10, 400]);
//   pmeter.threshold(600);
// }

// function keyPressed() {
//   console.log('is over?', pmeter.val, pmeter.overThreshold());
// }

// Temp Tests -- Temp sensor in A2

// var thermo;

// function setup() {
//   thermo = b.pin({ pin: 0, voltsIn: 5 }, 'TEMP');
//   thermo.read();
// }

// function keyPressed() {
//   if (keyCode === LEFT_ARROW) {
//     console.log('f');
//     console.log(thermo.F);
//   } else if (keyCode === RIGHT_ARROW) {
//     console.log('c');
//     console.log(thermo.C);
//   } else if (keyCode === UP_ARROW) {
//     console.log('v');
//     console.log(thermo);
//   } else if (keyCode === DOWN_ARROW) {
//     console.log('k')
//     console.log(thermo.K);
//   }
// }

// // Tone Test -- Piezo in pin 8 and ground

// var t;

// function setup() {
//   t = b.pin(8, 'TONE'); // Can also set mode to 'PIEZO'
// }

// function keyPressed() {
//   if (keyCode === LEFT_ARROW) {
//     console.log('note');
//     t.tone('e7', 10000)
//   } else if (keyCode === RIGHT_ARROW) {
//     console.log('freq');
//     t.tone(600, 400);
//   } else if (keyCode === UP_ARROW) {
//     console.log('up does nothing!!');
//     console.log(t);
//   } else if (keyCode === DOWN_ARROW) {
//     console.log('nT')
//     t.noTone();
//   }
// }

// // Knock Test -- Piezo in A0 and ground

// var k;

// function setup() {
//  k = b.pin(0, 'KNOCK'); // Can also set mode to 'PIEZO'
//  k.threshold(200);
//  k.read();
// }

// function draw() {
//   console.log(k.val, k.threshold, k.overThreshold());
// }

// // Serial Tests

// var serial;

// function setup() {
//   serial = p5.serial();
//   serial.list();

//   // serial.connect('/dev/cu.usbmodem1421');
//   // serial.read(function(data){ console.log(data); })
// }

// // User-declared function -- just requires a board

// var socket;

// function setup() {
//   socket = io.connect('http://localhost:8000/sensors');
// }

// function keyPressed() {
//   if (keyCode === UP_ARROW) {
//     console.log('emitting hi, check server for execution');
//     socket.emit('say hi', {message: 'sarahpants!'});
//   } else if (keyCode === DOWN_ARROW){
//     console.log('emitting hi, check server for execution');
//     socket.emit('say hi', {message: 'tiger breath!'});
//   }
// }<|endoftext|>


<commit_before>import uuid from "uuid/v4";

export default function(store) {
    const nodeArray = [{
        "x": 0.0,
        "y": 0.0,
        "z": 0.0
    }, {
        "x": 3.0,
        "y": 0.0,
        "z": 0.0
    }, {
        "x": 0.0,
        "y": 3.0,
        "z": 0.0
    }, {
        "x": 0.0,
        "y": 0.0,
        "z": 3.0
    }, {
        "x": 3.0,
        "y": 3.0,
        "z": 0.0
    }, {
        "x": 3.0,
        "y": 0.0,
        "z": 3.0
    }, {
        "x": 0.0,
        "y": 3.0,
        "z": 3.0
    }, {
        "x": 3.0,
        "y": 3.0,
        "z": 3.0
    }];
    const nodes = {};
    const nodeIds = [];
    nodeArray.forEach((node) => {
        const id = uuid();
        nodeIds.push(id);
        nodes[id] = node;
    });

    const material = uuid();
    const section = uuid();
    const combination = [
        [0, 3],
        [1, 5],
        [2, 6],
        [3, 5],
        [3, 6],
        [4, 7],
        [5, 7],
        [6, 7],
        [0, 5],
        [4, 5],
        [0, 6],
        [4, 6],
        [5, 6],
        [3, 1],
        [2, 7],
        [2, 3],
        [1, 7],
        [3, 7]
    ];
    const lines = {};
    combination.forEach((ids) => {
        lines[uuid()] = {
            n1: nodeIds[ids[0]],
            n2: nodeIds[ids[1]],
            material,
            section
        };
    });

    const materials = {
        [material]: {
            E: 1,
            G: 1
        }
    };

    const sections = {
        [section]: {
            shape: "H",
            B: 3.125,
            H: 3.2,
            tf: 0.1,
            tw: 0.125
        }
    };

    const boundaries = {};
    for (let i = 0; i < 4; ++i) {
        boundaries[uuid()] = {
            node: nodeIds[i],
            x: true,
            y: true,
            z: true,
            rx: true,
            ry: true,
            rz: true
        };
    }
    for (let i = 4; i < 8; ++i) {
        boundaries[uuid()] = {
            node: nodeIds[i],
            x: 0,
            y: 0,
            z: 0,
            rx: true,
            ry: true,
            rz: true
        };
    }

    const nodeloads = {};
    [3, 6].forEach((i) => {
        nodeloads[uuid()] = {
            node: nodeIds[i],
            x: 1.0,
            y: 0.0,
            z: 0.0,
            rx: 0.0,
            ry: 0.0,
            rz: 0.0
        };
    });

    store.dispatch("model/input/setData", {
        nodes,
        lines,
        boundaries,
        materials,
        nodeloads,
        sections
    });
};
<commit_msg>同一平面上の節点を拘束するようモデルを変更。<commit_after>import uuid from "uuid/v4";

export default function(store) {
    const nodeArray = [{
        "x": 0.0,
        "y": 0.0,
        "z": 0.0
    }, {
        "x": 3.0,
        "y": 0.0,
        "z": 0.0
    }, {
        "x": 0.0,
        "y": 3.0,
        "z": 0.0
    }, {
        "x": 3.0,
        "y": 3.0,
        "z": 0.0
    }, {
        "x": 0.0,
        "y": 0.0,
        "z": 3.0
    }, {
        "x": 3.0,
        "y": 0.0,
        "z": 3.0
    }, {
        "x": 0.0,
        "y": 3.0,
        "z": 3.0
    }, {
        "x": 3.0,
        "y": 3.0,
        "z": 3.0
    }];
    const nodes = {};
    const nodeIds = [];
    nodeArray.forEach((node) => {
        const id = uuid();
        nodeIds.push(id);
        nodes[id] = node;
    });

    const material = uuid();
    const section = uuid();
    const combination = [
        [0, 3],
        [1, 5],
        [2, 6],
        [3, 5],
        [3, 6],
        [4, 7],
        [5, 7],
        [6, 7],
        [0, 5],
        [4, 5],
        [0, 6],
        [4, 6],
        [5, 6],
        [3, 1],
        [2, 7],
        [2, 3],
        [1, 7],
        [3, 7]
    ];
    const lines = {};
    combination.forEach((ids) => {
        lines[uuid()] = {
            n1: nodeIds[ids[0]],
            n2: nodeIds[ids[1]],
            material,
            section
        };
    });

    const materials = {
        [material]: {
            E: 1,
            G: 1
        }
    };

    const sections = {
        [section]: {
            shape: "H",
            B: 3.125,
            H: 3.2,
            tf: 0.1,
            tw: 0.125
        }
    };

    const boundaries = {};
    for (let i = 0; i < 4; ++i) {
        boundaries[uuid()] = {
            node: nodeIds[i],
            x: true,
            y: true,
            z: true,
            rx: true,
            ry: true,
            rz: true
        };
    }
    for (let i = 4; i < 8; ++i) {
        boundaries[uuid()] = {
            node: nodeIds[i],
            x: 0,
            y: 0,
            z: 0,
            rx: true,
            ry: true,
            rz: true
        };
    }

    const nodeloads = {};
    [3, 6].forEach((i) => {
        nodeloads[uuid()] = {
            node: nodeIds[i],
            x: 1.0,
            y: 0.0,
            z: 0.0,
            rx: 0.0,
            ry: 0.0,
            rz: 0.0
        };
    });

    store.dispatch("model/input/setData", {
        nodes,
        lines,
        boundaries,
        materials,
        nodeloads,
        sections
    });
};
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2012 Massachusetts Institute of Technology, Adobe Systems
 * Incorporated, and other contributors. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define */

define(function (require, exports, module) {
    var AgentManager = require("AgentManager");

    /**
     * emits 'data' and 'close'.
     * 'abstract' parent class, expecting subclasses to provide
     *   _open: return a promise for the raw handle corresponding to the given query
     *   _free: release the handle
     *   _refresh: return a promise for the latest data
     */
    function Handle(agent, interval, query) {
        this._agent = agent;
        this._interval = interval;
        $(this._agent).on("disconnect", this.close.bind(this));
        this._open(query).done(function (rawHandle) {
            this._rawHandle = rawHandle;
            if (this._closed) {
                this.free();
            } else {
                this._refreshPeriodically();
            }
        }.bind(this)).fail(this.close.bind(this));
    }
    Handle.prototype = {
        free: function () {
            if ("_rawHandle" in this) {
                if (this._agent.isReady()) {
                    this._free(this._rawHandle);
                }
                delete this._rawHandle;
            }
        },
        close: function () {
            this.free();
            if (!this._closed) {
                this._closed = true;
                $(this).triggerHandler("close");
            }
        },
        _refreshPeriodically: function () {
            if (!this._closed) {
                this._refresh().done(function (data) {
                    if (!this._isEmpty(data)) {
                        $(this).triggerHandler("data", [data]);
                    }
                }.bind(this)).fail(function () {
                    console.log('[theseus] refresh failed');
                }.bind(this)).always(function () {
                    setTimeout(this._refreshPeriodically.bind(this), this._interval);
                }.bind(this));
            }
        },
        /** if returns false, the 'data' event won't be emitted */
        _isEmpty: function (data) {
            return false;
        },
    };

    /**
     * when a new agent appears, automatically creates a handle for it.
     * emits all its handles' "data" events for your convenience.
     * emits "agentDisconnected" so that you know to clear the data you've
     *   received from that agent.
     */
    function AggregateHandle(query) {
        this._query = query;
        this._handles = [];
        AgentManager.agents().forEach(this._agentConnected.bind(this));
        $(AgentManager).on("agentConnected", function (ev, agent) {
            this._agentConnected(agent)
        }.bind(this));
    }
    AggregateHandle.prototype = {
        close: function () {
            this._closed = true;
            this._handles.forEach(function (handle) { handle.close() });
            this._handles = [];
        },
        _agentConnected: function (agent) {
            if (this._closed) {
                return;
            }

            var handle = this._newHandle(agent);
            this._handles.push(handle);

            $(handle).on("data", function (ev, data) {
                $(this).triggerHandler("data", [{ agent: agent, data: data }]);
            }.bind(this));

            $(handle).on("close", function (ev) {
                this._removeHandle(handle);
                $(this).triggerHandler("agentDisconnected", [agent]);
            }.bind(this));
        },
        _removeHandle: function (handle) {
            var i = this._handles.indexOf(handle);
            if (i !== -1) {
                this._handles.splice(i, 1);
            }
        },
    };

    // so, this is clearly not how JavaScript is supposed to be used

    function makeHandleConstructor(functions) {
        var constructor = function (agent, interval) {
            this._open = functions._open;
            this._free = functions._free;
            this._refresh = functions._refresh;
            if (functions._isEmpty) this._isEmpty = functions._isEmpty;
            Handle.call(this, agent, interval, null /* query */);
        };
        constructor.prototype = Handle.prototype;
        return constructor;
    }

    function makeAggregateHandleConstructor(handleFunctions) {
        var handleConstructor = makeHandleConstructor(handleFunctions);

        var constructor = function (interval) {
            this._newHandle = function (agent) { return new handleConstructor(agent, interval) };

            AggregateHandle.call(this);
        }
        constructor.prototype = AggregateHandle.prototype;
        return constructor;
    }

    // but whatever, this part is fine

    var NodesAggregateHandle = makeAggregateHandleConstructor({
        _open: function () { return this._agent.trackNodes().done(function (handle) { this._rawHandle = handle }.bind(this)) },
        _free: function () { this._agent.untrackNodes(this._rawHandle) },
        _refresh: function () { return this._agent.nodeDelta(this._rawHandle) },
        _isEmpty: function (data) { return data.length === 0 },
    });

    var EpochsAggregateHandle = makeAggregateHandleConstructor({
        _open: function () { return this._agent.trackEpochs().done(function (handle) { this._rawHandle = handle }.bind(this)) },
        _free: function () { this._agent.untrackEpochs(this._rawHandle) },
        _refresh: function () { return this._agent.epochDelta(this._rawHandle) },
    });

    var ExceptionsAggregateHandle = makeAggregateHandleConstructor({
        _open: function () { return this._agent.trackExceptions().done(function (handle) { this._rawHandle = handle }.bind(this)) },
        _free: function () { this._agent.untrackExceptions(this._rawHandle) },
        _refresh: function () { return this._agent.exceptionDelta(this._rawHandle) },
    });

    /**
     * returns an object on which you can listen for 'data' events.
     * historical data will be sent with the first 'data' event.
     * when 'agentDisconnected' event is emitted, clear all data you've received
     *   from that agent.
     * call close() when you are done.
     */

    function trackNodes(updateInterval) {
        updateInterval || (updateInterval = 1000);
        return new NodesAggregateHandle(updateInterval);
    }

    function trackEpochs(updateInterval) {
        updateInterval || (updateInterval = 1000);
        return new EpochsAggregateHandle(updateInterval);
    }

    function trackExceptions(updateInterval) {
        updateInterval || (updateInterval = 1000);
        return new ExceptionsAggregateHandle(updateInterval);
    }

    exports.trackEpochs = trackEpochs;
    exports.trackNodes = trackNodes;
    exports.trackExceptions = trackExceptions;
});
<commit_msg>simplified code by relying on the handle being passed through to the parent class via the promise<commit_after>/*
 * Copyright (c) 2012 Massachusetts Institute of Technology, Adobe Systems
 * Incorporated, and other contributors. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define */

define(function (require, exports, module) {
    var AgentManager = require("AgentManager");

    /**
     * emits 'data' and 'close'.
     * 'abstract' parent class, expecting subclasses to provide
     *   _open: return a promise for the raw handle corresponding to the given query
     *   _free: release the handle
     *   _refresh: return a promise for the latest data
     */
    function Handle(agent, interval, query) {
        this._agent = agent;
        this._interval = interval;
        $(this._agent).on("disconnect", this.close.bind(this));
        this._open(query).done(function (rawHandle) {
            this._rawHandle = rawHandle;
            if (this._closed) {
                this.free();
            } else {
                this._refreshPeriodically();
            }
        }.bind(this)).fail(this.close.bind(this));
    }
    Handle.prototype = {
        free: function () {
            if ("_rawHandle" in this) {
                if (this._agent.isReady()) {
                    this._free(this._rawHandle);
                }
                delete this._rawHandle;
            }
        },
        close: function () {
            this.free();
            if (!this._closed) {
                this._closed = true;
                $(this).triggerHandler("close");
            }
        },
        _refreshPeriodically: function () {
            if (!this._closed) {
                this._refresh().done(function (data) {
                    if (!this._isEmpty(data)) {
                        $(this).triggerHandler("data", [data]);
                    }
                }.bind(this)).fail(function () {
                    console.log('[theseus] refresh failed');
                }.bind(this)).always(function () {
                    setTimeout(this._refreshPeriodically.bind(this), this._interval);
                }.bind(this));
            }
        },
        /** if returns false, the 'data' event won't be emitted */
        _isEmpty: function (data) {
            return false;
        },
    };

    /**
     * when a new agent appears, automatically creates a handle for it.
     * emits all its handles' "data" events for your convenience.
     * emits "agentDisconnected" so that you know to clear the data you've
     *   received from that agent.
     */
    function AggregateHandle(query) {
        this._query = query;
        this._handles = [];
        AgentManager.agents().forEach(this._agentConnected.bind(this));
        $(AgentManager).on("agentConnected", function (ev, agent) {
            this._agentConnected(agent)
        }.bind(this));
    }
    AggregateHandle.prototype = {
        close: function () {
            this._closed = true;
            this._handles.forEach(function (handle) { handle.close() });
            this._handles = [];
        },
        _agentConnected: function (agent) {
            if (this._closed) {
                return;
            }

            var handle = this._newHandle(agent);
            this._handles.push(handle);

            $(handle).on("data", function (ev, data) {
                $(this).triggerHandler("data", [{ agent: agent, data: data }]);
            }.bind(this));

            $(handle).on("close", function (ev) {
                this._removeHandle(handle);
                $(this).triggerHandler("agentDisconnected", [agent]);
            }.bind(this));
        },
        _removeHandle: function (handle) {
            var i = this._handles.indexOf(handle);
            if (i !== -1) {
                this._handles.splice(i, 1);
            }
        },
    };

    // so, this is clearly not how JavaScript is supposed to be used

    function makeHandleConstructor(functions) {
        var constructor = function (agent, interval) {
            this._open = functions._open;
            this._free = functions._free;
            this._refresh = functions._refresh;
            if (functions._isEmpty) this._isEmpty = functions._isEmpty;
            Handle.call(this, agent, interval, null /* query */);
        };
        constructor.prototype = Handle.prototype;
        return constructor;
    }

    function makeAggregateHandleConstructor(handleFunctions) {
        var handleConstructor = makeHandleConstructor(handleFunctions);

        var constructor = function (interval) {
            this._newHandle = function (agent) { return new handleConstructor(agent, interval) };

            AggregateHandle.call(this);
        }
        constructor.prototype = AggregateHandle.prototype;
        return constructor;
    }

    // but whatever, this part is fine

    var NodesAggregateHandle = makeAggregateHandleConstructor({
        _open: function () { return this._agent.trackNodes() },
        _free: function () { this._agent.untrackNodes(this._rawHandle) },
        _refresh: function () { return this._agent.nodeDelta(this._rawHandle) },
        _isEmpty: function (data) { return data.length === 0 },
    });

    var EpochsAggregateHandle = makeAggregateHandleConstructor({
        _open: function () { return this._agent.trackEpochs() },
        _free: function () { this._agent.untrackEpochs(this._rawHandle) },
        _refresh: function () { return this._agent.epochDelta(this._rawHandle) },
    });

    var ExceptionsAggregateHandle = makeAggregateHandleConstructor({
        _open: function () { return this._agent.trackExceptions() },
        _free: function () { this._agent.untrackExceptions(this._rawHandle) },
        _refresh: function () { return this._agent.exceptionDelta(this._rawHandle) },
    });

    /**
     * returns an object on which you can listen for 'data' events.
     * historical data will be sent with the first 'data' event.
     * when 'agentDisconnected' event is emitted, clear all data you've received
     *   from that agent.
     * call close() when you are done.
     */

    function trackNodes(updateInterval) {
        updateInterval || (updateInterval = 1000);
        return new NodesAggregateHandle(updateInterval);
    }

    function trackEpochs(updateInterval) {
        updateInterval || (updateInterval = 1000);
        return new EpochsAggregateHandle(updateInterval);
    }

    function trackExceptions(updateInterval) {
        updateInterval || (updateInterval = 1000);
        return new ExceptionsAggregateHandle(updateInterval);
    }

    exports.trackEpochs = trackEpochs;
    exports.trackNodes = trackNodes;
    exports.trackExceptions = trackExceptions;
});
<|endoftext|>


<commit_before>var paused = 0;

angular.module("gameApp", [])
    //called by ng-controller in receiver.html
    //creats instance of cast receiver
    .controller("appController", ["$scope", "keyPressHandlerService", function ($scope, keyPressHandlerService) {
        window.onload = function () {
            cast.receiver.logger.setLevelValue(0);
            window.castReceiverManager = cast.receiver.CastReceiverManager.getInstance();
            console.log('Starting Receiver Manager');

            // handler for the 'ready' event
            castReceiverManager.onReady = function (event) {
                console.log('Received Ready event: ' + JSON.stringify(event.data));
                window.castReceiverManager.setApplicationState('Application status is ready...');
            };

            // handler for 'senderconnected' event
            castReceiverManager.onSenderConnected = function (event) {
                console.log('Received Sender Connected event: ' + event.data);
                console.log(window.castReceiverManager.getSender(event.data).userAgent);
            };

            // handler for 'senderdisconnected' event
            castReceiverManager.onSenderDisconnected = function (event) {
                console.log('Received Sender Disconnected event: ' + event.data);
                if (window.castReceiverManager.getSenders().length == 0) {
                    window.close();
                }
            };

            // handler for 'systemvolumechanged' event
            castReceiverManager.onSystemVolumeChanged = function (event) {
                console.log('Received System Volume Changed event: ' + event.data['level'] + ' ' +
                    event.data['muted']);
            };

            // create a CastMessageBus to handle messages for a custom namespace
            window.messageBus =
                window.castReceiverManager.getCastMessageBus(
                    'urn:x-cast:com.google.cast.sample.helloworld');

            // handler for the CastMessageBus message event
            //called when receiver created above gets data
            window.messageBus.onMessage = function (event) {
                //print received message for debugging
                console.log('Message [' + event.senderId + ']: ' + event.data);
                // display the message from the sender
                displayText(event.data);

                //if pause message received, toggle paused flag
                if (event.data == 80) {
                    //if not paused, raise flag and display "play"
                    if (paused == 1) {
                        paused = 0;
                        console.log("play!")
                    }
                    //if paused, reset flag and display "pause"
                    else {
                        console.log("pause!");
                        paused = 1;
                    }

                }

                //if not pause message, spend data to key press handler
                //simulate a key up AND key down to prevent continuous movement
                keyPressHandlerService.keyPress(event.data);
                keyPressHandlerService.keyRelease(event.data);

                // inform all senders on the CastMessageBus of the incoming message event
                // sender message listener will be invoked
                window.messageBus.send(event.senderId, event.data);
            }

            // initialize the CastReceiverManager with an application status message
            window.castReceiverManager.start({
                statusText: 'Application is starting'
            });
            console.log('Receiver Manager started');
        };

        // utility function to display the text message in the input field
        function displayText(text) {
            console.log(text);
            document.getElementById('message').innerText = text;
            window.castReceiverManager.setApplicationState(text);
        };

        //    function triggerKeyDown() {
        //    var e = new KeyboardEvent('keydown', {'key': 'ArrowLeft', 'code': "ArrowLeft", 'keyCode': 38,'which':38});
        //    document.dispatchEvent(e);
        //      console.log(e);
        //  };

        /*

                $scope.keydown = function(keyEvent) {
                    if (!$scope.instructionsDisplayed) {
                        $scope.instructionsDisplayed = true;
                        return;
                    }
                    keyPressHandlerService.keyPress(keyEvent.key);
                };

                $scope.keyup = function(keyEvent) {
                    keyPressHandlerService.keyRelease(keyEvent.key);
                };
        */
    }])

//initialize game canvase and start game
.directive("centipedeGame", ["$interval", "gameService", "renderService", "graphicsEngineService", function ($interval, gameService, renderService, graphicsEngineService) {
    return {
        restrict: 'A',
        template: '<canvas id="gameCanvas" width="600" height="640" style="text-align: center; position: absolute; left:50%; top: 50%; transform: translate(-50%,-50%);"></canvas>',

        link: function (scope, element) {
            var intervalPromise;
            var animation = 0;
            var canvas = element.find('canvas')[0].getContext("2d");

            graphicsEngineService.initialise(canvas, 'App/img/graphics.png');
            gameService.initialise();

            var background = new Image();
            background.src = "App/img/bg.png";

            // Make sure the image is loaded first otherwise nothing will draw.
            background.onload = function () {
                canvas.drawImage(background, 0, 0);
            }

            //loop to keep game running
            //cycle through, updating animations
            function gameLoop() {

                animation++;

                if (animation == 4) {
                    animation = 0;
                }
                //if game is not paused, update the screen
                if (paused != 1) {
                    gameService.update(animation);
                    renderService.draw(animation);
                } else {
                    graphicsEngineService.drawText(
                        1,
                        210,
                        300,
                        "Paused",
                        "yellow",
                        "32px Arial bold");
                }

            }

            intervalPromise = $interval(gameLoop, 50);

            scope.$on("$destroy", function () {
                if (intervalPromise) {
                    $interval.cancel(intervalPromise);
                    intervalPromise = undefined;
                }
            });
        }
    }
    }]);<commit_msg>add bg<commit_after>var paused = 0;

angular.module("gameApp", [])
    //called by ng-controller in receiver.html
    //creats instance of cast receiver
    .controller("appController", ["$scope", "keyPressHandlerService", function ($scope, keyPressHandlerService) {
        window.onload = function () {
            cast.receiver.logger.setLevelValue(0);
            window.castReceiverManager = cast.receiver.CastReceiverManager.getInstance();
            console.log('Starting Receiver Manager');

            // handler for the 'ready' event
            castReceiverManager.onReady = function (event) {
                console.log('Received Ready event: ' + JSON.stringify(event.data));
                window.castReceiverManager.setApplicationState('Application status is ready...');
            };

            // handler for 'senderconnected' event
            castReceiverManager.onSenderConnected = function (event) {
                console.log('Received Sender Connected event: ' + event.data);
                console.log(window.castReceiverManager.getSender(event.data).userAgent);
            };

            // handler for 'senderdisconnected' event
            castReceiverManager.onSenderDisconnected = function (event) {
                console.log('Received Sender Disconnected event: ' + event.data);
                if (window.castReceiverManager.getSenders().length == 0) {
                    window.close();
                }
            };

            // handler for 'systemvolumechanged' event
            castReceiverManager.onSystemVolumeChanged = function (event) {
                console.log('Received System Volume Changed event: ' + event.data['level'] + ' ' +
                    event.data['muted']);
            };

            // create a CastMessageBus to handle messages for a custom namespace
            window.messageBus =
                window.castReceiverManager.getCastMessageBus(
                    'urn:x-cast:com.google.cast.sample.helloworld');

            // handler for the CastMessageBus message event
            //called when receiver created above gets data
            window.messageBus.onMessage = function (event) {
                //print received message for debugging
                console.log('Message [' + event.senderId + ']: ' + event.data);
                // display the message from the sender
                displayText(event.data);

                //if pause message received, toggle paused flag
                if (event.data == 80) {
                    //if not paused, raise flag and display "play"
                    if (paused == 1) {
                        paused = 0;
                        console.log("play!")
                    }
                    //if paused, reset flag and display "pause"
                    else {
                        console.log("pause!");
                        paused = 1;
                    }

                }

                //if not pause message, spend data to key press handler
                //simulate a key up AND key down to prevent continuous movement
                keyPressHandlerService.keyPress(event.data);
                keyPressHandlerService.keyRelease(event.data);

                // inform all senders on the CastMessageBus of the incoming message event
                // sender message listener will be invoked
                window.messageBus.send(event.senderId, event.data);
            }

            // initialize the CastReceiverManager with an application status message
            window.castReceiverManager.start({
                statusText: 'Application is starting'
            });
            console.log('Receiver Manager started');
        };

        // utility function to display the text message in the input field
        function displayText(text) {
            console.log(text);
            document.getElementById('message').innerText = text;
            window.castReceiverManager.setApplicationState(text);
        };

        //    function triggerKeyDown() {
        //    var e = new KeyboardEvent('keydown', {'key': 'ArrowLeft', 'code': "ArrowLeft", 'keyCode': 38,'which':38});
        //    document.dispatchEvent(e);
        //      console.log(e);
        //  };

        /*

                $scope.keydown = function(keyEvent) {
                    if (!$scope.instructionsDisplayed) {
                        $scope.instructionsDisplayed = true;
                        return;
                    }
                    keyPressHandlerService.keyPress(keyEvent.key);
                };

                $scope.keyup = function(keyEvent) {
                    keyPressHandlerService.keyRelease(keyEvent.key);
                };
        */
    }])

//initialize game canvase and start game
.directive("centipedeGame", ["$interval", "gameService", "renderService", "graphicsEngineService", function ($interval, gameService, renderService, graphicsEngineService) {
    return {
        restrict: 'A',
        template: '<canvas id="gameCanvas" width="600" height="640" style="text-align: center; position: absolute; left:50%; top: 50%; transform: translate(-50%,-50%); bacground:url("App/img/bg.png")"></canvas>',

        link: function (scope, element) {
            var intervalPromise;
            var animation = 0;
            var canvas = element.find('canvas')[0].getContext("2d");

            graphicsEngineService.initialise(canvas, 'App/img/graphics.png');
            gameService.initialise();

            //loop to keep game running
            //cycle through, updating animations
            function gameLoop() {

                animation++;

                if (animation == 4) {
                    animation = 0;
                }
                //if game is not paused, update the screen
                if (paused != 1) {
                    gameService.update(animation);
                    renderService.draw(animation);
                } else {
                    graphicsEngineService.drawText(
                        1,
                        210,
                        300,
                        "Paused",
                        "yellow",
                        "32px Arial bold");
                }

            }

            intervalPromise = $interval(gameLoop, 50);

            scope.$on("$destroy", function () {
                if (intervalPromise) {
                    $interval.cancel(intervalPromise);
                    intervalPromise = undefined;
                }
            });
        }
    }
    }]);<|endoftext|>


<commit_before>const defaultOpts = {
  // required opts
  React: null,
  ReactDOM: null,
  rootComponent: null,
  domElementGetter: null,
  suppressComponentDidCatchWarning: false,
}

export default function singleSpaReact(userOpts) {
  if (typeof userOpts !== 'object') {
    throw new Error(`single-spa-react requires a configuration object`);
  }

  const opts = {
    ...defaultOpts,
    ...userOpts,
  };

  if (!opts.React) {
    throw new Error(`single-spa-react must be passed opts.React`);
  }

  if (!opts.ReactDOM) {
    throw new Error(`single-spa-react must be passed opts.ReactDOM`);
  }

  if (!opts.rootComponent) {
    throw new Error(`single-spa-react must be passed opts.rootComponent`);
  }

  if (!opts.domElementGetter) {
    throw new Error(`single-spa-react must be passed opts.domElementGetter function`);
  }

  return {
    bootstrap: bootstrap.bind(null, opts),
    mount: mount.bind(null, opts),
    unmount: unmount.bind(null, opts),
  };
}

function bootstrap(opts) {
  return Promise.resolve();
}

function mount(opts, props) {
  return new Promise((resolve, reject) => {
    const whenFinished = function() {
      resolve(this);
    };
    const renderedComponent = opts.ReactDOM.render(opts.React.createElement(opts.rootComponent), getRootDomEl(opts), whenFinished);
    if (!renderedComponent.componentDidCatch && !opts.suppressComponentDidCatchWarning && atLeastReact16(opts.React)) {
      console.warn(`single-spa-react: ${props.name || props.appName || props.childAppName}'s rootComponent should implement componentDidCatch to avoid accidentally unmounting the entire single-spa application.`);
    }
  })
}

function unmount(opts) {
  return Promise
    .resolve()
    .then(() => {
      opts.ReactDOM.unmountComponentAtNode(getRootDomEl(opts));
    })
}

function getRootDomEl(opts) {
  const el = opts.domElementGetter();
  if (!el) {
    throw new Error(`single-spa-react: domElementGetter function did not return a valid dom element`);
  }

  return el;
}

function atLeastReact16(React) {
  if (React && typeof React.version === 'string' && React.version.indexOf('.') >= 0) {
    const majorVersionString = React.version.slice(0, React.version.indexOf('.'));
    try {
      return Number(majorVersionString) >= 16;
    } catch(err) {
      return false;
    }
  } else {
    return false;
  }
}
<commit_msg>Passing single-spa props to root react component<commit_after>const defaultOpts = {
  // required opts
  React: null,
  ReactDOM: null,
  rootComponent: null,
  domElementGetter: null,
  suppressComponentDidCatchWarning: false,
}

export default function singleSpaReact(userOpts) {
  if (typeof userOpts !== 'object') {
    throw new Error(`single-spa-react requires a configuration object`);
  }

  const opts = {
    ...defaultOpts,
    ...userOpts,
  };

  if (!opts.React) {
    throw new Error(`single-spa-react must be passed opts.React`);
  }

  if (!opts.ReactDOM) {
    throw new Error(`single-spa-react must be passed opts.ReactDOM`);
  }

  if (!opts.rootComponent) {
    throw new Error(`single-spa-react must be passed opts.rootComponent`);
  }

  if (!opts.domElementGetter) {
    throw new Error(`single-spa-react must be passed opts.domElementGetter function`);
  }

  return {
    bootstrap: bootstrap.bind(null, opts),
    mount: mount.bind(null, opts),
    unmount: unmount.bind(null, opts),
  };
}

function bootstrap(opts) {
  return Promise.resolve();
}

function mount(opts, props) {
  return new Promise((resolve, reject) => {
    const whenFinished = function() {
      resolve(this);
    };
    const renderedComponent = opts.ReactDOM.render(opts.React.createElement(opts.rootComponent, props), getRootDomEl(opts), whenFinished);
    if (!renderedComponent.componentDidCatch && !opts.suppressComponentDidCatchWarning && atLeastReact16(opts.React)) {
      console.warn(`single-spa-react: ${props.name || props.appName || props.childAppName}'s rootComponent should implement componentDidCatch to avoid accidentally unmounting the entire single-spa application.`);
    }
  })
}

function unmount(opts) {
  return Promise
    .resolve()
    .then(() => {
      opts.ReactDOM.unmountComponentAtNode(getRootDomEl(opts));
    })
}

function getRootDomEl(opts) {
  const el = opts.domElementGetter();
  if (!el) {
    throw new Error(`single-spa-react: domElementGetter function did not return a valid dom element`);
  }

  return el;
}

function atLeastReact16(React) {
  if (React && typeof React.version === 'string' && React.version.indexOf('.') >= 0) {
    const majorVersionString = React.version.slice(0, React.version.indexOf('.'));
    try {
      return Number(majorVersionString) >= 16;
    } catch(err) {
      return false;
    }
  } else {
    return false;
  }
}
<|endoftext|>