<commit_before>/*---------------------------------------------------------
 * OpenERP diagram library
 *---------------------------------------------------------*/

openerp.web_diagram = function (instance) {
var QWeb = instance.web.qweb,
      _t = instance.web._t,
     _lt = instance.web._lt;
instance.web.views.add('diagram', 'instance.web.DiagramView');
instance.web.DiagramView = instance.web.View.extend({
    display_name: _lt('Diagram'),
    searchable: false,
    init: function(parent, dataset, view_id, options) {
        this._super(parent);
        this.set_default_options(options);
        this.view_manager = parent;
        this.dataset = dataset;
        this.model = this.dataset.model;
        this.view_id = view_id;
        this.domain = this.dataset._domain || [];
        this.context = {};
        this.ids = this.dataset.ids;
    },
    start: function() {
        return this.rpc("/web_diagram/diagram/load", {"model": this.model, "view_id": this.view_id}, this.on_loaded);
    },

    toTitleCase: function(str) {
        return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
    },

    on_loaded: function(result) {

        var self = this;
        if(this.ids && this.ids.length) {
            this.id = this.ids[self.dataset.index || 0];
        }

        this.fields_view = result.fields_view,
        this.view_id = this.fields_view.view_id,
        this.fields = this.fields_view.fields,
        this.nodes = this.fields_view.arch.children[0],
        this.connectors = this.fields_view.arch.children[1],
        this.node = this.nodes.attrs.object,
        this.connector = this.connectors.attrs.object;

        this.$element.html(QWeb.render("DiagramView", this));
        this.$element.addClass(this.fields_view.arch.attrs['class']);

        this.$element.find('div.oe_diagram_pager button[data-pager-action]').click(function() {
            var action = $(this).data('pager-action');
            self.on_pager_action(action);
        });

        this.do_update_pager();

        // New Node,Edge
        this.$element.find('#new_node.oe_diagram_button_new').click(function(){self.add_node();});

        if(this.id) {
            self.get_diagram_info();
        }

    },

    get_diagram_info: function() {
        var self = this;
        var params = {
            'id': this.id,
            'model': this.model,
            'node': this.node,
            'connector': this.connector,
            'bgcolor': this.nodes.attrs.bgcolor,
            'shape': this.nodes.attrs.shape,
            'src_node': this.connectors.attrs.source,
            'des_node': this.connectors.attrs.destination,
            'label': this.connectors.attrs.label || false,
            'visible_nodes': [],
            'invisible_nodes': [],
            'node_fields': [],
            'connectors': [],
            'connectors_fields': []
        };

        _.each(this.nodes.children, function(child) {
            if(child.attrs.invisible == '1')
                params['invisible_nodes'].push(child.attrs.name);
            else {
                params['visible_nodes'].push(child.attrs.name);
                params['node_fields'].push(self.fields[child.attrs.name]['string']|| this.toTitleCase(child.attrs.name));
            }
        });

        _.each(this.connectors.children, function(conn) {
            params['connectors_fields'].push(self.fields[conn.attrs.name]['string']|| this.toTitleCase(conn.attrs.name));
            params['connectors'].push(conn.attrs.name);
        });

        this.rpc(
            '/web_diagram/diagram/get_diagram_info',params,
            function(result) {
                self.draw_diagram(result);
            }
        );
    },

    on_diagram_loaded: function(record) {
        var id_record = record['id'];
        if(id_record) {
            this.id = id_record;
            this.get_diagram_info();
        }
    },

    // Set-up the drawing elements of the diagram
    draw_diagram: function(result) {
        var self = this;
        var res_nodes  = result['nodes'];
        var res_edges  = result['conn'];
        this.parent_field = result.parent_field;
        this.$element.find('h3.oe_diagram_title').text(result.name);

        var id_to_node = {};

        var style = {
            edge_color: "#A0A0A0",
            edge_label_color: "#555",
            edge_label_font_size: 10,
            edge_width: 2,
            edge_spacing: 100,
            edge_loop_radius: 100,

            node_label_color: "#333",
            node_label_font_size: 12,
            node_outline_color: "#333",
            node_outline_width: 1,
            node_selected_color: "#0097BE",
            node_selected_width: 2,
            node_size_x: 110,
            node_size_y: 80,
            connector_active_color: "#FFF",
            connector_radius: 4,

            close_button_radius: 8,
            close_button_color: "#333",
            close_button_x_color: "#FFF",

            gray: "#DCDCDC",
            white: "#FFF",

            viewport_margin: 50
        };

        // remove previous diagram
        var canvas = self.$element.find('div.oe_diagram_diagram')
                             .empty().get(0);

        var r  = new Raphael(canvas, '100%','100%');

        var graph  = new CuteGraph(r,style,canvas.parentNode);

        var confirm_dialog = $('#dialog').dialog({
            autoOpen: false,
            title: _t("Are you sure?") });

        _.each(res_nodes, function(node) {
            var n = new CuteNode(
                graph,
                node.x + 50,  //FIXME the +50 should be in the layout algorithm
                node.y + 50,
                CuteGraph.wordwrap(node.name, 14),
                node.shape === 'rectangle' ? 'rect' : 'circle',
                node.color === 'white' ? style.white : style.gray);

            n.id = node.id;
            id_to_node[node.id] = n;
        });

        _.each(res_edges, function(edge) {
            var e =  new CuteEdge(
                graph,
                CuteGraph.wordwrap(edge.signal, 32),
                id_to_node[edge.s_id],
                id_to_node[edge.d_id] || id_to_node[edge.s_id]  );  //WORKAROUND
            e.id = edge.id;
        });

        CuteNode.double_click_callback = function(cutenode){
            self.edit_node(cutenode.id);
        };
        var i = 0;
        CuteNode.destruction_callback = function(cutenode){
            if(!confirm(_t("Deleting this node cannot be undone.\nIt will also delete all connected transitions.\n\nAre you sure ?"))){
                return $.Deferred().reject().promise();
            }
            return new instance.web.DataSet(self,self.node).unlink([cutenode.id]);
        };
        CuteEdge.double_click_callback = function(cuteedge){
            self.edit_connector(cuteedge.id);
        };

        CuteEdge.creation_callback = function(node_start, node_end){
            return {label:_t("")};
        };
        CuteEdge.new_edge_callback = function(cuteedge){
            self.add_connector(cuteedge.get_start().id,
                               cuteedge.get_end().id,
                               cuteedge);
        };
        CuteEdge.destruction_callback = function(cuteedge){
            if(!confirm(_t("Deleting this transition cannot be undone.\n\nAre you sure ?"))){
                return $.Deferred().reject().promise();
            }
            return new instance.web.DataSet(self,self.connector).unlink([cuteedge.id]);
        };

    },

    // Creates a popup to edit the content of the node with id node_id
    edit_node: function(node_id){
        var self = this;
        var title = _t('Activity');
        var pop = new instance.web.form.FormOpenPopup(self);

        pop.show_element(
                self.node,
                node_id,
                self.context || self.dataset.context,
                {
                    title: _t("Open: ") + title
                }
            );

        pop.on_write.add(function() {
            self.dataset.read_index(_.keys(self.fields_view.fields)).pipe(self.on_diagram_loaded);
            });

        var form_fields = [self.parent_field];
        var form_controller = pop.view_form;

        form_controller.on_record_loaded.add_first(function() {
            _.each(form_fields, function(fld) {
                if (!(fld in form_controller.fields)) { return; }
                var field = form_controller.fields[fld];
                field.$input.prop('disabled', true);
                field.$drop_down.unbind();
                field.$menu_btn.unbind();
            });
        });
    },

    // Creates a popup to add a node to the diagram
    add_node: function(){
        var self = this;
        var title = _t('Activity');
        var pop = new instance.web.form.SelectCreatePopup(self);
        pop.select_element(
            self.node,
            {
                title: _t("Create:") + title,
                initial_view: 'form',
                disable_multiple_selection: true
            },
            self.dataset.domain,
            self.context || self.dataset.context
        );
        pop.on_select_elements.add_last(function(element_ids) {
            self.dataset.read_index(_.keys(self.fields_view.fields)).pipe(self.on_diagram_loaded);
        });

        var form_controller = pop.view_form;
        var form_fields = [this.parent_field];

        form_controller.on_record_loaded.add_last(function() {
            _.each(form_fields, function(fld) {
                if (!(fld in form_controller.fields)) { return; }
                var field = form_controller.fields[fld];
                field.set_value(self.id);
                field.dirty = true;
            });
        });
    },

    // Creates a popup to edit the connector of id connector_id
    edit_connector: function(connector_id){
        var self = this;
        var title = _t('Transition');
        var pop = new instance.web.form.FormOpenPopup(self);
        pop.show_element(
            self.connector,
            parseInt(connector_id,10),      //FIXME Isn't connector_id supposed to be an int ?
            self.context || self.dataset.context,
            {
                title: _t("Open: ") + title
            }
        );
        pop.on_write.add(function() {
            self.dataset.read_index(_.keys(self.fields_view.fields)).pipe(self.on_diagram_loaded);
        });
    },

    // Creates a popup to add a connector from node_source_id to node_dest_id.
    // dummy_cuteedge if not null, will be removed form the graph after the popup is closed.
    add_connector: function(node_source_id, node_dest_id, dummy_cuteedge){
        var self = this;
        var title = _t('Transition');
        var pop = new instance.web.form.SelectCreatePopup(self);

        pop.select_element(
            self.connector,
            {
                title: _t("Create:") + title,
                initial_view: 'form',
                disable_multiple_selection: true
            },
            this.dataset.domain,
            this.context || this.dataset.context
        );

        pop.on_select_elements.add_last(function(element_ids) {
            self.dataset.read_index(_.keys(self.fields_view.fields)).pipe(self.on_diagram_loaded);
        });
        // We want to destroy the dummy edge after a creation cancel. This destroys it even if we save the changes.
        // This is not a problem since the diagram is completely redrawn on saved changes.
        pop.$element.bind("dialogbeforeclose",function(){
            if(dummy_cuteedge){
                dummy_cuteedge.remove();
            }
        });

        var form_controller = pop.view_form;

        form_controller.on_record_loaded.add_last(function () {
            form_controller.fields[self.connectors.attrs.source].set_value(node_source_id);
            form_controller.fields[self.connectors.attrs.source].dirty = true;
            form_controller.fields[self.connectors.attrs.destination].set_value(node_dest_id);
            form_controller.fields[self.connectors.attrs.destination].dirty = true;
        });
    },

    on_pager_action: function(action) {
        switch (action) {
            case 'first':
                this.dataset.index = 0;
                break;
            case 'previous':
                this.dataset.previous();
                break;
            case 'next':
                this.dataset.next();
                break;
            case 'last':
                this.dataset.index = this.dataset.ids.length - 1;
                break;
        }
        var loaded = this.dataset.read_index(_.keys(this.fields_view.fields))
                .pipe(this.on_diagram_loaded);
        this.do_update_pager();
        return loaded;
    },

    do_update_pager: function(hide_index) {
        var $pager = this.$element.find('div.oe_diagram_pager');
        var index = hide_index ? '-' : this.dataset.index + 1;
        if(!this.dataset.count) {
            this.dataset.count = this.dataset.ids.length;
        }
        $pager.find('span.oe_pager_index').html(index);
        $pager.find('span.oe_pager_count').html(this.dataset.count);
    },

    do_show: function() {
        this.do_push_state({});
        return $.when(this._super(), this.on_pager_action('reload'));
    }
});
};

// vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax:
<commit_msg>[MERGE] diagram view label<commit_after>/*---------------------------------------------------------
 * OpenERP diagram library
 *---------------------------------------------------------*/

openerp.web_diagram = function (instance) {
var QWeb = instance.web.qweb,
      _t = instance.web._t,
     _lt = instance.web._lt;
instance.web.views.add('diagram', 'instance.web.DiagramView');
instance.web.DiagramView = instance.web.View.extend({
    display_name: _lt('Diagram'),
    searchable: false,
    init: function(parent, dataset, view_id, options) {
        this._super(parent);
        this.set_default_options(options);
        this.view_manager = parent;
        this.dataset = dataset;
        this.model = this.dataset.model;
        this.view_id = view_id;
        this.domain = this.dataset._domain || [];
        this.context = {};
        this.ids = this.dataset.ids;
    },
    start: function() {
        return this.rpc("/web_diagram/diagram/load", {"model": this.model, "view_id": this.view_id}, this.on_loaded);
    },

    toTitleCase: function(str) {
        return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
    },

    on_loaded: function(result) {

        var self = this;
        if(this.ids && this.ids.length) {
            this.id = this.ids[self.dataset.index || 0];
        }

        this.fields_view = result.fields_view,
        this.view_id = this.fields_view.view_id,
        this.fields = this.fields_view.fields,
        this.nodes = this.fields_view.arch.children[0],
        this.connectors = this.fields_view.arch.children[1],
        this.node = this.nodes.attrs.object,
        this.connector = this.connectors.attrs.object;
        this.labels = _.filter(this.fields_view.arch.children, function(label) {
            return label.tag == "label";
        });

        this.$element.html(QWeb.render("DiagramView", this));
        this.$element.addClass(this.fields_view.arch.attrs['class']);

        _.each(self.labels,function(label){
            html_label = '
' + label.attrs.string + "
";
            self.$element.find('.oe_diagram_header').append(html_label);
        })

        this.$element.find('div.oe_diagram_pager button[data-pager-action]').click(function() {
            var action = $(this).data('pager-action');
            self.on_pager_action(action);
        });

        this.do_update_pager();

        // New Node,Edge
        this.$element.find('#new_node.oe_diagram_button_new').click(function(){self.add_node();});

        if(this.id) {
            self.get_diagram_info();
        }

    },

    get_diagram_info: function() {
        var self = this;
        var params = {
            'id': this.id,
            'model': this.model,
            'node': this.node,
            'connector': this.connector,
            'bgcolor': this.nodes.attrs.bgcolor,
            'shape': this.nodes.attrs.shape,
            'src_node': this.connectors.attrs.source,
            'des_node': this.connectors.attrs.destination,
            'label': this.connectors.attrs.label || false,
            'visible_nodes': [],
            'invisible_nodes': [],
            'node_fields': [],
            'connectors': [],
            'connectors_fields': []
        };

        _.each(this.nodes.children, function(child) {
            if(child.attrs.invisible == '1')
                params['invisible_nodes'].push(child.attrs.name);
            else {
                params['visible_nodes'].push(child.attrs.name);
                params['node_fields'].push(self.fields[child.attrs.name]['string']|| this.toTitleCase(child.attrs.name));
            }
        });

        _.each(this.connectors.children, function(conn) {
            params['connectors_fields'].push(self.fields[conn.attrs.name]['string']|| this.toTitleCase(conn.attrs.name));
            params['connectors'].push(conn.attrs.name);
        });

        this.rpc(
            '/web_diagram/diagram/get_diagram_info',params,
            function(result) {
                self.draw_diagram(result);
            }
        );
    },

    on_diagram_loaded: function(record) {
        var id_record = record['id'];
        if(id_record) {
            this.id = id_record;
            this.get_diagram_info();
        }
    },

    // Set-up the drawing elements of the diagram
    draw_diagram: function(result) {
        var self = this;
        var res_nodes  = result['nodes'];
        var res_edges  = result['conn'];
        this.parent_field = result.parent_field;
        this.$element.find('h3.oe_diagram_title').text(result.name);

        var id_to_node = {};

        var style = {
            edge_color: "#A0A0A0",
            edge_label_color: "#555",
            edge_label_font_size: 10,
            edge_width: 2,
            edge_spacing: 100,
            edge_loop_radius: 100,

            node_label_color: "#333",
            node_label_font_size: 12,
            node_outline_color: "#333",
            node_outline_width: 1,
            node_selected_color: "#0097BE",
            node_selected_width: 2,
            node_size_x: 110,
            node_size_y: 80,
            connector_active_color: "#FFF",
            connector_radius: 4,

            close_button_radius: 8,
            close_button_color: "#333",
            close_button_x_color: "#FFF",

            gray: "#DCDCDC",
            white: "#FFF",

            viewport_margin: 50
        };

        // remove previous diagram
        var canvas = self.$element.find('div.oe_diagram_diagram')
                             .empty().get(0);

        var r  = new Raphael(canvas, '100%','100%');

        var graph  = new CuteGraph(r,style,canvas.parentNode);

        var confirm_dialog = $('#dialog').dialog({
            autoOpen: false,
            title: _t("Are you sure?") });

        _.each(res_nodes, function(node) {
            var n = new CuteNode(
                graph,
                node.x + 50,  //FIXME the +50 should be in the layout algorithm
                node.y + 50,
                CuteGraph.wordwrap(node.name, 14),
                node.shape === 'rectangle' ? 'rect' : 'circle',
                node.color === 'white' ? style.white : style.gray);

            n.id = node.id;
            id_to_node[node.id] = n;
        });

        _.each(res_edges, function(edge) {
            var e =  new CuteEdge(
                graph,
                CuteGraph.wordwrap(edge.signal, 32),
                id_to_node[edge.s_id],
                id_to_node[edge.d_id] || id_to_node[edge.s_id]  );  //WORKAROUND
            e.id = edge.id;
        });

        CuteNode.double_click_callback = function(cutenode){
            self.edit_node(cutenode.id);
        };
        var i = 0;
        CuteNode.destruction_callback = function(cutenode){
            if(!confirm(_t("Deleting this node cannot be undone.\nIt will also delete all connected transitions.\n\nAre you sure ?"))){
                return $.Deferred().reject().promise();
            }
            return new instance.web.DataSet(self,self.node).unlink([cutenode.id]);
        };
        CuteEdge.double_click_callback = function(cuteedge){
            self.edit_connector(cuteedge.id);
        };

        CuteEdge.creation_callback = function(node_start, node_end){
            return {label:_t("")};
        };
        CuteEdge.new_edge_callback = function(cuteedge){
            self.add_connector(cuteedge.get_start().id,
                               cuteedge.get_end().id,
                               cuteedge);
        };
        CuteEdge.destruction_callback = function(cuteedge){
            if(!confirm(_t("Deleting this transition cannot be undone.\n\nAre you sure ?"))){
                return $.Deferred().reject().promise();
            }
            return new instance.web.DataSet(self,self.connector).unlink([cuteedge.id]);
        };

    },

    // Creates a popup to edit the content of the node with id node_id
    edit_node: function(node_id){
        var self = this;
        var title = _t('Activity');
        var pop = new instance.web.form.FormOpenPopup(self);

        pop.show_element(
                self.node,
                node_id,
                self.context || self.dataset.context,
                {
                    title: _t("Open: ") + title
                }
            );

        pop.on_write.add(function() {
            self.dataset.read_index(_.keys(self.fields_view.fields)).pipe(self.on_diagram_loaded);
            });

        var form_fields = [self.parent_field];
        var form_controller = pop.view_form;

        form_controller.on_record_loaded.add_first(function() {
            _.each(form_fields, function(fld) {
                if (!(fld in form_controller.fields)) { return; }
                var field = form_controller.fields[fld];
                field.$input.prop('disabled', true);
                field.$drop_down.unbind();
                field.$menu_btn.unbind();
            });
        });
    },

    // Creates a popup to add a node to the diagram
    add_node: function(){
        var self = this;
        var title = _t('Activity');
        var pop = new instance.web.form.SelectCreatePopup(self);
        pop.select_element(
            self.node,
            {
                title: _t("Create:") + title,
                initial_view: 'form',
                disable_multiple_selection: true
            },
            self.dataset.domain,
            self.context || self.dataset.context
        );
        pop.on_select_elements.add_last(function(element_ids) {
            self.dataset.read_index(_.keys(self.fields_view.fields)).pipe(self.on_diagram_loaded);
        });

        var form_controller = pop.view_form;
        var form_fields = [this.parent_field];

        form_controller.on_record_loaded.add_last(function() {
            _.each(form_fields, function(fld) {
                if (!(fld in form_controller.fields)) { return; }
                var field = form_controller.fields[fld];
                field.set_value(self.id);
                field.dirty = true;
            });
        });
    },

    // Creates a popup to edit the connector of id connector_id
    edit_connector: function(connector_id){
        var self = this;
        var title = _t('Transition');
        var pop = new instance.web.form.FormOpenPopup(self);
        pop.show_element(
            self.connector,
            parseInt(connector_id,10),      //FIXME Isn't connector_id supposed to be an int ?
            self.context || self.dataset.context,
            {
                title: _t("Open: ") + title
            }
        );
        pop.on_write.add(function() {
            self.dataset.read_index(_.keys(self.fields_view.fields)).pipe(self.on_diagram_loaded);
        });
    },

    // Creates a popup to add a connector from node_source_id to node_dest_id.
    // dummy_cuteedge if not null, will be removed form the graph after the popup is closed.
    add_connector: function(node_source_id, node_dest_id, dummy_cuteedge){
        var self = this;
        var title = _t('Transition');
        var pop = new instance.web.form.SelectCreatePopup(self);

        pop.select_element(
            self.connector,
            {
                title: _t("Create:") + title,
                initial_view: 'form',
                disable_multiple_selection: true
            },
            this.dataset.domain,
            this.context || this.dataset.context
        );

        pop.on_select_elements.add_last(function(element_ids) {
            self.dataset.read_index(_.keys(self.fields_view.fields)).pipe(self.on_diagram_loaded);
        });
        // We want to destroy the dummy edge after a creation cancel. This destroys it even if we save the changes.
        // This is not a problem since the diagram is completely redrawn on saved changes.
        pop.$element.bind("dialogbeforeclose",function(){
            if(dummy_cuteedge){
                dummy_cuteedge.remove();
            }
        });

        var form_controller = pop.view_form;

        form_controller.on_record_loaded.add_last(function () {
            form_controller.fields[self.connectors.attrs.source].set_value(node_source_id);
            form_controller.fields[self.connectors.attrs.source].dirty = true;
            form_controller.fields[self.connectors.attrs.destination].set_value(node_dest_id);
            form_controller.fields[self.connectors.attrs.destination].dirty = true;
        });
    },

    on_pager_action: function(action) {
        switch (action) {
            case 'first':
                this.dataset.index = 0;
                break;
            case 'previous':
                this.dataset.previous();
                break;
            case 'next':
                this.dataset.next();
                break;
            case 'last':
                this.dataset.index = this.dataset.ids.length - 1;
                break;
        }
        var loaded = this.dataset.read_index(_.keys(this.fields_view.fields))
                .pipe(this.on_diagram_loaded);
        this.do_update_pager();
        return loaded;
    },

    do_update_pager: function(hide_index) {
        var $pager = this.$element.find('div.oe_diagram_pager');
        var index = hide_index ? '-' : this.dataset.index + 1;
        if(!this.dataset.count) {
            this.dataset.count = this.dataset.ids.length;
        }
        $pager.find('span.oe_pager_index').html(index);
        $pager.find('span.oe_pager_count').html(this.dataset.count);
    },

    do_show: function() {
        this.do_push_state({});
        return $.when(this._super(), this.on_pager_action('reload'));
    }
});
};

// vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax:
<|endoftext|>


<commit_before>define(['app',
	'/app/views/directives/login.directive.html.js',
	'/app/views/register/register-record-list.directive.js',
	//'../js/directives/forms/form-controls.js',
	//'./tasks/my-completed-tasks.directive.js',
	//'./tasks/my-pending-tasks.directive.js',
	//'./tasks/my-tasks.directive.js',
	'/app/views/forms/edit/km-form-buttons.js',
	'/app/views/forms/edit/editFormUtility.js',
	'/app/views/forms/edit/field-embed-contact.directive.js',
	'/app/views/forms/edit/edit-contact-base.directive.js',
	'/app/views/forms/view/view-contact-reference.directive.js',
	'/app/views/forms/view/view-organization-reference.directive.js',
	'/app/views/forms/view/record-loader.directive.html.js',
	'/app/views/forms/view/view-organization.directive.js',
	'/app/views/forms/view/view-organization-reference.directive.js',
	'/app/views/directives/task-id-directive.html.js',
	'/app/views/directives/user-details.directive.html.js',
	'/app/views/directives/ngxLazy.directive.js'], function (app) {

  "use strict";

  app.controller("TypeDocumentListController",
    ["$rootScope", "$scope", "$q", "$window", "IStorage", "underscore",
     "schemaTypes", "$compile", "$timeout","lstringFilter", "$routeParams","$filter",'$location',
    function ($rootScope, $scope, $q, $window, storage, _,
      schemaTypes,$compile,$timeout,lstringFilter, $routeParams, $filter, $location) {

    $scope.type = $rootScope.document_types[$filter("mapSchema")($routeParams.document_type)];

	$scope.path = $location.path();

    //intro.js configurations
	$scope.startTour=false;

        if($routeParams.tour)
        {
            $scope.startTour=true;
            $location.search("tour", null);
        }
    $scope.introOptions = {
      steps: [
        {
          element: '#filter_buttons',
          intro: 'Use these buttons to filter by the status of the document, and you may type in a keyword to quickly narrow down the list',
        },
        {
          element: '#new_button',
          intro: 'Create a new ' + $routeParams.document_type + ' document by clicking here.',
        },
        {
          element: '.document_buttons',
          intro: 'duplicate, edit, and delete documents using these buttons.',
          position: 'left',
        },
      ],
    };

    $scope.dashboardFilter = "All";

    $scope.setDashFilter = function(filter){
        $scope.dashboardFilter = filter;
    }
    $scope.isFilter = function(filter){
        return	$scope.dashboardFilter == filter || $scope.dashboardFilter == "All";
    }

  }]);
});
<commit_msg>remove intro tour code<commit_after>define(['app',
	'/app/views/directives/login.directive.html.js',
	'/app/views/register/register-record-list.directive.js',
	//'../js/directives/forms/form-controls.js',
	//'./tasks/my-completed-tasks.directive.js',
	//'./tasks/my-pending-tasks.directive.js',
	//'./tasks/my-tasks.directive.js',
	'/app/views/forms/edit/km-form-buttons.js',
	'/app/views/forms/edit/editFormUtility.js',
	'/app/views/forms/edit/field-embed-contact.directive.js',
	'/app/views/forms/edit/edit-contact-base.directive.js',
	'/app/views/forms/view/view-contact-reference.directive.js',
	'/app/views/forms/view/view-organization-reference.directive.js',
	'/app/views/forms/view/record-loader.directive.html.js',
	'/app/views/forms/view/view-organization.directive.js',
	'/app/views/forms/view/view-organization-reference.directive.js',
	'/app/views/directives/task-id-directive.html.js',
	'/app/views/directives/user-details.directive.html.js',
	'/app/views/directives/ngxLazy.directive.js'], function (app) {

  "use strict";

  app.controller("TypeDocumentListController",
    ["$rootScope", "$scope", "$q", "$window", "IStorage", "underscore",
     "schemaTypes", "$compile", "$timeout","lstringFilter", "$routeParams","$filter",'$location',
    function ($rootScope, $scope, $q, $window, storage, _,
      schemaTypes,$compile,$timeout,lstringFilter, $routeParams, $filter, $location) {

    $scope.type = $rootScope.document_types[$filter("mapSchema")($routeParams.document_type)];

	$scope.path = $location.path();

    $scope.dashboardFilter = "All";

    $scope.setDashFilter = function(filter){
        $scope.dashboardFilter = filter;
    }
    $scope.isFilter = function(filter){
        return	$scope.dashboardFilter == filter || $scope.dashboardFilter == "All";
    }

  }]);
});
<|endoftext|>


<commit_before>var backButtonHandler = null;

var stack = [];

function backButtonClick (e) {
	if(typeof(backButtonHandler) === "function")
		backButtonHandler(e);
}

exports.onBackButtonClick = function(handler) {
	backButtonHandler = handler;
};

exports.openPage = function (title, view) {
	var hidingView = stack[stack.length - 1];

	var openingViewMatrix = Ti.UI.create2DMatrix();
	openingViewMatrix = openingViewMatrix.translate(-400, 0);

	var hidingViewMatrix = Ti.UI.create2DMatrix();
	hidingViewMatrix = hidingViewMatrix.scale(0.5, 0.5);

	var openAnimation = Ti.UI.createAnimation({
		transform: openingViewMatrix,
		duration: 300
	});
	openAnimation.addEventListener("complete", function() {
		stack.push(view);
		$.currentWindowTitle.text = title;
		$.icon.visible = true;
	});
	// openAnimation.addEventListener("start", function(){
	// });

	var hideAnimation = Ti.UI.createAnimation({
		transform: hidingViewMatrix,
		duration: 300
	});
	hideAnimation.addEventListener("complete", function() {
		hidingView.visible = false;
	});

	$.content.add(view);
	view.setLeft(200);
	view.setRight(-200);
	hidingView.animate(hideAnimation);
	view.animate(openAnimation);
};

exports.setFirstPage = function(title, view) {
	title = title || "";
	$.icon.visible = false;
	$.currentWindowTitle.text = title;
	stack.push(view);
	$.content.add(view);
};
<commit_msg>front leaving-through complete<commit_after>var backButtonHandler = function(e) {
	var hidingView = stack[stack.length - 1];
	var openingView = stack[stack.length - 2];

	var openingViewMatrix = Ti.UI.create2DMatrix();
	openingViewMatrix = openingViewMatrix.scale(1, 1);

	var hidingViewMatrix = Ti.UI.create2DMatrix();
	hidingViewMatrix = hidingViewMatrix.translate(400, 0);

	var openAnimation = Ti.UI.createAnimation({
		transform: openingViewMatrix,
		duration: 300
	});

	openAnimation.addEventListener("complete", function() {
		titles.pop();
		$.currentWindowTitle.text = titles[titles.length - 1];
	});

	var hideAnimation = Ti.UI.createAnimation({
		transform: hidingViewMatrix,
		duration: 300
	});

	hideAnimation.addEventListener("complete", function() {
		stack.pop();
		$.content.remove(hidingView);
		if(stack.length < 2)
			$.icon.visible = false;
	});

	openingView.show();
	openingView.animate(openAnimation);
	hidingView.animate(hideAnimation);
};

var stack = [];
var titles = [];

function backButtonClick (e) {
	if(typeof(backButtonHandler) === "function")
		backButtonHandler(e);
}

exports.onBackButtonClick = function(handler) {
	backButtonHandler = handler;
};

exports.openPage = function (title, view) {
	var hidingView = stack[stack.length - 1];

	var openingViewMatrix = Ti.UI.create2DMatrix();
	openingViewMatrix = openingViewMatrix.translate(-400, 0);

	var hidingViewMatrix = Ti.UI.create2DMatrix();
	hidingViewMatrix = hidingViewMatrix.scale(0.5, 0.5);

	var openAnimation = Ti.UI.createAnimation({
		transform: openingViewMatrix,
		duration: 300
	});
	openAnimation.addEventListener("complete", function() {
		stack.push(view);
		titles.push(title);
		view.setLeft(leftPos);
		view.setRight(rightPos);
		$.currentWindowTitle.text = title;
		$.icon.visible = true;
	});
	// openAnimation.addEventListener("start", function(){
	// });

	var hideAnimation = Ti.UI.createAnimation({
		transform: hidingViewMatrix,
		duration: 300
	});
	hideAnimation.addEventListener("complete", function() {
		hidingView.visible = false;
	});

	$.content.add(view);

	var leftPos = view.getLeft();
	var rightPos = view.getRight();

	view.setLeft(200);
	view.setRight(-200);
	hidingView.animate(hideAnimation);
	view.animate(openAnimation);
};

exports.setFirstPage = function(title, view) {
	title = title || "";
	$.icon.visible = false;
	$.currentWindowTitle.text = title;
	stack.push(view);
	titles.push(title);
	$.content.add(view);
};
<|endoftext|>


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

/**
 * External dependencies
 */
import { useMount } from 'react-use';
import { Slide } from '@material-ui/core';

/**
 * WordPress dependencies
 */
import { useCallback, useEffect, useState } from '@wordpress/element';
import { __ } from '@wordpress/i18n';

/**
 * Internal dependencies
 */
import Data from 'googlesitekit-data';
import { CORE_FORMS } from '../../googlesitekit/datastore/forms/constants';
import { CORE_USER } from '../../googlesitekit/datastore/user/constants';
import SurveyCompletion from './SurveyCompletion';
import SurveyQuestionRating from './SurveyQuestionRating';
import SurveyQuestionOpenText from './SurveyQuestionOpenText';
import SurveyQuestionMultiSelect from './SurveyQuestionMultiSelect';
import SurveyQuestionSingleSelect from './SurveyQuestionSingleSelect';
import SurveyTerms from './SurveyTerms';
const { useDispatch, useSelect } = Data;

const SURVEY_ANSWER_DELAY_MS = 300;

const TYPE_MULTI_SELECT = 'multi_select';
const TYPE_OPEN_TEXT = 'open_text';
const TYPE_RATING = 'rating';
const TYPE_SINGLE_SELECT = 'single_select';

const KNOWN_QUESTION_TYPES = [
	TYPE_MULTI_SELECT,
	TYPE_OPEN_TEXT,
	TYPE_RATING,
	TYPE_SINGLE_SELECT,
];

export default function CurrentSurvey() {
	const [ sentSurveyShownEvent, setSentSurveyShownEvent ] = useState( false );
	const [ sentCompletionEvent, setSentCompletionEvent ] = useState( false );
	const [ animateSurvey, setAnimateSurvey ] = useState( false );
	const [ hasAnsweredQuestion, setHasAnsweredQuestion ] = useState( false );

	const {
		completions,
		questions,
		surveySession,
		isTrackingEnabled,
	} = useSelect( ( select ) => ( {
		completions: select( CORE_USER ).getCurrentSurveyCompletions(),
		questions: select( CORE_USER ).getCurrentSurveyQuestions(),
		surveySession: select( CORE_USER ).getCurrentSurveySession(),
		isTrackingEnabled: select( CORE_USER ).isTrackingEnabled(),
	} ) );

	const formName = surveySession
		? `survey-${ surveySession.session_id }`
		: null;

	const { shouldHide, answers } = useSelect( ( select ) => ( {
		shouldHide: select( CORE_FORMS ).getValue( formName, 'hideSurvey' ),
		answers: select( CORE_FORMS ).getValue( formName, 'answers' ),
	} ) );

	const { setValues } = useDispatch( CORE_FORMS );
	const { sendSurveyEvent } = useDispatch( CORE_USER );

	useEffect( () => {
		if ( questions?.length && ! sentSurveyShownEvent ) {
			setSentSurveyShownEvent( true );
			sendSurveyEvent( 'survey_shown' );
		}
	}, [ questions, sentSurveyShownEvent, sendSurveyEvent ] );

	const currentQuestionOrdinal =
		Math.max( 0, ...( answers || [] ).map( ( a ) => a.question_ordinal ) ) +
		1;

	const currentQuestion = questions?.find(
		( { question_ordinal: questionOrdinal } ) =>
			questionOrdinal === currentQuestionOrdinal
	);

	const answerQuestion = useCallback(
		( answer ) => {
			if ( hasAnsweredQuestion ) {
				return;
			}

			setHasAnsweredQuestion( true );
			sendSurveyEvent( 'question_answered', {
				// eslint-disable-next-line camelcase
				question_ordinal: currentQuestion?.question_ordinal,
				answer,
			} );

			setTimeout( () => {
				setValues( formName, {
					answers: [
						...( answers || [] ),
						{
							// eslint-disable-next-line camelcase
							question_ordinal: currentQuestion?.question_ordinal,
							answer,
						},
					],
				} );

				setHasAnsweredQuestion( false );
			}, SURVEY_ANSWER_DELAY_MS );
		},
		[
			answers,
			currentQuestion,
			formName,
			sendSurveyEvent,
			setValues,
			hasAnsweredQuestion,
		]
	);

	// We only have trigger conditions for questions that are answered with
	// ordinal values right now.
	const ordinalAnswerMap = answers?.length
		? answers.reduce( ( acc, answer ) => {
				return {
					...acc,
					[ answer.question_ordinal ]:
						answer.answer.answer.answer_ordinal,
				};
		  }, {} )
		: [];

	// Check to see if a completion trigger has been met.
	let triggeredCompletion;
	if ( questions?.length && currentQuestionOrdinal > questions?.length ) {
		// Use Array.some to avoid looping through all completions; once the first
		// matching completion has been found, treat the survey as complete.
		completions?.some( ( completion ) => {
			completion.trigger_condition.some( ( condition ) => {
				// If a question was answered with the appropriate value, a completion
				// trigger has been fulfilled and we should treat this survey as
				// complete.
				if (
					condition.answer_ordinal.includes(
						ordinalAnswerMap[ condition.question_ordinal ]
					)
				) {
					// eslint-disable-line camelcase
					triggeredCompletion = completion;
					return true;
				}

				return false;
			} );

			if ( triggeredCompletion ) {
				return true;
			}

			return false;
		} );

		// If no specific trigger has been found but all questions are answered, use
		// the first available trigger.
		if ( ! triggeredCompletion ) {
			triggeredCompletion = completions[ 0 ];
		}
	}

	const ctaOnClick = useCallback( () => {
		sendSurveyEvent( 'follow_up_link_clicked', {
			completion_ordinal: triggeredCompletion?.completion_ordinal, // eslint-disable-line camelcase
		} );
		sendSurveyEvent( 'survey_closed' );
		setValues( formName, { hideSurvey: true } );
	}, [ formName, sendSurveyEvent, setValues, triggeredCompletion ] );

	const dismissSurvey = useCallback( () => {
		sendSurveyEvent( 'survey_closed' );
		setAnimateSurvey( false );
	}, [ sendSurveyEvent ] );

	const handleAnimationOnExited = useCallback( () => {
		setValues( formName, { hideSurvey: true } );
	}, [ formName, setValues ] );

	useEffect( () => {
		if ( triggeredCompletion && ! sentCompletionEvent ) {
			setSentCompletionEvent( true );
			sendSurveyEvent( 'completion_shown', {
				completion_ordinal: triggeredCompletion?.completion_ordinal, // eslint-disable-line camelcase
			} );
		}
	}, [ sentCompletionEvent, sendSurveyEvent, triggeredCompletion ] );

	useMount( () => {
		setAnimateSurvey( true );
	} );

	if (
		shouldHide ||
		! questions ||
		! completions ||
		isTrackingEnabled === undefined
	) {
		return null;
	}

	if ( triggeredCompletion ) {
		return (
			<Slide
				direction="up"
				in={ animateSurvey }
				onExited={ handleAnimationOnExited }
			>

					<SurveyCompletion
						dismissSurvey={ dismissSurvey }
						ctaOnClick={ ctaOnClick }
						ctaText={ triggeredCompletion.follow_up_text }
						ctaURL={ triggeredCompletion.follow_up_url }
						title={ triggeredCompletion.completion_title }
					>
						{ triggeredCompletion.completion_text }
					</SurveyCompletion>

			</Slide>
		);
	}

	// eslint-disable-next-line camelcase
	if ( ! KNOWN_QUESTION_TYPES.includes( currentQuestion?.question_type ) ) {
		return null;
	}

	const commonProps = {
		key: currentQuestion.question_text,
		answerQuestion,
		dismissSurvey,
		question: currentQuestion.question_text,
		submitButtonText:
			questions?.length === currentQuestionOrdinal
				? __( 'Submit', 'google-site-kit' )
				: __( 'Next', 'google-site-kit' ),
	};

	return (
		<Slide
			direction="up"
			in={ animateSurvey }
			onExited={ handleAnimationOnExited }
		>

				{ currentQuestion.question_type === TYPE_MULTI_SELECT && (
					<SurveyQuestionMultiSelect
						{ ...commonProps }
						choices={ currentQuestion.question.answer_choice }
						minChoices={ currentQuestion.question.min_choices }
						maxChoices={ currentQuestion.question.max_choices }
					/>
				) }
				{ currentQuestion.question_type === TYPE_OPEN_TEXT && (
					<SurveyQuestionOpenText
						{ ...commonProps }
						subtitle={ currentQuestion.question.subtitle }
						placeholder={ currentQuestion.question.placeholder }
					/>
				) }
				{ currentQuestion.question_type === TYPE_RATING && (
					<SurveyQuestionRating
						{ ...commonProps }
						choices={ currentQuestion.question.answer_choice }
					/>
				) }
				{ currentQuestion.question_type === TYPE_SINGLE_SELECT && (
					<SurveyQuestionSingleSelect
						{ ...commonProps }
						choices={ currentQuestion.question.answer_choice }
					/>
				) }

				{ isTrackingEnabled === false &&
					currentQuestion?.question_ordinal === 1 && ( // eslint-disable-line camelcase

							<SurveyTerms />

					) }

		</Slide>
	);
}
<commit_msg>Update the CurrentSurvey component to work correctly with conditional surveys.<commit_after>/**
 * CurrentSurvey component.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * External dependencies
 */
import { useMount } from 'react-use';
import { Slide } from '@material-ui/core';

/**
 * WordPress dependencies
 */
import { useCallback, useEffect, useState } from '@wordpress/element';
import { __ } from '@wordpress/i18n';

/**
 * Internal dependencies
 */
import Data from 'googlesitekit-data';
import { CORE_FORMS } from '../../googlesitekit/datastore/forms/constants';
import { CORE_USER } from '../../googlesitekit/datastore/user/constants';
import SurveyCompletion from './SurveyCompletion';
import SurveyQuestionRating from './SurveyQuestionRating';
import SurveyQuestionOpenText from './SurveyQuestionOpenText';
import SurveyQuestionMultiSelect from './SurveyQuestionMultiSelect';
import SurveyQuestionSingleSelect from './SurveyQuestionSingleSelect';
import SurveyTerms from './SurveyTerms';
const { useDispatch, useSelect } = Data;

const SURVEY_ANSWER_DELAY_MS = 300;

const TYPE_MULTI_SELECT = 'multi_select';
const TYPE_OPEN_TEXT = 'open_text';
const TYPE_RATING = 'rating';
const TYPE_SINGLE_SELECT = 'single_select';

const KNOWN_QUESTION_TYPES = [
	TYPE_MULTI_SELECT,
	TYPE_OPEN_TEXT,
	TYPE_RATING,
	TYPE_SINGLE_SELECT,
];

export default function CurrentSurvey() {
	const [ sentSurveyShownEvent, setSentSurveyShownEvent ] = useState( false );
	const [ sentCompletionEvent, setSentCompletionEvent ] = useState( false );
	const [ animateSurvey, setAnimateSurvey ] = useState( false );
	const [ hasAnsweredQuestion, setHasAnsweredQuestion ] = useState( false );

	const {
		completions,
		questions,
		surveySession,
		isTrackingEnabled,
	} = useSelect( ( select ) => ( {
		completions: select( CORE_USER ).getCurrentSurveyCompletions(),
		questions: select( CORE_USER ).getCurrentSurveyQuestions(),
		surveySession: select( CORE_USER ).getCurrentSurveySession(),
		isTrackingEnabled: select( CORE_USER ).isTrackingEnabled(),
	} ) );

	const formName = surveySession
		? `survey-${ surveySession.session_id }`
		: null;

	const { shouldHide, answers = [] } = useSelect( ( select ) => ( {
		shouldHide: select( CORE_FORMS ).getValue( formName, 'hideSurvey' ),
		answers: select( CORE_FORMS ).getValue( formName, 'answers' ),
	} ) );

	const { setValues } = useDispatch( CORE_FORMS );
	const { sendSurveyEvent } = useDispatch( CORE_USER );

	useEffect( () => {
		if ( questions?.length && ! sentSurveyShownEvent ) {
			setSentSurveyShownEvent( true );
			sendSurveyEvent( 'survey_shown' );
		}
	}, [ questions, sentSurveyShownEvent, sendSurveyEvent ] );

	// We only have trigger conditions for questions that are answered with
	// ordinal values right now.
	const ordinalAnswerMap = answers.reduce( ( acc, answer ) => {
		return {
			...acc,
			[ answer.question_ordinal ]: answer.answer.answer.answer_ordinal,
		};
	}, {} );

	let currentQuestionOrdinal =
		Math.max( 0, ...answers.map( ( a ) => a.question_ordinal ) ) + 1;

	const currentQuestion = questions?.find( ( question ) => {
		const {
			question_ordinal: questionOrdinal,
			trigger_condition: conditions,
		} = question;

		if ( Array.isArray( conditions ) && conditions.length > 0 ) {
			for ( const condition of conditions ) {
				const answer = ordinalAnswerMap[ condition.question_ordinal ];
				const allowedAnswers = condition.answer_ordinal || [];
				if ( answer && ! allowedAnswers.includes( answer ) ) {
					currentQuestionOrdinal++;
					return false;
				}
			}
		}

		return questionOrdinal === currentQuestionOrdinal;
	} );

	const answerQuestion = useCallback(
		( answer ) => {
			if ( hasAnsweredQuestion ) {
				return;
			}

			setHasAnsweredQuestion( true );
			sendSurveyEvent( 'question_answered', {
				// eslint-disable-next-line camelcase
				question_ordinal: currentQuestion?.question_ordinal,
				answer,
			} );

			setTimeout( () => {
				setValues( formName, {
					answers: [
						...answers,
						{
							// eslint-disable-next-line camelcase
							question_ordinal: currentQuestion?.question_ordinal,
							answer,
						},
					],
				} );

				setHasAnsweredQuestion( false );
			}, SURVEY_ANSWER_DELAY_MS );
		},
		[
			answers,
			currentQuestion,
			formName,
			sendSurveyEvent,
			setValues,
			hasAnsweredQuestion,
		]
	);

	// Check to see if a completion trigger has been met.
	let triggeredCompletion;
	if ( questions?.length && currentQuestionOrdinal > questions.length ) {
		triggeredCompletion = ( completions || [] ).find( ( completion ) => {
			const conditions = completion.trigger_condition || [];

			for ( const condition of conditions ) {
				// If a question was answered with the appropriate value, a completion
				// trigger has been fulfilled and we should treat this survey as
				// complete.
				if (
					condition.answer_ordinal.includes(
						ordinalAnswerMap[ condition.question_ordinal ]
					)
				) {
					// eslint-disable-line camelcase
					triggeredCompletion = completion;
					return true;
				}
			}

			return false;
		} );

		// If no specific trigger has been found but all questions are answered, use
		// the first available trigger.
		if ( ! triggeredCompletion ) {
			triggeredCompletion = completions[ 0 ];
		}
	}

	const ctaOnClick = useCallback( () => {
		sendSurveyEvent( 'follow_up_link_clicked', {
			completion_ordinal: triggeredCompletion?.completion_ordinal, // eslint-disable-line camelcase
		} );
		sendSurveyEvent( 'survey_closed' );
		setValues( formName, { hideSurvey: true } );
	}, [ formName, sendSurveyEvent, setValues, triggeredCompletion ] );

	const dismissSurvey = useCallback( () => {
		sendSurveyEvent( 'survey_closed' );
		setAnimateSurvey( false );
	}, [ sendSurveyEvent ] );

	const handleAnimationOnExited = useCallback( () => {
		setValues( formName, { hideSurvey: true } );
	}, [ formName, setValues ] );

	useEffect( () => {
		if ( triggeredCompletion && ! sentCompletionEvent ) {
			setSentCompletionEvent( true );
			sendSurveyEvent( 'completion_shown', {
				completion_ordinal: triggeredCompletion?.completion_ordinal, // eslint-disable-line camelcase
			} );
		}
	}, [ sentCompletionEvent, sendSurveyEvent, triggeredCompletion ] );

	useMount( () => {
		setAnimateSurvey( true );
	} );

	if (
		shouldHide ||
		! questions ||
		! completions ||
		isTrackingEnabled === undefined
	) {
		return null;
	}

	if ( triggeredCompletion ) {
		return (
			<Slide
				direction="up"
				in={ animateSurvey }
				onExited={ handleAnimationOnExited }
			>

					<SurveyCompletion
						dismissSurvey={ dismissSurvey }
						ctaOnClick={ ctaOnClick }
						ctaText={ triggeredCompletion.follow_up_text }
						ctaURL={ triggeredCompletion.follow_up_url }
						title={ triggeredCompletion.completion_title }
					>
						{ triggeredCompletion.completion_text }
					</SurveyCompletion>

			</Slide>
		);
	}

	// eslint-disable-next-line camelcase
	if ( ! KNOWN_QUESTION_TYPES.includes( currentQuestion?.question_type ) ) {
		return null;
	}

	const commonProps = {
		key: currentQuestion.question_text,
		answerQuestion,
		dismissSurvey,
		question: currentQuestion.question_text,
		submitButtonText:
			questions?.length === currentQuestionOrdinal
				? __( 'Submit', 'google-site-kit' )
				: __( 'Next', 'google-site-kit' ),
	};

	return (
		<Slide
			direction="up"
			in={ animateSurvey }
			onExited={ handleAnimationOnExited }
		>

				{ currentQuestion.question_type === TYPE_MULTI_SELECT && (
					<SurveyQuestionMultiSelect
						{ ...commonProps }
						choices={ currentQuestion.question.answer_choice }
						minChoices={ currentQuestion.question.min_choices }
						maxChoices={ currentQuestion.question.max_choices }
					/>
				) }
				{ currentQuestion.question_type === TYPE_OPEN_TEXT && (
					<SurveyQuestionOpenText
						{ ...commonProps }
						subtitle={ currentQuestion.question.subtitle }
						placeholder={ currentQuestion.question.placeholder }
					/>
				) }
				{ currentQuestion.question_type === TYPE_RATING && (
					<SurveyQuestionRating
						{ ...commonProps }
						choices={ currentQuestion.question.answer_choice }
					/>
				) }
				{ currentQuestion.question_type === TYPE_SINGLE_SELECT && (
					<SurveyQuestionSingleSelect
						{ ...commonProps }
						choices={ currentQuestion.question.answer_choice }
					/>
				) }

				{ isTrackingEnabled === false &&
					currentQuestion?.question_ordinal === 1 && ( // eslint-disable-line camelcase

							<SurveyTerms />

					) }

		</Slide>
	);
}
<|endoftext|>


<commit_before>
App.service('SensorGraph', /*@ngInject*/ function ($uibModal, Sensor, SensorFormatter) {
    var rickshaw = Rickshaw.Graph;

    function init($scope, element, height, sensorIds, parameters) {
        var legend = element.querySelector('.legend');

        $scope.$on('sensor.update', function(event, data) {
            if ($scope.isSensorActive(data.sensorId)) {
                update();
            }
        });

        Sensor.getCachedData().success(function(data) {
            $scope.types         = data.types;
            $scope.fromIntervals = data.fromIntervals;
            $scope.sensors       = data.sensors;
            $scope.tags          = aggregateTags(data.sensors);

            Sensor.getValues(sensorIds.join(':'), parameters).success(function (data) {
                var yAxisFormatter = getAxisFormatter(data.json);

                $scope.activeSensorIds = Object.keys(data.json).map(Number);
                $scope.ago   = data.ago;
                $scope.to    = data.to;
                $scope.stats = {};

                $scope.graph = new rickshaw({
                    element: element.querySelector('.chart'),
                    width: element.clientWidth - 40,
                    interpolation: 'basis',
                    height: height,
                    min: 'auto',
                    renderer: 'line',
                    series: decompressData(data)
                });
                new rickshaw.Axis.Time({graph: $scope.graph});
                new rickshaw.Axis.Y({
                    graph: $scope.graph,
                    orientation: 'right',
                    element: element.querySelector('.y_axis'),
                    tickFormat: yAxisFormatter
                });
                new rickshaw.ClickDetail({
                    graph: $scope.graph,
                    clickHandler (value){
                        $uibModal.open({
                            templateUrl: '/templates/sensor/sensor_value_detail.html',
                            controller: 'SensorValueDetailModalController',
                            resolve: {
                                value: () => value
                            }
                        }).result.then(update);
                    }
                });
                new rickshaw.HoverDetail({
                    graph: $scope.graph,
                    formatter (series, x, y) {
                        var type = $scope.types[series.type];
                        var formatter = SensorFormatter.getFormatter(series.formatter || type.formatter);
                        var date = new Date(x * 1000);
                        var dateString = '{0} {1}:{2}
'.format(
                            date.toDateString(),
                            ("0" + date.getHours()).slice(-2),
                            ("0" + parseInt(date.getMinutes())).slice(-2)
                        );
                        return dateString + series.name + ": " + formatter(y);
                    },
                    xFormatter (x) {
                        return new Date(x * 1000).toDateString();
                    }
                });

                new rickshaw.Legend({
                    element: legend,
                    graph: $scope.graph
                });

                $scope.graph.render();
            });
        });

        function update(parameter = '') {
            var activeIds  = $scope.activeSensorIds.join(':') || "0";
            var parameters = `?from=${$scope.ago}${parameter}`;

            /**
             * @param sensorValues
             */
            function updateGraph(sensorValues) {
                sensorValues.active = $scope.graph.series.active;
                $scope.graph.series = sensorValues;
                $scope.graph.update();

                legend.innerHTML = '';
                new rickshaw.Legend({
                    element: legend,
                    graph: $scope.graph
                });
            }

            Sensor.getValues(activeIds, parameters).success(function (data) {
                updateGraph(decompressData(data));
            });
        }

        /**
         * @param {Number} sensorId
         * @returns {boolean}
         */
        $scope.isSensorActive = function (sensorId) {
            return $scope.activeSensorIds && $scope.activeSensorIds.indexOf(~~sensorId) > -1;
        };

        /**
         * @param {Number} sensorId
         * @param {Number} ago
         */
        $scope.sensorView = function (sensorId, ago) {
            sensorId = ~~sensorId;
            $scope.ago = ago || $scope.ago;

            if (sensorId) {
                if ($scope.isSensorActive(sensorId)) {
                    var index = $scope.activeSensorIds.indexOf(sensorId);
                    $scope.activeSensorIds.splice(index, 1);
                } else {
                    $scope.activeSensorIds.push(sensorId);
                }
            }

            update('&save=1');

            return false;
        };
    }

    function getAxisFormatter(data) {
        var formatter = Rickshaw.Fixtures.Number.formatKMBT;
        var formatterName;
        for (let sensorId in data) {
            let currentFormatterName = data[sensorId].formatter;
            if (formatterName && currentFormatterName !== formatterName) {
                // other formatter is already registered :(
                return formatter;
            }

            formatterName = currentFormatterName;
        }

        if (formatterName) {
            return SensorFormatter.getFormatter(formatterName);
        }

        return formatter;
    }

    function decompressData(data) {
        var final = [];
        for (let sensorData of data.json) {
            var graphData = [];
            for (let i = 0; i < sensorData.data.length; i += 2) {
                graphData.push({
                    x: sensorData.data[i],
                    y: sensorData.data[i+1]
                });
            }
            sensorData = graphData;
            final.push(sensorData);
        }

        return final;
    }

    // todo use tag service
    function aggregateTags(rawSensors) {
        var tags = {};
        for (let sensor of rawSensors) {
            if (sensor.tags) {
                for (let tag of sensor.tags) {
                    if (!tags[tag]) {
                        tags[tag] = [];
                    }
                    tags[tag].push(sensor);
                }
            }
        }
        return tags;
    }

    return init;
});
<commit_msg>fixed build<commit_after>
App.service('SensorGraph', /*@ngInject*/ function ($uibModal, Sensor, SensorFormatter) {
    var rickshaw = Rickshaw.Graph;

    function init($scope, element, height, sensorIds, parameters) {
        var legend = element.querySelector('.legend');

        $scope.$on('sensor.update', function(event, data) {
            if ($scope.isSensorActive(data.sensorId)) {
                update();
            }
        });

        Sensor.getCachedData().success(function(data) {
            $scope.types         = data.types;
            $scope.fromIntervals = data.fromIntervals;
            $scope.sensors       = data.sensors;
            $scope.tags          = aggregateTags(data.sensors);

            Sensor.getValues(sensorIds.join(':'), parameters).success(function (data) {
                var yAxisFormatter = getAxisFormatter(data.json);

                $scope.activeSensorIds = Object.keys(data.json).map(Number);
                $scope.ago   = data.ago;
                $scope.to    = data.to;
                $scope.stats = {};

                $scope.graph = new rickshaw({
                    element: element.querySelector('.chart'),
                    width: element.clientWidth - 40,
                    interpolation: 'basis',
                    height: height,
                    min: 'auto',
                    renderer: 'line',
                    series: decompressData(data)
                });
                new rickshaw.Axis.Time({graph: $scope.graph});
                new rickshaw.Axis.Y({
                    graph: $scope.graph,
                    orientation: 'right',
                    element: element.querySelector('.y_axis'),
                    tickFormat: yAxisFormatter
                });
                new rickshaw.ClickDetail({
                    graph: $scope.graph,
                    clickHandler (value){
                        $uibModal.open({
                            templateUrl: '/templates/sensor/sensor_value_detail.html',
                            controller: 'SensorValueDetailModalController',
                            resolve: {
                                value: () => value
                            }
                        }).result.then(update);
                    }
                });
                new rickshaw.HoverDetail({
                    graph: $scope.graph,
                    formatter (series, x, y) {
                        var type = $scope.types[series.type];
                        var formatter = SensorFormatter.getFormatter(series.formatter || type.formatter);
                        var date = new Date(x * 1000);
                        var dateString = '{0} {1}:{2}
'.format(
                            date.toDateString(),
                            ("0" + date.getHours()).slice(-2),
                            ("0" + parseInt(date.getMinutes())).slice(-2)
                        );
                        return dateString + series.name + ": " + formatter(y);
                    },
                    xFormatter (x) {
                        return new Date(x * 1000).toDateString();
                    }
                });

                new rickshaw.Legend({
                    element: legend,
                    graph: $scope.graph
                });

                $scope.graph.render();
            });
        });

        function update(parameter = '') {
            var activeIds  = $scope.activeSensorIds.join(':') || "0";
            var parameters = `?from=${$scope.ago}${parameter}`;

            /**
             * @param sensorValues
             */
            function updateGraph(sensorValues) {
                sensorValues.active = $scope.graph.series.active;
                $scope.graph.series = sensorValues;
                $scope.graph.update();

                legend.innerHTML = '';
                new rickshaw.Legend({
                    element: legend,
                    graph: $scope.graph
                });
            }

            Sensor.getValues(activeIds, parameters).success(function (data) {
                updateGraph(decompressData(data));
            });
        }

        /**
         * @param {Number} sensorId
         * @returns {boolean}
         */
        $scope.isSensorActive = function (sensorId) {
            return $scope.activeSensorIds && $scope.activeSensorIds.indexOf(~~sensorId) > -1;
        };

        /**
         * @param {Number} sensorId
         * @param {Number} ago
         */
        $scope.sensorView = function (sensorId, ago) {
            sensorId = ~~sensorId;
            $scope.ago = ago || $scope.ago;

            if (sensorId) {
                if ($scope.isSensorActive(sensorId)) {
                    var index = $scope.activeSensorIds.indexOf(sensorId);
                    $scope.activeSensorIds.splice(index, 1);
                } else {
                    $scope.activeSensorIds.push(sensorId);
                }
            }

            update('&save=1');

            return false;
        };
    }

    function getAxisFormatter(data) {
        var formatter = Rickshaw.Fixtures.Number.formatKMBT;
        var formatterName;
        for (let sensorId in data) {
            let currentFormatterName = data[sensorId].formatter;
            if (formatterName && currentFormatterName !== formatterName) {
                // other formatter is already registered :(
                return formatter;
            }

            formatterName = currentFormatterName;
        }

        if (formatterName) {
            return SensorFormatter.getFormatter(formatterName);
        }

        return formatter;
    }

    function decompressData(data) {
        let final = [];
        for (let sensorId in data.json) {
            let graphData = [];
            for (let i = 0; i < data.json[sensorId].data.length; i += 2) {
                graphData.push({
                    x: data.json[sensorId].data[i],
                    y: data.json[sensorId].data[i+1]
                });
            }
            data.json[sensorId].data = graphData;
            final.push(data.json[sensorId]);
        }

        return final;
    }

    // todo use tag service
    function aggregateTags(rawSensors) {
        var tags = {};
        if (!rawSensors) {
            return tags;
        }
        for (let idx in rawSensors) {
            let sensor = rawSensors[idx];
            if (sensor.tags) {
                for (let tag of sensor.tags) {
                    if (!tags[tag]) {
                        tags[tag] = [];
                    }
                    tags[tag].push(sensor);
                }
            }
        }
        return tags;
    }

    return init;
});
<|endoftext|>


<commit_before>import Ember from 'ember';
import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin';

import ExpPlayerRouteMixin from 'exp-player/mixins/exp-player-route';

export default Ember.Route.extend(AuthenticatedRouteMixin, ExpPlayerRouteMixin, {
    currentUser: Ember.inject.service(),
    _getExperiment() {
        return new Ember.RSVP.Promise((resolve) => {
            resolve(this.modelFor('experiments.info'));
        });
    },
    _getSession(params, experiment) {
        return this.get('currentUser').getCurrentUser().then(([account, profile]) => {
            var session = this.store.createRecord(experiment.get('sessionCollectionId'), {
                experimentId: experiment.id,
                profileId: profile.get('id'),
                profileVersion: '', // TODO
                completed: false,
                feedback: '',
                hasReadFeedback: '',
                softwareVersion: '',
                expData: {},
                sequence: []
            });

            session.setProperties({
                id: 'PREVIEW_DATA_DISREGARD'
            });

            return session.reopen({
                save() {
                    // TODO add UI for researcher to see data
                    console.log('Preview Data Save:', this.toJSON());
                    return Ember.RSVP.resolve(this);
                }
            });
        });
    },
    actions: {
        willTransition: function(transition) {
            // FIXME: This won't prevent back button or manual URL change. See https://guides.emberjs.com/v2.3.0/routing/preventing-and-retrying-transitions/#toc_preventing-transitions-via-code-willtransition-code
            if (this.controller.isDirty() && !confirm('Are you sure you want to exit the experiment?')) {
                transition.abort();
                return false;
            } else {
                // Bubble this action to parent routes
                return true;
            }
        }
    }
});
<commit_msg>Re-open session in experimenter route subclass<commit_after>import Ember from 'ember';
import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin';

import ExpPlayerRouteMixin from 'exp-player/mixins/exp-player-route';

export default Ember.Route.extend(AuthenticatedRouteMixin, ExpPlayerRouteMixin, {
    currentUser: Ember.inject.service(),
    _getExperiment() {
        return new Ember.RSVP.Promise((resolve) => {
            resolve(this.modelFor('experiments.info'));
        });
    },
    _getSession(params, experiment) {
        this._super(params, experiment).then((session) => {
            session.setProperties({
                id: 'PREVIEW_DATA_DISREGARD'
            });

            return session.reopen({
                save() {
                    // TODO add UI for researcher to see data
                    console.log('Preview Data Save:', this.toJSON());
                    return Ember.RSVP.resolve(this);
                }
            });
        });
    },
    actions: {
        willTransition: function(transition) {
            // FIXME: This won't prevent back button or manual URL change. See https://guides.emberjs.com/v2.3.0/routing/preventing-and-retrying-transitions/#toc_preventing-transitions-via-code-willtransition-code
            if (this.controller.isDirty() && !confirm('Are you sure you want to exit the experiment?')) {
                transition.abort();
                return false;
            } else {
                // Bubble this action to parent routes
                return true;
            }
        }
    }
});
<|endoftext|>


<commit_before>import { HeatmapTiledPixiTrack } from './HeatmapTiledPixiTrack';
import { format } from 'd3-format';
import { tileProxy } from './services';

export default class HorizontalMultivecTrack extends HeatmapTiledPixiTrack {
  tileDataToCanvas(pixData) {
    const canvas = document.createElement('canvas');

    canvas.width = this.tilesetInfo.shape[0];
    canvas.height = this.tilesetInfo.shape[1];

    const ctx = canvas.getContext('2d');

    ctx.fillStyle = 'transparent';
    ctx.fillRect(0, 0, canvas.width, canvas.height);

    const pix = new ImageData(pixData, canvas.width, canvas.height);

    ctx.putImageData(pix, 0, 0);

    return canvas;
  }

  setSpriteProperties(sprite, zoomLevel, tilePos) {
    const { tileX, tileWidth } = this.getTilePosAndDimensions(zoomLevel,
      tilePos,
      this.tilesetInfo.tile_size);

    const tileEndX = tileX + tileWidth;

    sprite.width = this._refXScale(tileEndX) - this._refXScale(tileX);
    sprite.height = this.dimensions[1];

    sprite.x = this._refXScale(tileX);
    sprite.y = 0;
  }

  zoomed(newXScale, newYScale, k, tx) {
    super.zoomed(newXScale, newYScale);

    this.pMain.position.x = tx; // translateX;
    this.pMain.position.y = this.position[1]; // translateY;

    this.pMain.scale.x = k; // scaleX;
    this.pMain.scale.y = 1; // scaleY;

    this.drawColorbar();
  }

  calculateVisibleTiles() {
    // if we don't know anything about this dataset, no point
    // in trying to get tiles
    if (!this.tilesetInfo) { return; }

    this.zoomLevel = this.calculateZoomLevel();

    const sortedResolutions = this.tilesetInfo.resolutions
      .map(x => +x).sort((a, b) => b - a);

    this.xTiles = tileProxy.calculateTilesFromResolution(
      sortedResolutions[this.zoomLevel],
      this._xScale,
      this.tilesetInfo.min_pos[0],
      null,
      this.tilesetInfo.tile_size);

    const tiles = this.xTiles.map(x => [this.zoomLevel, x]);

    this.setVisibleTiles(tiles);
  }

  calculateZoomLevel() {
    if (!this.tilesetInfo)
      return;

    let minX = this.tilesetInfo.min_pos[0];

    let zoomIndexX = tileProxy.calculateZoomLevelFromResolutions(this.tilesetInfo.resolutions, this._xScale, minX);

    return zoomIndexX;
  }

  /*
   * The local tile identifier.
   *
   * tile contains [zoomLevel, xPos, yPos]
   */
  tileToLocalId(tile) {
    if (tile.dataTransform && tile.dataTransform !== 'default') {
      return `${tile.join('.')}.${tile.mirrored}.${tile.dataTransform}`;
    }

    return `${tile.join('.')}.${tile.mirrored}`;
  }

  /**
   * Create the local tile identifier, which be used with the
   * tile stores in TiledPixiTrack
   *
   * @param {array} tile: [zoomLevel, xPos]
   */
  tileToLocalId(tile) {
    return `${tile.join('.')}`;
  }

  /**
   * Create the remote tile identifier, which will be used to identify the
   * tile on the server
   *
   * @param {array} tile: [zoomLevel, xPos]
   */
  tileToRemoteId(tile) {
    return `${tile.join('.')}`;
  }

  /**
   * Calculate the tile position at the given track position
   *
   * @param {Number} trackX: The track's X position
   * @param {Number} trackY: The track's Y position
   *
   * @return {array} [zoomLevel, tilePos]
   */
  getTilePosAtPosition(trackX, trackY) {
    if (!this.tilesetInfo)
      return;

    const zoomLevel = this.calculateZoomLevel();

    // the width of the tile in base pairs
    const tileWidth = tileProxy.calculateTileWidth(this.tilesetInfo, zoomLevel, this.tilesetInfo.tile_size);

    // the position of the tile containing the query position
    const tilePos = this._xScale.invert(trackX) / tileWidth;

    return [zoomLevel, Math.floor(tilePos)];
  }

  /**
   * Return the data currently visible at position X and Y
   *
   * @param {Number} trackX: The x position relative to the track's start and end
   * @param {Number} trakcY: The y position relative to the track's start and end
   */
  getVisibleData(trackX, trackY) {
    const zoomLevel = this.calculateZoomLevel();

    // the width of the tile in base pairs
    const tileWidth = tileProxy.calculateTileWidth(this.tilesetInfo, zoomLevel, this.tilesetInfo.tile_size);

    // the position of the tile containing the query position
    const tilePos = this._xScale.invert(trackX) / tileWidth;

    console.log('tilesetInfo:', this.tilesetInfo);

    // the position of query within the tile
    const posInTileX = this.tilesetInfo.tile_size * (tilePos - Math.floor(tilePos));
    const posInTileY = (trackY / this.dimensions[1])  * this.tilesetInfo.shape[1];

    const tileId = this.tileToLocalId([zoomLevel, Math.floor(tilePos)])
    const fetchedTile = this.fetchedTiles[tileId];

    // console.log('tileId:', tileId);
    // console.log('vaft:', this.visibleAndFetchedTiles());

    let value = '';

    if (fetchedTile) {
      /*
      const a = rangeQuery2d(fetchedTile.tileData.dense,
        this.tilesetInfo.shape[0],
        this.tilesetInfo.shape[1],
        [Math.floor(posInTileX), Math.floor(posInTileX)],
        [posInTileY, posInTileY],
      */
      const index = this.tilesetInfo.shape[0] * Math.floor(posInTileY) + Math.floor(posInTileX);
      value = format(".3f")(fetchedTile.tileData.dense[index]);
    }

    console.log('posInTileX:', posInTileX);

    // add information about the row
    if (this.tilesetInfo.row_infos) {
      value += "
";
      value += this.tilesetInfo.row_infos[Math.floor(posInTileY)];
    }

    return `${value}`;
  }

    /**
     * Get some information to display when the mouse is over this
     * track
     *
     * @param {Number} trackX: the x position of the mouse over the track
     * @param {Number} trackY: the y position of the mouse over the track
     *
     * @return {string}: A HTML string containing the information to display
     *
     */
  getMouseOverHtml(trackX, trackY) {
    if (!this.tilesetInfo)
      return '';

    const tilePos = this.getTilePosAtPosition(trackX, trackY);

    let output = "Data value: " + this.getVisibleData(trackX, trackY) + "
";
    output += `Zoom level: ${tilePos[0]} tile position: ${tilePos[1]}`;

    return output;
  }
}
<commit_msg>Removed log statements from mouseover handler<commit_after>import { HeatmapTiledPixiTrack } from './HeatmapTiledPixiTrack';
import { format } from 'd3-format';
import { tileProxy } from './services';

export default class HorizontalMultivecTrack extends HeatmapTiledPixiTrack {
  tileDataToCanvas(pixData) {
    const canvas = document.createElement('canvas');

    canvas.width = this.tilesetInfo.shape[0];
    canvas.height = this.tilesetInfo.shape[1];

    const ctx = canvas.getContext('2d');

    ctx.fillStyle = 'transparent';
    ctx.fillRect(0, 0, canvas.width, canvas.height);

    const pix = new ImageData(pixData, canvas.width, canvas.height);

    ctx.putImageData(pix, 0, 0);

    return canvas;
  }

  setSpriteProperties(sprite, zoomLevel, tilePos) {
    const { tileX, tileWidth } = this.getTilePosAndDimensions(zoomLevel,
      tilePos,
      this.tilesetInfo.tile_size);

    const tileEndX = tileX + tileWidth;

    sprite.width = this._refXScale(tileEndX) - this._refXScale(tileX);
    sprite.height = this.dimensions[1];

    sprite.x = this._refXScale(tileX);
    sprite.y = 0;
  }

  zoomed(newXScale, newYScale, k, tx) {
    super.zoomed(newXScale, newYScale);

    this.pMain.position.x = tx; // translateX;
    this.pMain.position.y = this.position[1]; // translateY;

    this.pMain.scale.x = k; // scaleX;
    this.pMain.scale.y = 1; // scaleY;

    this.drawColorbar();
  }

  calculateVisibleTiles() {
    // if we don't know anything about this dataset, no point
    // in trying to get tiles
    if (!this.tilesetInfo) { return; }

    this.zoomLevel = this.calculateZoomLevel();

    const sortedResolutions = this.tilesetInfo.resolutions
      .map(x => +x).sort((a, b) => b - a);

    this.xTiles = tileProxy.calculateTilesFromResolution(
      sortedResolutions[this.zoomLevel],
      this._xScale,
      this.tilesetInfo.min_pos[0],
      null,
      this.tilesetInfo.tile_size);

    const tiles = this.xTiles.map(x => [this.zoomLevel, x]);

    this.setVisibleTiles(tiles);
  }

  calculateZoomLevel() {
    if (!this.tilesetInfo)
      return;

    let minX = this.tilesetInfo.min_pos[0];

    let zoomIndexX = tileProxy.calculateZoomLevelFromResolutions(this.tilesetInfo.resolutions, this._xScale, minX);

    return zoomIndexX;
  }

  /*
   * The local tile identifier.
   *
   * tile contains [zoomLevel, xPos, yPos]
   */
  tileToLocalId(tile) {
    if (tile.dataTransform && tile.dataTransform !== 'default') {
      return `${tile.join('.')}.${tile.mirrored}.${tile.dataTransform}`;
    }

    return `${tile.join('.')}.${tile.mirrored}`;
  }

  /**
   * Create the local tile identifier, which be used with the
   * tile stores in TiledPixiTrack
   *
   * @param {array} tile: [zoomLevel, xPos]
   */
  tileToLocalId(tile) {
    return `${tile.join('.')}`;
  }

  /**
   * Create the remote tile identifier, which will be used to identify the
   * tile on the server
   *
   * @param {array} tile: [zoomLevel, xPos]
   */
  tileToRemoteId(tile) {
    return `${tile.join('.')}`;
  }

  /**
   * Calculate the tile position at the given track position
   *
   * @param {Number} trackX: The track's X position
   * @param {Number} trackY: The track's Y position
   *
   * @return {array} [zoomLevel, tilePos]
   */
  getTilePosAtPosition(trackX, trackY) {
    if (!this.tilesetInfo)
      return;

    const zoomLevel = this.calculateZoomLevel();

    // the width of the tile in base pairs
    const tileWidth = tileProxy.calculateTileWidth(this.tilesetInfo, zoomLevel, this.tilesetInfo.tile_size);

    // the position of the tile containing the query position
    const tilePos = this._xScale.invert(trackX) / tileWidth;

    return [zoomLevel, Math.floor(tilePos)];
  }

  /**
   * Return the data currently visible at position X and Y
   *
   * @param {Number} trackX: The x position relative to the track's start and end
   * @param {Number} trakcY: The y position relative to the track's start and end
   */
  getVisibleData(trackX, trackY) {
    const zoomLevel = this.calculateZoomLevel();

    // the width of the tile in base pairs
    const tileWidth = tileProxy.calculateTileWidth(this.tilesetInfo, zoomLevel, this.tilesetInfo.tile_size);

    // the position of the tile containing the query position
    const tilePos = this._xScale.invert(trackX) / tileWidth;

    // the position of query within the tile
    const posInTileX = this.tilesetInfo.tile_size * (tilePos - Math.floor(tilePos));
    const posInTileY = (trackY / this.dimensions[1])  * this.tilesetInfo.shape[1];

    const tileId = this.tileToLocalId([zoomLevel, Math.floor(tilePos)])
    const fetchedTile = this.fetchedTiles[tileId];

    // console.log('tileId:', tileId);
    // console.log('vaft:', this.visibleAndFetchedTiles());

    let value = '';

    if (fetchedTile) {
      /*
      const a = rangeQuery2d(fetchedTile.tileData.dense,
        this.tilesetInfo.shape[0],
        this.tilesetInfo.shape[1],
        [Math.floor(posInTileX), Math.floor(posInTileX)],
        [posInTileY, posInTileY],
      */
      const index = this.tilesetInfo.shape[0] * Math.floor(posInTileY) + Math.floor(posInTileX);
      value = format(".3f")(fetchedTile.tileData.dense[index]);
    }

    // add information about the row
    if (this.tilesetInfo.row_infos) {
      value += "
";
      value += this.tilesetInfo.row_infos[Math.floor(posInTileY)];
    }

    return `${value}`;
  }

    /**
     * Get some information to display when the mouse is over this
     * track
     *
     * @param {Number} trackX: the x position of the mouse over the track
     * @param {Number} trackY: the y position of the mouse over the track
     *
     * @return {string}: A HTML string containing the information to display
     *
     */
  getMouseOverHtml(trackX, trackY) {
    if (!this.tilesetInfo)
      return '';

    const tilePos = this.getTilePosAtPosition(trackX, trackY);

    let output = "Data value: " + this.getVisibleData(trackX, trackY) + "
";
    output += `Zoom level: ${tilePos[0]} tile position: ${tilePos[1]}`;

    return output;
  }
}
<|endoftext|>


<commit_before>(function () {

  'use strict';
  angular
    .module('newplayer.component')

  /** @ngInject */
    .controller('npHTMLController',
    function ($log, $scope, $rootScope) {
      var vm = this,
        cmpData = $scope.component.data,
        content = null;
      $log.debug('npHTML::data', cmpData);

      if (cmpData.link) {
        this.link = cmpData.link;
      }

      this.content = cmpData.content;
      $log.info('npHTML::content', $scope.content, this.content, cmpData.link);

      this.handleLink = function() {
        $log.info('npHTML:handleLink | link is a manifest');
        $rootScope.$broadcast('npReplaceManifest', cmpData.link);
      }
    }
  )

  /** @ngInject */
    .run(
    function ($log, $rootScope) {
      $log.debug('npHTML::component loaded!');
    }
  );

})();
<commit_msg>formatting/jshint error squash<commit_after>(function () {
  'use strict';
  angular
    .module('newplayer.component')
  /** @ngInject */
    .controller('npHTMLController',
    function ($log, $scope, $rootScope) {
      var vm = this,
        cmpData = $scope.component.data,
        content = null;
      $log.debug('npHTML::data', cmpData);
      if (cmpData.link) {
        this.link = cmpData.link;
      }
      this.content = cmpData.content;
      $log.info('npHTML::content', $scope.content, this.content, cmpData.link);
      this.handleLink = function() {
        $log.info('npHTML:handleLink | link is a manifest');
        $rootScope.$broadcast('npReplaceManifest', cmpData.link);
      };
    }
  )
  /** @ngInject */
    .run(
    function ($log, $rootScope) {
      $log.debug('npHTML::component loaded!');
    }
  );
})();
<|endoftext|>


<commit_before>/*
 * @author     Alexander Shumilov
 * @copyright  2013-2018 MapCentia ApS
 * @license    http://www.gnu.org/licenses/#AGPL  GNU AFFERO GENERAL PUBLIC LICENSE 3
 */

import React from 'react';
import PropTypes from 'prop-types';

/**
 * Title field
 */
class TitleFieldComponent extends React.Component {
    constructor(props) {
        super(props);
        if (props.type !== `userOwned` && props.type !== `browserOwned`) {
            throw new Error(`Invalid type options`);
        }

        this.state = {
            title: (props.value ? props.value : ``)
        }
    }

    onChange(event) {
        this.setState({ title: event.target.value });
    }

    onSave() {
        this.props.onAdd(this.state.title);
        this.setState({ title: '' });
    }

    handleKeyPress(event) {
        if (event.key === `Enter` && this.state.title) {
            this.props.onAdd(this.state.title);
            this.setState({ title: '' });
        }
    }

    render() {
        let buttonStyle = {
            padding: `4px`,
            margin: `0px`
        };

        let cancelControl = false;
        if (this.props.onCancel) {
            cancelControl = (<button
                title={__(`Cancel`)}
                className="btn btn-xs btn-primary"
                onClick={this.props.onCancel}
                style={buttonStyle}>
                cancel
            </button>);
        }

        let containerStyle = { width: '50%', display: 'inline-table', paddingLeft: '8px' };
        if (`customStyle` in this.props && this.props.customStyle) {
            for (let key in this.props.customStyle) {
                containerStyle[key] = this.props.customStyle[key];
            }
        }

        return (

            <input
                id={(this.props.id ? this.props.id : ``)}
                value={this.state.title}
                type="text"
                className="form-control"
                placeholder={__("New title")}
                onChange={this.onChange.bind(this)}
                onKeyPress={this.handleKeyPress.bind(this)}/>

                <button
                    title={__(`Save`)}
                    className="btn btn-xs btn-primary"
                    onClick={this.onSave.bind(this)}
                    disabled={!this.state.title}
                    style={buttonStyle}>
                    save{(this.props.saveButtonText ? ` ` + this.props.saveButtonText : ``)}
                </button>
                {cancelControl}

);
    }
}

TitleFieldComponent.propTypes = {
    value: PropTypes.string,
    onAdd: PropTypes.func.isRequired,
    onCancel: PropTypes.func
};

export default TitleFieldComponent;<commit_msg>Minor style changes for Title field<commit_after>/*
 * @author     Alexander Shumilov
 * @copyright  2013-2018 MapCentia ApS
 * @license    http://www.gnu.org/licenses/#AGPL  GNU AFFERO GENERAL PUBLIC LICENSE 3
 */

import React from 'react';
import PropTypes from 'prop-types';

/**
 * Title field
 */
class TitleFieldComponent extends React.Component {
    constructor(props) {
        super(props);
        if (props.type !== `userOwned` && props.type !== `browserOwned`) {
            throw new Error(`Invalid type options`);
        }

        this.state = {
            title: (props.value ? props.value : ``)
        }
    }

    onChange(event) {
        this.setState({ title: event.target.value });
    }

    onSave() {
        this.props.onAdd(this.state.title);
        this.setState({ title: '' });
    }

    handleKeyPress(event) {
        if (event.key === `Enter` && this.state.title) {
            this.props.onAdd(this.state.title);
            this.setState({ title: '' });
        }
    }

    render() {
        let buttonStyle = {
            padding: `4px`,
            margin: `0px`
        };

        let cancelControl = false;
        if (this.props.onCancel) {
            cancelControl = (<button
                title={__(`Cancel`)}
                className="btn btn-xs btn-primary"
                onClick={this.props.onCancel}
                style={buttonStyle}>
                cancel
            </button>);
        }

        let containerStyle = { width: '50%', display: 'inline-table', paddingLeft: '8px' };
        if (`customStyle` in this.props && this.props.customStyle) {
            for (let key in this.props.customStyle) {
                containerStyle[key] = this.props.customStyle[key];
            }
        }

        let inputStyle = {};
        if (this.props.layout === `dense`) {
            inputStyle.marginBottom = `0px`;
        }

        return (

            <input
                id={(this.props.id ? this.props.id : ``)}
                value={this.state.title}
                type="text"
                className="form-control"
                placeholder={__("New title")}
                onChange={this.onChange.bind(this)}
                onKeyPress={this.handleKeyPress.bind(this)}
                style={inputStyle}/>

                <button
                    title={__(`Save`)}
                    className="btn btn-xs btn-primary"
                    onClick={this.onSave.bind(this)}
                    disabled={!this.state.title}
                    style={buttonStyle}>
                    save{(this.props.saveButtonText ? ` ` + this.props.saveButtonText : ``)}
                </button>
                {cancelControl}

);
    }
}

TitleFieldComponent.propTypes = {
    value: PropTypes.string,
    onAdd: PropTypes.func.isRequired,
    onCancel: PropTypes.func,
    layout: PropTypes.string
};

TitleFieldComponent.defaultProps = {
    layout: 'regular'
};

export default TitleFieldComponent;<|endoftext|>


<commit_before>(function(root, factory) {

  if (typeof exports !== 'undefined') {
    if (typeof module !== 'undefined' && module.exports) {
      exports = module.exports = factory(root, exports);
    }
  } else if (typeof define === 'function' && define.amd) {
    define(['exports'], function(exports) {
      root.Lockr = factory(root, exports);
    });
  } else {
    root.Lockr = factory(root, {});
  }

}(this, function(root, Lockr) {
  'use strict';

  if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function(elt /*, from*/)
    {
      var len = this.length >>> 0;

      var from = Number(arguments[1]) || 0;
      from = (from < 0)
      ? Math.ceil(from)
      : Math.floor(from);
      if (from < 0)
        from += len;

      for (; from < len; from++)
      {
        if (from in this &&
            this[from] === elt)
          return from;
      }
      return -1;
    };
  }

  Lockr.prefix = "";

  Lockr._getPrefixedKey = function(key, options) {
    options = options || {};

    if (options.noPrefix) {
      return key;
    } else {
      return this.prefix + key;
    }

  };

  Lockr.set = function (key, value, options) {
    var query_key = this._getPrefixedKey(key, options);

    try {
      localStorage.setItem(query_key, JSON.stringify({"data": value}));
    } catch (e) {
      if (console) console.warn("Lockr didn't successfully save the '{"+ key +": "+ value +"}' pair, because the localStorage is full.");
    }
  };

  Lockr.get = function (key, missing, options) {
    var query_key = this._getPrefixedKey(key, options),
        value;

    try {
      value = JSON.parse(localStorage.getItem(query_key));
    } catch (e) {
        try {
            if(localStorage[query_key]) {
                value = JSON.parse('{"data":"' + localStorage.getItem(query_key) + '"}');
            } else{
                value = null;
            }
        } catch (e) {
            if (console) console.warn("Lockr could not load the item with key " + key);
        }
    }
    if(value === null) {
      return missing;
    } else if (typeof value.data !== 'undefined') {
      return value.data;
    } else {
      return missing;
    }
  };

  Lockr.sadd = function(key, value, options) {
    var query_key = this._getPrefixedKey(key, options),
        json;

    var values = Lockr.smembers(key);

    if (values.indexOf(value) > -1) {
      return null;
    }

    try {
      values.push(value);
      json = JSON.stringify({"data": values});
      localStorage.setItem(query_key, json);
    } catch (e) {
      console.log(e);
      if (console) console.warn("Lockr didn't successfully add the "+ value +" to "+ key +" set, because the localStorage is full.");
    }
  };

  Lockr.smembers = function(key, options) {
    var query_key = this._getPrefixedKey(key, options),
        value;

    try {
      value = JSON.parse(localStorage.getItem(query_key));
    } catch (e) {
      value = null;
    }

    if (value === null)
      return [];
    else
      return (value.data || []);
  };

  Lockr.sismember = function(key, value, options) {
    var query_key = this._getPrefixedKey(key, options);

    return Lockr.smembers(key).indexOf(value) > -1;
  };

  Lockr.getAll = function () {
    var keys = Object.keys(localStorage);

    return keys.map(function (key) {
      return Lockr.get(key);
    });
  };

  Lockr.srem = function(key, value, options) {
    var query_key = this._getPrefixedKey(key, options),
        json,
        index;

    var values = Lockr.smembers(key, value);

    index = values.indexOf(value);

    if (index > -1)
      values.splice(index, 1);

    json = JSON.stringify({"data": values});

    try {
      localStorage.setItem(query_key, json);
    } catch (e) {
      if (console) console.warn("Lockr couldn't remove the "+ value +" from the set "+ key);
    }
  };

  Lockr.rm =  function (key) {
    localStorage.removeItem(key);
  };

  Lockr.flush = function () {
    localStorage.clear();
  };
  return Lockr;

}));
<commit_msg>Take prefix into account in getAll-function<commit_after>(function(root, factory) {

  if (typeof exports !== 'undefined') {
    if (typeof module !== 'undefined' && module.exports) {
      exports = module.exports = factory(root, exports);
    }
  } else if (typeof define === 'function' && define.amd) {
    define(['exports'], function(exports) {
      root.Lockr = factory(root, exports);
    });
  } else {
    root.Lockr = factory(root, {});
  }

}(this, function(root, Lockr) {
  'use strict';

  if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function(elt /*, from*/)
    {
      var len = this.length >>> 0;

      var from = Number(arguments[1]) || 0;
      from = (from < 0)
      ? Math.ceil(from)
      : Math.floor(from);
      if (from < 0)
        from += len;

      for (; from < len; from++)
      {
        if (from in this &&
            this[from] === elt)
          return from;
      }
      return -1;
    };
  }

  Lockr.prefix = "";

  Lockr._getPrefixedKey = function(key, options) {
    options = options || {};

    if (options.noPrefix) {
      return key;
    } else {
      return this.prefix + key;
    }

  };

  Lockr.set = function (key, value, options) {
    var query_key = this._getPrefixedKey(key, options);

    try {
      localStorage.setItem(query_key, JSON.stringify({"data": value}));
    } catch (e) {
      if (console) console.warn("Lockr didn't successfully save the '{"+ key +": "+ value +"}' pair, because the localStorage is full.");
    }
  };

  Lockr.get = function (key, missing, options) {
    var query_key = this._getPrefixedKey(key, options),
        value;

    try {
      value = JSON.parse(localStorage.getItem(query_key));
    } catch (e) {
        try {
            if(localStorage[query_key]) {
                value = JSON.parse('{"data":"' + localStorage.getItem(query_key) + '"}');
            } else{
                value = null;
            }
        } catch (e) {
            if (console) console.warn("Lockr could not load the item with key " + key);
        }
    }
    if(value === null) {
      return missing;
    } else if (typeof value.data !== 'undefined') {
      return value.data;
    } else {
      return missing;
    }
  };

  Lockr.sadd = function(key, value, options) {
    var query_key = this._getPrefixedKey(key, options),
        json;

    var values = Lockr.smembers(key);

    if (values.indexOf(value) > -1) {
      return null;
    }

    try {
      values.push(value);
      json = JSON.stringify({"data": values});
      localStorage.setItem(query_key, json);
    } catch (e) {
      console.log(e);
      if (console) console.warn("Lockr didn't successfully add the "+ value +" to "+ key +" set, because the localStorage is full.");
    }
  };

  Lockr.smembers = function(key, options) {
    var query_key = this._getPrefixedKey(key, options),
        value;

    try {
      value = JSON.parse(localStorage.getItem(query_key));
    } catch (e) {
      value = null;
    }

    if (value === null)
      return [];
    else
      return (value.data || []);
  };

  Lockr.sismember = function(key, value, options) {
    var query_key = this._getPrefixedKey(key, options);

    return Lockr.smembers(key).indexOf(value) > -1;
  };

  Lockr.getAll = function () {
    var keys = Object.keys(localStorage);

    keys = keys.filter(function (key) {
      return key.indexOf(Lockr.prefix) !== -1
    });

    return keys.map(function (key) {
      return Lockr.get(key.substr(Lockr.prefix.length));
    });
  };

  Lockr.srem = function(key, value, options) {
    var query_key = this._getPrefixedKey(key, options),
        json,
        index;

    var values = Lockr.smembers(key, value);

    index = values.indexOf(value);

    if (index > -1)
      values.splice(index, 1);

    json = JSON.stringify({"data": values});

    try {
      localStorage.setItem(query_key, json);
    } catch (e) {
      if (console) console.warn("Lockr couldn't remove the "+ value +" from the set "+ key);
    }
  };

  Lockr.rm =  function (key) {
    localStorage.removeItem(key);
  };

  Lockr.flush = function () {
    localStorage.clear();
  };
  return Lockr;

}));
<|endoftext|>