<commit_before>openerp.base_kanban = function (openerp) {
QWeb.add_template('/base_kanban/static/src/xml/base_kanban.xml');
openerp.base.views.add('kanban', 'openerp.base_kanban.KanbanView');
openerp.base_kanban.KanbanView = openerp.base.View.extend({

    init: function(parent, element_id, dataset, view_id) {
        this._super(parent, element_id);
        this.view_manager = parent;
        this.dataset = dataset;
        this.domain = dataset.domain;
        this.context = dataset.context;
        this.model = this.dataset.model;
        this.view_id = view_id;
        this.group_by_field = false;
        this.source_index = {};
        this.all_display_data = false;
        this.groups = [];
    },

    start: function() {
        this.rpc("/base_kanban/kanbanview/load",
        {"model": this.model, "view_id": this.view_id}, this.on_loaded);
    },
    on_loaded: function(data) {
        var self = this;
        this.template_xml = '';
        this.columns = data.all_fields;
        _.each(data.fields_view.arch.children, function(child) {
            if (child.tag == "template"){
                self.template_xml = openerp.base.json_node_to_xml(child, true)
            }
        });
        if(this.template_xml){
            self.dataset.read_slice({
                context: self.dataset.get_context(),
                domain: self.dataset.get_domain()}, function (records) {
                self.all_display_data = [{'records': records, 'value':false, 'header': false, 'ids': self.dataset.ids}];
                self.on_show_data(self.all_display_data);
            });
        }
    },

    on_show_data: function(datas) {
        var self = this;
        var new_qweb = new QWeb2.Engine();
        self.$element.html(QWeb.render("KanbanBiew", {"datas" :datas}));

        this.on_reload_kanban();
        this.$element.find(".oe_column").sortable({
            connectWith: ".oe_column",
            start: function(event, ui) {
                self.source_index['index'] = ui.item.index();
                self.source_index['column'] = ui.item.parent().attr('id');
            },
            stop: self.on_recieve_record,
        });
        this.$element.find(".record").addClass("ui-widget ui-widget-content ui-helper-clearfix ui-corner-all")
            .find(".record-header")
                .addClass("ui-widget-header ui-corner-all")
                .prepend( "")
                .end()
            .find( ".record-content" );

        this.$element.find(".record-header .ui-icon").click(function() {
            $(this).toggleClass("ui-icon-minusthick").toggleClass("ui-icon-plusthick");
            $(this).parents(".record:first").find(".record-content").toggle();
        });
        this.$element.find('.record .ui-icon-closethick').click(this.on_close_action);
        this.$element.find(".oe_column").disableSelection();
    },

    on_button_click: function(button_attrs, record_id){
        var self = this;
        if(this.groups.length){
            _.each(this.groups, function (group) {
                group.list([],
                    function (groups) {},
                    function (dataset) {
                        dataset.read_slice({}, function(records) {
                            var index = parseInt(_.indexOf(dataset.ids, record_id));
                            if(index >= 0) {
                                self.on_confirm_click(dataset, button_attrs, index, record_id);
                            }
                        });
                    }
                );
            });
        } else{
            var index = parseInt(_.indexOf(self.dataset.ids, record_id));
            if(index >= 0) {
                _.extend(self.dataset, {domain: self.domain, context: self.context})
                self.on_confirm_click(self.dataset, button_attrs, index, record_id)
            }
        }
    },

    on_confirm_click: function(dataset, button_attrs, index, record_id){
        if(button_attrs.type == 'edit') {
            this.do_edit_record(dataset, index);
        } else{
            this.on_execute_button_click(dataset, button_attrs, record_id)
        }
    },

    do_edit_record: function (dataset, index) {
        var self = this;
        _.extend(this.dataset, {
            domain: dataset.domain,
            context: dataset.get_context()
        }).read_slice({}, function () {
            self.dataset.index = index;
            self.do_switch_view('form');
        });
    },

    do_delete: function (id) {
        var self = this;
        return $.when(this.dataset.unlink([id])).then(function () {
            self.drop_records(id);
        });
    },

    drop_records: function (id) {
        var self = this;
        _.each(self.all_display_data, function(data, index) {
            _.each(data.records, function(record, index_row) {
                if(parseInt(record.id) == id) {
                    self.all_display_data[index]['records'].splice(index_row, 1)
                    return false;
                }
            });
        });
        self.$element.find("#main_" + id).remove()
    },

    on_execute_button_click: function(dataset, button_attrs, record_id) {
        var self = this;
        this.execute_action(
            button_attrs, dataset,
            record_id, function () {
                var count = 1;
                _.each(self.all_display_data, function(data, index) {
                    self.dataset.read_ids( data.ids, [], function(records){
                        self.all_display_data[index].records = records;
                        if(self.all_display_data.length == count) {
                            self.on_reload_kanban();
                        }
                        count++;
                    });
                });
            }
        );
    },

    on_close_action: function(e) {
        var record_id = $(e.currentTarget).parents('.record:first').attr("id")
        if(record_id) {
            record_id = parseInt(record_id.split("_")[1])
            if(record_id) {
                this.do_delete(record_id);
            }
        }
    },

    on_recieve_record: function(event, ui) {
        var self = this;
        var from = ui.item.index();
        var search_action = false;
        var to = ui.item.prev().index() || 0;
        if(!ui.item.attr("id")){
            return false;
        }
        if(self.columns.sequence && (self.source_index.index >= 0 && self.source_index.index != from) ||
                (self.source_index.column && self.source_index.column != ui.item.parent().attr('id'))) {
            var child_record = ui.item.parent().children();
            var data, sequence = 1, index = to;
            child_record.splice(0, to);
            if(to >= 0 && child_record) {
                var record_id = parseInt($(child_record).attr("id").split("_")[1]);
                if(record_id) {
                    var flag = false;
                    _.each(self.all_display_data, function(data, index) {
                        _.each(data.records, function(record, index_row) {
	                        if(record_id == record.id && record.sequence) {
	                            sequence = record.sequence;
	                            flag = true;
	                            return false;
	                        }
                        });
                        if(flag) {return false;}
                    });
                }
            }
            _.each(child_record, function (child) {
                var child_id = parseInt($(child).attr("id").split("_")[1]);
                if(child_id) {
                    var flag = false;
                    _.each(self.all_display_data, function(data, index) {
                        _.each(data.records, function(record, index_row) {
                            if(parseInt(record.id) == child_id) {
                                self.all_display_data[index]['records'][index_row]['sequence'] = sequence;
                                flag = true;
                                return false;
                            }
                        });
                        if(flag) {return false;}
                    });
                    self.dataset.write(child_id, {sequence: sequence});
                    sequence++;
                    search_action = true;
                }
            });
        }
        if(self.group_by_field && self.source_index.column && self.source_index.column != ui.item.parent().attr('id')) {
            var value = ui.item.closest("td").attr("id")
            if(value) {
                var data_val = {};
                var wirte_id = parseInt(ui.item.attr("id").split("_")[1]);
                value = value.split("_")[1];
                if(value == 'false') {
                    value = false;
                }
                var update_record = false;
                _.each(self.all_display_data, function(data, index) {
                    _.each(data.records, function(record, index_row) {
                        if(parseInt(record.id) == wirte_id) {
                            self.all_display_data[index]['records'][index_row][self.group_by_field] = value;
                            update_record = self.all_display_data[index]['records'].splice(index_row,1)
                            return false;
                        }
                    });
                    if(update_record) {return false;}
                });
                _.each(self.all_display_data, function(data, index) {
                    if (data.value == value || (data.value == 'false' && value == false)) {
                        self.all_display_data[index]['records'].push(update_record[0]);
                    }
                });
                data_val[self.group_by_field] = value;
                self.dataset.write(wirte_id, data_val);
                search_action = true;
            }
        }
        if(search_action) {
            self.on_reload_kanban();
        }
        this.source_index = {};
    },

    on_reload_kanban: function(){
        var self = this;
        var new_qweb = new QWeb2.Engine();
        new_qweb.add_template('<templates><t t-name="custom_template">' + this.template_xml + '</t></templates>')
        _.each(self.all_display_data, function(data, index) {
            if(data.records.length > 0){
                _.each(data.records, function(record) {
                    self.$element.find("#data_" + record.id).children().remove()
                    self.$element.find("#data_" + record.id).append(new_qweb.render('custom_template', record));
                });
            }
            else{
                self.$element.find("#column_" + data.value).remove();
                self.all_display_data.splice(index, 1);
            }
        });
        this.$element.find( ".oe_table_column " ).css("width", 99 / self.all_display_data.length +"%");
        this.$element.find('button').click(function(){
            var record_id = $(this).closest(".record").attr("id");
            if(record_id) {
                record_id = parseInt(record_id.split("_")[1])
                if(record_id) {
                    if($(this).data("type") == "delete") {
                        self.do_delete(record_id);
                    }
                    else{
                        var button_attrs = $(this).data()
                        self.on_button_click(button_attrs, record_id);
                    }
                }
            }
        });
    },

    do_search: function (domains, contexts, group_by) {
        var self = this;
        this.rpc('/base/session/eval_domain_and_context', {
            domains: domains,
            contexts: contexts,
            group_by_seq: group_by
        }, function (results) {
            self.group_by_field = false;
            self.datagroup = new openerp.base.DataGroup(self, self.model, results.domain, results.context, results.group_by || []);
            self.dataset.context = results.context;
            self.dataset.domain = results.domain;
            self.datagroup.list([],
                function (groups) {
                    self.groups = groups;
                    if (group_by.length >= 1) {
                        self.group_by_field = group_by[0].group_by;
                        self.do_render_group(groups);
                    }
                },
                function (dataset) {
                    self.domain = dataset.domain;
                    self.context = dataset.context;
                    self.groups = [];
                    self.dataset.read_slice({}, function(records) {
                        self.all_display_data = [{'records': records, 'value':false, 'header' : false, 'ids': self.dataset.ids}];
                        self.$element.find("#kanbanview").remove();
                        self.on_show_data(self.all_display_data);
                    });
                }
            );

        });
    },

    do_render_group : function(datagroups){
        this.all_display_data = [];
        var self = this;
        _.each(datagroups, function (group) {
            self.dataset.context = group.context;
            self.dataset.domain = group.domain;
            var group_name = group.value;
            var group_value = group.value;
            if(!group.value) {
                group_name = "Undefined";
                group_value = 'false';
            }
            else if(group.value instanceof Array) {
                group_name = group.value[1]
                group_value = group.value[0]
            }
            self.dataset.read_slice({}, function(records) {
                self.all_display_data.push({"value" : group_value, "records": records, 'header':group_name, 'ids': self.dataset.ids});
                if (datagroups.length == self.all_display_data.length) {
                    self.$element.find("#kanbanview").remove();
                    self.on_show_data(self.all_display_data);
                }
            });
        });
    },

    do_show: function () {
        this.$element.show();
    },

    do_hide: function () {
        this.$element.hide();
    },

});
};

// vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax:
<commit_msg>[FIX] Fix problem on dropd records.<commit_after>openerp.base_kanban = function (openerp) {
QWeb.add_template('/base_kanban/static/src/xml/base_kanban.xml');
openerp.base.views.add('kanban', 'openerp.base_kanban.KanbanView');
openerp.base_kanban.KanbanView = openerp.base.View.extend({

    init: function(parent, element_id, dataset, view_id) {
        this._super(parent, element_id);
        this.view_manager = parent;
        this.dataset = dataset;
        this.domain = dataset.domain;
        this.context = dataset.context;
        this.model = this.dataset.model;
        this.view_id = view_id;
        this.group_by_field = false;
        this.source_index = {};
        this.all_display_data = false;
        this.groups = [];
    },

    start: function() {
        this.rpc("/base_kanban/kanbanview/load",
        {"model": this.model, "view_id": this.view_id}, this.on_loaded);
    },
    on_loaded: function(data) {
        var self = this;
        this.template_xml = '';
        this.columns = data.all_fields;
        _.each(data.fields_view.arch.children, function(child) {
            if (child.tag == "template"){
                self.template_xml = openerp.base.json_node_to_xml(child, true)
            }
        });
        if(this.template_xml){
            self.dataset.read_slice({
                context: self.dataset.get_context(),
                domain: self.dataset.get_domain()}, function (records) {
                self.all_display_data = [{'records': records, 'value':false, 'header': false, 'ids': self.dataset.ids}];
                self.on_show_data(self.all_display_data);
            });
        }
    },

    on_show_data: function(datas) {
        var self = this;
        var new_qweb = new QWeb2.Engine();
        self.$element.html(QWeb.render("KanbanBiew", {"datas" :datas}));

        this.on_reload_kanban();
        this.$element.find(".oe_column").sortable({
            connectWith: ".oe_column",
            start: function(event, ui) {
                self.source_index['index'] = ui.item.index();
                self.source_index['column'] = ui.item.parent().attr('id');
            },
            stop: self.on_recieve_record,
        });
        this.$element.find(".record").addClass("ui-widget ui-widget-content ui-helper-clearfix ui-corner-all")
            .find(".record-header")
                .addClass("ui-widget-header ui-corner-all")
                .prepend( "")
                .end()
            .find( ".record-content" );

        this.$element.find(".record-header .ui-icon").click(function() {
            $(this).toggleClass("ui-icon-minusthick").toggleClass("ui-icon-plusthick");
            $(this).parents(".record:first").find(".record-content").toggle();
        });
        this.$element.find('.record .ui-icon-closethick').click(this.on_close_action);
        this.$element.find(".oe_column").disableSelection();
    },

    on_button_click: function(button_attrs, record_id){
        var self = this;
        if(this.groups.length){
            _.each(this.groups, function (group) {
                group.list([],
                    function (groups) {},
                    function (dataset) {
                        dataset.read_slice({}, function(records) {
                            var index = parseInt(_.indexOf(dataset.ids, record_id));
                            if(index >= 0) {
                                self.on_confirm_click(dataset, button_attrs, index, record_id);
                            }
                        });
                    }
                );
            });
        } else{
            var index = parseInt(_.indexOf(self.dataset.ids, record_id));
            if(index >= 0) {
                _.extend(self.dataset, {domain: self.domain, context: self.context})
                self.on_confirm_click(self.dataset, button_attrs, index, record_id)
            }
        }
    },

    on_confirm_click: function(dataset, button_attrs, index, record_id){
        if(button_attrs.type == 'edit') {
            this.do_edit_record(dataset, index);
        } else{
            this.on_execute_button_click(dataset, button_attrs, record_id)
        }
    },

    do_edit_record: function (dataset, index) {
        var self = this;
        _.extend(this.dataset, {
            domain: dataset.domain,
            context: dataset.get_context()
        }).read_slice({}, function () {
            self.dataset.index = index;
            self.do_switch_view('form');
        });
    },

    do_delete: function (id) {
        var self = this;
        return $.when(this.dataset.unlink([id])).then(function () {
            self.drop_records(id);
        });
    },

    drop_records: function (id) {
        var self = this;
        _.each(self.all_display_data, function(data, index) {
            _.each(data.records, function(record, index_row) {
                if(parseInt(record.id) == id) {
                    self.all_display_data[index]['records'].splice(index_row, 1)
                    self.all_display_data[index]['ids'].splice(index_row, 1)
                    return false;
                }
            });
        });
        self.$element.find("#main_" + id).remove()
    },

    on_execute_button_click: function(dataset, button_attrs, record_id) {
        var self = this;
        this.execute_action(
            button_attrs, dataset,
            record_id, function () {
                var count = 1;
                _.each(self.all_display_data, function(data, index) {
                    self.dataset.read_ids( data.ids, [], function(records){
                        self.all_display_data[index].records = records;
                        if(self.all_display_data.length == count) {
                            self.on_reload_kanban();
                        }
                        count++;
                    });
                });
            }
        );
    },

    on_close_action: function(e) {
        var record_id = $(e.currentTarget).parents('.record:first').attr("id")
        if(record_id) {
            record_id = parseInt(record_id.split("_")[1])
            if(record_id) {
                this.do_delete(record_id);
            }
        }
    },

    on_recieve_record: function(event, ui) {
        var self = this;
        var from = ui.item.index();
        var search_action = false;
        var to = ui.item.prev().index() || 0;
        if(!ui.item.attr("id")){
            return false;
        }
        if(self.columns.sequence && (self.source_index.index >= 0 && self.source_index.index != from) ||
                (self.source_index.column && self.source_index.column != ui.item.parent().attr('id'))) {
            var child_record = ui.item.parent().children();
            var data, sequence = 1, index = to;
            child_record.splice(0, to);
            if(to >= 0 && child_record) {
                var record_id = parseInt($(child_record).attr("id").split("_")[1]);
                if(record_id) {
                    var flag = false;
                    _.each(self.all_display_data, function(data, index) {
                        _.each(data.records, function(record, index_row) {
	                        if(record_id == record.id && record.sequence) {
	                            sequence = record.sequence;
	                            flag = true;
	                            return false;
	                        }
                        });
                        if(flag) {return false;}
                    });
                }
            }
            _.each(child_record, function (child) {
                var child_id = parseInt($(child).attr("id").split("_")[1]);
                if(child_id) {
                    var flag = false;
                    _.each(self.all_display_data, function(data, index) {
                        _.each(data.records, function(record, index_row) {
                            if(parseInt(record.id) == child_id) {
                                self.all_display_data[index]['records'][index_row]['sequence'] = sequence;
                                flag = true;
                                return false;
                            }
                        });
                        if(flag) {return false;}
                    });
                    self.dataset.write(child_id, {sequence: sequence});
                    sequence++;
                    search_action = true;
                }
            });
        }
        if(self.group_by_field && self.source_index.column && self.source_index.column != ui.item.parent().attr('id')) {
            var value = ui.item.closest("td").attr("id")
            if(value) {
                var data_val = {};
                var wirte_id = parseInt(ui.item.attr("id").split("_")[1]);
                value = value.split("_")[1];
                if(value == 'false') {
                    value = false;
                }
                var update_record = false;
                _.each(self.all_display_data, function(data, index) {
                    _.each(data.records, function(record, index_row) {
                        if(parseInt(record.id) == wirte_id) {
                            self.all_display_data[index]['records'][index_row][self.group_by_field] = value;
                            update_record = self.all_display_data[index]['records'].splice(index_row,1)
                            return false;
                        }
                    });
                    if(update_record) {return false;}
                });
                _.each(self.all_display_data, function(data, index) {
                    if (data.value == value || (data.value == 'false' && value == false)) {
                        self.all_display_data[index]['records'].push(update_record[0]);
                    }
                });
                data_val[self.group_by_field] = value;
                self.dataset.write(wirte_id, data_val);
                search_action = true;
            }
        }
        if(search_action) {
            self.on_reload_kanban();
        }
        this.source_index = {};
    },

    on_reload_kanban: function(){
        var self = this;
        var new_qweb = new QWeb2.Engine();
        new_qweb.add_template('<templates><t t-name="custom_template">' + this.template_xml + '</t></templates>')
        _.each(self.all_display_data, function(data, index) {
            if(data.records.length > 0){
                _.each(data.records, function(record) {
                    self.$element.find("#data_" + record.id).children().remove()
                    self.$element.find("#data_" + record.id).append(new_qweb.render('custom_template', record));
                });
            }
            else{
                self.$element.find("#column_" + data.value).remove();
                self.all_display_data.splice(index, 1);
            }
        });
        this.$element.find( ".oe_table_column " ).css("width", 99 / self.all_display_data.length +"%");
        this.$element.find('button').click(function(){
            var record_id = $(this).closest(".record").attr("id");
            if(record_id) {
                record_id = parseInt(record_id.split("_")[1])
                if(record_id) {
                    if($(this).data("type") == "delete") {
                        self.do_delete(record_id);
                    }
                    else{
                        var button_attrs = $(this).data()
                        self.on_button_click(button_attrs, record_id);
                    }
                }
            }
        });
    },

    do_search: function (domains, contexts, group_by) {
        var self = this;
        this.rpc('/base/session/eval_domain_and_context', {
            domains: domains,
            contexts: contexts,
            group_by_seq: group_by
        }, function (results) {
            self.group_by_field = false;
            self.datagroup = new openerp.base.DataGroup(self, self.model, results.domain, results.context, results.group_by || []);
            self.dataset.context = results.context;
            self.dataset.domain = results.domain;
            self.datagroup.list([],
                function (groups) {
                    self.groups = groups;
                    if (group_by.length >= 1) {
                        self.group_by_field = group_by[0].group_by;
                        self.do_render_group(groups);
                    }
                },
                function (dataset) {
                    self.domain = dataset.domain;
                    self.context = dataset.context;
                    self.groups = [];
                    self.dataset.read_slice({}, function(records) {
                        self.all_display_data = [{'records': records, 'value':false, 'header' : false, 'ids': self.dataset.ids}];
                        self.$element.find("#kanbanview").remove();
                        self.on_show_data(self.all_display_data);
                    });
                }
            );

        });
    },

    do_render_group : function(datagroups){
        this.all_display_data = [];
        var self = this;
        _.each(datagroups, function (group) {
            self.dataset.context = group.context;
            self.dataset.domain = group.domain;
            var group_name = group.value;
            var group_value = group.value;
            if(!group.value) {
                group_name = "Undefined";
                group_value = 'false';
            }
            else if(group.value instanceof Array) {
                group_name = group.value[1]
                group_value = group.value[0]
            }
            self.dataset.read_slice({}, function(records) {
                self.all_display_data.push({"value" : group_value, "records": records, 'header':group_name, 'ids': self.dataset.ids});
                if (datagroups.length == self.all_display_data.length) {
                    self.$element.find("#kanbanview").remove();
                    self.on_show_data(self.all_display_data);
                }
            });
        });
    },

    do_show: function () {
        this.$element.show();
    },

    do_hide: function () {
        this.$element.hide();
    },

});
};

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


<commit_before>var TransitionParser = require('../TransitionParser');

describe('TransitionParser', function () {

  it('should return an empty object when there is no transition', function () {
    var style = {
      background: '#FFF',
      height: '50px',
      width: '50px',
    };

    var transitions = TransitionParser.getTransitionValues(style);

    expect(transitions).toEqual({});
  });

  it('should parse transition shorthand correctly', function () {
    var style = {
      background: '#FFF',
      height: '50px',
      width: '50px',
      transition: 'background 1s, height 2s, width 3s',
    };

    var transitions = TransitionParser.getTransitionValues(style);

    expect(transitions).toEqual({
      transitionProperty: ['background', 'height', 'width'],
      transitionDuration: [1000, 2000, 3000],
      transitionDelay: [0, 0, 0],
    });
  });

  it('should parse transitions with different lengths correctly', function () {
    var style = {
      background: '#FFF',
      height: '50px',
      width: '50px',
      transitionProperty: 'background, height, width',
      transitionDuration: '1s, 2s',
      transitionDelay: '3s',
    };

    var transitions = TransitionParser.getTransitionValues(style);

    expect(transitions).toEqual({
      transitionProperty: ['background', 'height', 'width'],
      transitionDuration: [1000, 2000],
      transitionDelay: [3000],
    });
  });

  it('should parse respecting the order of appearance', function () {
    var style = {
      background: '#FFF',
      height: '50px',
      transition: 'background 1s 3s, height 2s 3s',
      transitionDelay: '4s',
    };

    var transitions = TransitionParser.getTransitionValues(style);

    expect(transitions).toEqual({
      transitionProperty: ['background', 'height'],
      transitionDuration: [1000, 2000],
      transitionDelay: [4000],
    });

    style = {
      background: '#FFF',
      height: '50px',
      transitionDelay: '4s',
      transition: 'background 1s 3s, height 2s 3s',
    };

    transitions = TransitionParser.getTransitionValues(style);

    expect(transitions).toEqual({
      transitionProperty: ['background', 'height'],
      transitionDuration: [1000, 2000],
      transitionDelay: [3000, 3000],
    });

    style = {
      background: '#FFF',
      height: '50px',
      transitionDelay: '4s',
      transition: 'background 1s 3s, height 2s 3s',
      transitionDuration: '5s, 6s',
    };

    transitions = TransitionParser.getTransitionValues(style);

    expect(transitions).toEqual({
      transitionProperty: ['background', 'height'],
      transitionDuration: [5000, 6000],
      transitionDelay: [3000, 3000],
    });
  });

  it('should parse the "all" property correctly', function () {
    var style = {
      background: '#FFF',
      height: '50px',
      width: '50px',
      transitionProperty: 'all, background',
      transitionDuration: '1s, 2s',
    };

    var transitions = TransitionParser.getTransitionValues(style);

    expect(transitions).toEqual({
      transitionProperty: ['all', 'background'],
      transitionDuration: [1000, 2000],
    });
  });

  it('should parse the "all" property in shorthands correctly', function () {
    var style = {
      background: '#FFF',
      height: '50px',
      width: '50px',
      transition: 'all 1s ease-out 1s, background 2s',
    };

    var transitions = TransitionParser.getTransitionValues(style);

    expect(transitions).toEqual({
      transitionProperty: ['all', 'background'],
      transitionDuration: [1000, 2000],
      transitionDelay: [1000, 0],
    });
  });

  it('should not differentiate uppercase and lowercase letters', function () {
    var style = {
      background: '#FFF',
      height: '50px',
      width: '50px',
      transition: 'AlL 1S, backgroUnD 2s',
    };

    var transitions = TransitionParser.getTransitionValues(style);

    expect(transitions).toEqual({
      transitionProperty: ['all', 'background'],
      transitionDuration: [1000, 2000],
      transitionDelay: [0, 0],
    });

    style = {
      background: '#FFF',
      height: '50px',
      width: '50px',
      transitionProperty: 'AlL, backgroUnD',
      transitionDuration: '1S, 2s',
    };

    transitions = TransitionParser.getTransitionValues(style);

    expect(transitions).toEqual({
      transitionProperty: ['all', 'background'],
      transitionDuration: [1000, 2000],
    });
  });

  it('should not handle "s" and "ms" units', function () {
    var style = {
      background: '#FFF',
      height: '50px',
      width: '50px',
      transition: 'all 1s, background 20ms',
    };

    var transitions = TransitionParser.getTransitionValues(style);

    expect(transitions).toEqual({
      transitionProperty: ['all', 'background'],
      transitionDuration: [1000, 20],
      transitionDelay: [0, 0],
    });

    style = {
      background: '#FFF',
      height: '50px',
      width: '50px',
      transitionProperty: 'all, background',
      transitionDuration: '1s, 20ms',
    };

    transitions = TransitionParser.getTransitionValues(style);

    expect(transitions).toEqual({
      transitionProperty: ['all', 'background'],
      transitionDuration: [1000, 20],
    });
  });

});<commit_msg>Add tests of browser prefix and multiple spaces<commit_after>var TransitionParser = require('../TransitionParser');

describe('TransitionParser', function () {

  it('should return an empty object when there is no transition', function () {
    var style = {
      background: '#FFF',
      height: '50px',
      width: '50px',
    };

    var transitions = TransitionParser.getTransitionValues(style);

    expect(transitions).toEqual({});
  });

  it('should parse transition shorthand correctly', function () {
    var style = {
      background: '#FFF',
      height: '50px',
      width: '50px',
      transition: 'background 1s, height 2s, width 3s',
    };

    var transitions = TransitionParser.getTransitionValues(style);

    expect(transitions).toEqual({
      transitionProperty: ['background', 'height', 'width'],
      transitionDuration: [1000, 2000, 3000],
      transitionDelay: [0, 0, 0],
    });
  });

  it('should parse transitions with different lengths correctly', function () {
    var style = {
      background: '#FFF',
      height: '50px',
      width: '50px',
      transitionProperty: 'background, height, width',
      transitionDuration: '1s, 2s',
      transitionDelay: '3s',
    };

    var transitions = TransitionParser.getTransitionValues(style);

    expect(transitions).toEqual({
      transitionProperty: ['background', 'height', 'width'],
      transitionDuration: [1000, 2000],
      transitionDelay: [3000],
    });
  });

  it('should parse respecting the order of appearance', function () {
    var style = {
      background: '#FFF',
      height: '50px',
      transition: 'background 1s 3s, height 2s 3s',
      transitionDelay: '4s',
    };

    var transitions = TransitionParser.getTransitionValues(style);

    expect(transitions).toEqual({
      transitionProperty: ['background', 'height'],
      transitionDuration: [1000, 2000],
      transitionDelay: [4000],
    });

    style = {
      background: '#FFF',
      height: '50px',
      transitionDelay: '4s',
      transition: 'background 1s 3s, height 2s 3s',
    };

    transitions = TransitionParser.getTransitionValues(style);

    expect(transitions).toEqual({
      transitionProperty: ['background', 'height'],
      transitionDuration: [1000, 2000],
      transitionDelay: [3000, 3000],
    });

    style = {
      background: '#FFF',
      height: '50px',
      transitionDelay: '4s',
      transition: 'background 1s 3s, height 2s 3s',
      transitionDuration: '5s, 6s',
    };

    transitions = TransitionParser.getTransitionValues(style);

    expect(transitions).toEqual({
      transitionProperty: ['background', 'height'],
      transitionDuration: [5000, 6000],
      transitionDelay: [3000, 3000],
    });
  });

  it('should parse the "all" property correctly', function () {
    var style = {
      background: '#FFF',
      height: '50px',
      width: '50px',
      transitionProperty: 'all, background',
      transitionDuration: '1s, 2s',
    };

    var transitions = TransitionParser.getTransitionValues(style);

    expect(transitions).toEqual({
      transitionProperty: ['all', 'background'],
      transitionDuration: [1000, 2000],
    });
  });

  it('should parse the "all" property in shorthands correctly', function () {
    var style = {
      background: '#FFF',
      height: '50px',
      width: '50px',
      transition: 'all 1s ease-out 1s, background 2s',
    };

    var transitions = TransitionParser.getTransitionValues(style);

    expect(transitions).toEqual({
      transitionProperty: ['all', 'background'],
      transitionDuration: [1000, 2000],
      transitionDelay: [1000, 0],
    });
  });

  it('should not differentiate uppercase and lowercase letters', function () {
    var style = {
      background: '#FFF',
      height: '50px',
      width: '50px',
      transition: 'AlL 1S, backgroUnD 2s',
    };

    var transitions = TransitionParser.getTransitionValues(style);

    expect(transitions).toEqual({
      transitionProperty: ['all', 'background'],
      transitionDuration: [1000, 2000],
      transitionDelay: [0, 0],
    });

    style = {
      background: '#FFF',
      height: '50px',
      width: '50px',
      transitionProperty: 'AlL, backgroUnD',
      transitionDuration: '1S, 2s',
    };

    transitions = TransitionParser.getTransitionValues(style);

    expect(transitions).toEqual({
      transitionProperty: ['all', 'background'],
      transitionDuration: [1000, 2000],
    });
  });

  it('should not handle "s" and "ms" units', function () {
    var style = {
      background: '#FFF',
      height: '50px',
      width: '50px',
      transition: 'all 1s, background 20ms',
    };

    var transitions = TransitionParser.getTransitionValues(style);

    expect(transitions).toEqual({
      transitionProperty: ['all', 'background'],
      transitionDuration: [1000, 20],
      transitionDelay: [0, 0],
    });

    style = {
      background: '#FFF',
      height: '50px',
      width: '50px',
      transitionProperty: 'all, background',
      transitionDuration: '1s, 20ms',
    };

    transitions = TransitionParser.getTransitionValues(style);

    expect(transitions).toEqual({
      transitionProperty: ['all', 'background'],
      transitionDuration: [1000, 20],
    });
  });

  it('should handle extra spaces correctly', function () {
    var style = {
      background: '#FFF',
      height: '50px',
      width: '50px',
      transition: '    all     1s   ,background   20ms    ',
    };

    var transitions = TransitionParser.getTransitionValues(style);

    expect(transitions).toEqual({
      transitionProperty: ['all', 'background'],
      transitionDuration: [1000, 20],
      transitionDelay: [0, 0],
    });

    style = {
      background: '#FFF',
      height: '50px',
      width: '50px',
      transitionProperty: '    all   ,    background',
      transitionDuration: '1s,20ms',
    };

    transitions = TransitionParser.getTransitionValues(style);

    expect(transitions).toEqual({
      transitionProperty: ['all', 'background'],
      transitionDuration: [1000, 20],
    });
  });

  it('should handle browser prefixes correctly', function () {
    var style = {
      background: '#FFF',
      height: '50px',
      width: '50px',
      transition: 'all 1s ,background 20ms',
      WebkitTransition: 'all 1s ,background 2s',
    };

    var transitions = TransitionParser.getTransitionValues(style);

    expect(transitions).toEqual({
      transitionProperty: ['all', 'background'],
      transitionDuration: [1000, 2000],
      transitionDelay: [0, 0],
    });

    style = {
      background: '#FFF',
      height: '50px',
      width: '50px',
      transition: 'all 1s ,background 20ms',
      MozTransition: 'all 1s ,background 2s',
    };

    transitions = TransitionParser.getTransitionValues(style);

    expect(transitions).toEqual({
      transitionProperty: ['all', 'background'],
      transitionDuration: [1000, 2000],
      transitionDelay: [0, 0],
    });

    style = {
      background: '#FFF',
      height: '50px',
      width: '50px',
      transition: 'all 1s ,background 20ms',
      msTransition: 'all 1s ,background 2s',
    };

    transitions = TransitionParser.getTransitionValues(style);

    expect(transitions).toEqual({
      transitionProperty: ['all', 'background'],
      transitionDuration: [1000, 2000],
      transitionDelay: [0, 0],
    });
  });

});<|endoftext|>


<commit_before>'use strict';

var fs = require('fs'),
    path = require('path');

var Ipc = require('ipc'),
    app = require('app'),
    browserOpen = require('./util/browser-open'),
    Dialog = require('dialog');

var errorUtil = require('./util/error'),
    parseUtil = require('./util/parse');

var SUPPORTED_EXT = [ 'bpmn', 'dmn', 'xml' ];

var SUPPORTED_EXT_BPMN = { name: 'BPMN diagram', extensions: [ 'bpmn', 'xml' ] },
    SUPPORTED_EXT_DMN = { name: 'DMN table', extensions: [ 'dmn', 'xml' ] };

var SUPPORTED_EXT_FILTER = [
  { name: 'All supported', extensions: SUPPORTED_EXT },
  SUPPORTED_EXT_BPMN,
  SUPPORTED_EXT_DMN,
  { name: 'All files', extensions: [ '*' ] }
];

var FILE_ENCODING = { encoding: 'utf8' };

/**
 * General structure for the diagram's file as an object.
 *
 * @param  {String} filePath
 * @param  {String} file
 */
function createDiagramFile(filePath, file) {
  return {
    contents: file,
    name: path.basename(filePath),
    notation: parseUtil.extractNotation(file),
    path: filePath
  };
}

/**
 * Interface for handling files.
 *
 * @param  {Object} browserWindow   Main browser window
 */
function FileSystem(browserWindow, config) {
  var self = this;

  this.browserWindow = browserWindow;
  this.config = config;

  Ipc.on('file.save', function(evt, newDirectory, diagramFile) {
    self.save(newDirectory, diagramFile, function(err, updatedDiagram) {
      if (err) {
        return self.handleError('file.save.response', err);
      }

      app.emit('editor:add-recent', updatedDiagram.path);

      browserWindow.webContents.send('file.save.response', null, updatedDiagram);
    });
  });

  Ipc.on('file.add', function(evt, path) {
    self.addFile(path);
  });

  Ipc.on('file.open', function(evt) {
    self.open(function(err, diagramFile) {
      if (err) {
        return self.handleError('file.open.response', err);
      }

      app.emit('editor:add-recent', diagramFile.path);

      browserWindow.webContents.send('file.open.response', null, diagramFile);
    });
  });

  Ipc.on('file.close', function(evt, diagramFile) {
    self.close(diagramFile, function(err, updatedDiagram) {
      if (err) {
        return self.handleError('file.close.response', err);
      }

      browserWindow.webContents.send('file.close.response', null, updatedDiagram);
    });
  });

  Ipc.on('editor.quit', function(evt, hasUnsavedChanges) {
    self.browserWindow.webContents.send('editor.quit.response', null);

    return app.emit('editor:quit-allowed');
  });

  Ipc.on('editor.import.error', function(evt, diagramFile, trace) {
    self.handleImportError(diagramFile, trace, function(result) {
      self.browserWindow.webContents.send('editor.import.error.response', result);

      self.browserWindow.webContents.send('editor.actions', { event: 'editor.close' });
    });
  });

  Ipc.on('editor.ready', function(evt) {
    app.emit('editor:ready');
  });
}

FileSystem.prototype.open = function(callback) {
  var self = this;

  this.showOpenDialog(function(filenames) {
    if (!filenames) {
      return callback(new Error(errorUtil.CANCELLATION_MESSAGE));
    }

    self._openFile(filenames[0], callback);
  });
};

FileSystem.prototype._openFile = function(filePath, callback) {
  var self = this;

  var diagramFile;

  try {
    diagramFile = readDiagram(filePath);

    if (!diagramFile.notation) {
      self.showUnrecognizedFileDialog(diagramFile.name);

      return self.open(callback);
    }
  } catch (err) {
    return callback(err);
  }

  if (parseUtil.hasActivitiURL(diagramFile.contents)) {

    self.showNamespaceDialog(function(answer) {
      if (answer === 0) {
        diagramFile.contents = parseUtil.replaceNamespace(diagramFile.contents);
      }

      callback(null, diagramFile);
    });
  } else {
    callback(null, diagramFile);
  }
};

FileSystem.prototype.addFile = function(filePath) {
  var self = this,
      browserWindow = this.browserWindow;

  this._openFile(filePath, function(err, diagramFile) {
    if (err) {
      return self.showGeneralErrorDialog();
    }

    browserWindow.webContents.send('editor.actions', {
      event: 'file.add',
      data: {
        diagram: diagramFile
      }
    });
  });
};

FileSystem.prototype.save = function(newDirectory, diagramFile, callback) {
  var self = this;

  // Save as..
  if (newDirectory || diagramFile.path === '[unsaved]') {
    this.showSaveAsDialog(diagramFile, function(filename) {
      if (!filename) {
        return callback(new Error(errorUtil.CANCELLATION_MESSAGE));
      }

      filename = self.sanitizeFilename(filename, diagramFile.notation);

      self._save(filename, diagramFile, callback);
    });
  } else {
    this._save(diagramFile.path, diagramFile, callback);
  }
};

FileSystem.prototype._save = function(filePath, diagramFile, callback) {

  try {
    var newDiagramFile = writeDiagram(filePath, diagramFile);

    callback(null, newDiagramFile);
  } catch (err) {
    callback(err);
  }
};

FileSystem.prototype.close = function(diagramFile, callback) {
  var self = this;

  this.showCloseDialog(diagramFile.name, function(result) {
    if (result === 2) {
      return callback(new Error(errorUtil.CANCELLATION_MESSAGE));
    }
    else if (result === 1) {
      // omitting the diagram to indicate that
      // stuff was not saved...
      return callback(null);
    }
    else {
      self.save(null, diagramFile, callback);
    }
  });
};

FileSystem.prototype.handleImportError = function(diagramFile, trace, callback) {

  this.showImportErrorDialog(diagramFile.name, trace, function(answer) {
    switch (answer) {
      case 1:
        browserOpen('https://forum.bpmn.io/');
        callback('forum');
        break;
      case 2:
        browserOpen('https://github.com/bpmn-io/bpmn-js/issues');
        callback('tracker');
        break;
      default:
        callback('close');
    }
  });
};

/**
 * Handle errors that the IPC has to deal with.
 *
 * @param  {String} event
 * @param  {Error} err
 */
FileSystem.prototype.handleError = function(event, err) {
  if (!errorUtil.isCancel(err)) {
    this.showGeneralErrorDialog();
  }
  this.browserWindow.webContents.send(event, errorUtil.normalizeError(err));
};

FileSystem.prototype.showOpenDialog = function(callback) {
  var config = this.config,
      defaultPath = config.get('defaultPath', app.getPath('userDesktop')),
      filenames;

  var opts = {
    title: 'Open diagram',
    defaultPath: defaultPath,
    properties: [ 'openFile' ],
    filters: SUPPORTED_EXT_FILTER,
    noLink: true
  };

  filenames = Dialog.showOpenDialog(this.browserWindow, opts);

  if (filenames) {
    config.set('defaultPath', path.dirname(filenames[0]));
  }

  callback(filenames);
};

FileSystem.prototype.showSaveAsDialog = function(diagramFile, callback) {
  var config = this.config,
      defaultPath = config.get('defaultPath', app.getPath('userDesktop'));

  var notation = diagramFile.notation,
      name = diagramFile.name,
      filters = [];

  if (notation === 'bpmn') {
    filters.push(SUPPORTED_EXT_BPMN);
  } else {
    filters.push(SUPPORTED_EXT_DMN);
  }

  var opts = {
    title: 'Save ' + name + ' as..',
    filters: filters,
    defaultPath: defaultPath,
    noLink: true
  };

  callback(Dialog.showSaveDialog(this.browserWindow, opts));
};

FileSystem.prototype.showCloseDialog = function(name, callback) {
  var opts = {
    title: 'Close diagram',
    message: 'Save changes to ' + name + ' before closing?',
    type: 'question',
    buttons: [ 'Save', 'Don\'t Save', 'Cancel' ],
    noLink: true
  };

  callback(Dialog.showMessageBox(this.browserWindow, opts));
};

FileSystem.prototype.showImportErrorDialog = function(fileName, trace, callback) {
  var opts = {
    type: 'error',
    title: 'Importing Error',
    buttons: [ 'Close', 'Forum', 'Issue Tracker' ],
    message: 'Ooops, we could not display this diagram!',
    detail: [
      'Do you believe "' + fileName + '" is valid BPMN or DMN diagram?',
      'If so, please consult our forum or file an issue in our issue tracker.',
      '',
      trace
    ].join('\n'),
    noLink: true
  };

  callback(Dialog.showMessageBox(this.browserWindow, opts));
};

FileSystem.prototype.showUnrecognizedFileDialog = function(name) {
  Dialog.showMessageBox({
    type: 'warning',
    title: 'Unrecognized file format',
    buttons: [ 'Close' ],
    message: 'The file "' + name + '" is not a BPMN or DMN file.',
    noLink: true
  });
};

FileSystem.prototype.showNamespaceDialog = function(callback) {
  var opts = {
    type: 'warning',
    title: 'Deprecated <activiti> namespace detected',
    buttons: [ 'Yes', 'No' ],
    message: 'Would you like to convert your diagram to the <camunda> namespace?',
    detail: [
      'This will allow you to maintain execution related properties.',
      '',
      '<camunda> namespace support works from Camunda BPM version 7.4.0, 7.3.3, 7.2.6 onwards.'
    ].join('\n'),
    noLink: true
  };

  callback(Dialog.showMessageBox(this.browserWindow, opts));
};

FileSystem.prototype.showGeneralErrorDialog = function() {
  Dialog.showErrorBox('Error', 'There was an internal error.' + '\n' + 'Please try again.');
};

FileSystem.prototype.sanitizeFilename = function(filename, notation) {
  var extension = path.extname(filename);

  if (extension === '') {
    return filename + '.' + notation;
  }

  return filename;
};

module.exports = FileSystem;

function readDiagram(diagramPath) {

  var contents = fs.readFileSync(diagramPath, FILE_ENCODING);

  // trim leading and trailing whitespace
  // this fixes obscure import errors for non-strict
  // xml exports
  contents = contents.replace(/(^\s*|\s*$)/g, '');

  return createDiagramFile(diagramPath, contents);
}

module.exports.readDiagram = readDiagram;

var assign = require('lodash/object/assign');

function writeDiagram(diagramPath, diagramFile) {
  fs.writeFileSync(diagramPath, diagramFile.contents, FILE_ENCODING);

  return assign({}, diagramFile, {
    name: path.basename(diagramPath),
    path: diagramPath
  });
}

module.exports.writeDiagram = writeDiagram;<commit_msg>feat(app): remember target folder during Save As...<commit_after>'use strict';

var fs = require('fs'),
    path = require('path');

var Ipc = require('ipc'),
    app = require('app'),
    browserOpen = require('./util/browser-open'),
    Dialog = require('dialog');

var errorUtil = require('./util/error'),
    parseUtil = require('./util/parse');

var SUPPORTED_EXT = [ 'bpmn', 'dmn', 'xml' ];

var SUPPORTED_EXT_BPMN = { name: 'BPMN diagram', extensions: [ 'bpmn', 'xml' ] },
    SUPPORTED_EXT_DMN = { name: 'DMN table', extensions: [ 'dmn', 'xml' ] };

var SUPPORTED_EXT_FILTER = [
  { name: 'All supported', extensions: SUPPORTED_EXT },
  SUPPORTED_EXT_BPMN,
  SUPPORTED_EXT_DMN,
  { name: 'All files', extensions: [ '*' ] }
];

var FILE_ENCODING = { encoding: 'utf8' };

/**
 * General structure for the diagram's file as an object.
 *
 * @param  {String} filePath
 * @param  {String} file
 */
function createDiagramFile(filePath, file) {
  return {
    contents: file,
    name: path.basename(filePath),
    notation: parseUtil.extractNotation(file),
    path: filePath
  };
}

/**
 * Interface for handling files.
 *
 * @param  {Object} browserWindow   Main browser window
 */
function FileSystem(browserWindow, config) {
  var self = this;

  this.browserWindow = browserWindow;
  this.config = config;

  Ipc.on('file.save', function(evt, newDirectory, diagramFile) {
    self.save(newDirectory, diagramFile, function(err, updatedDiagram) {
      if (err) {
        return self.handleError('file.save.response', err);
      }

      app.emit('editor:add-recent', updatedDiagram.path);

      browserWindow.webContents.send('file.save.response', null, updatedDiagram);
    });
  });

  Ipc.on('file.add', function(evt, path) {
    self.addFile(path);
  });

  Ipc.on('file.open', function(evt) {
    self.open(function(err, diagramFile) {
      if (err) {
        return self.handleError('file.open.response', err);
      }

      app.emit('editor:add-recent', diagramFile.path);

      browserWindow.webContents.send('file.open.response', null, diagramFile);
    });
  });

  Ipc.on('file.close', function(evt, diagramFile) {
    self.close(diagramFile, function(err, updatedDiagram) {
      if (err) {
        return self.handleError('file.close.response', err);
      }

      browserWindow.webContents.send('file.close.response', null, updatedDiagram);
    });
  });

  Ipc.on('editor.quit', function(evt, hasUnsavedChanges) {
    self.browserWindow.webContents.send('editor.quit.response', null);

    return app.emit('editor:quit-allowed');
  });

  Ipc.on('editor.import.error', function(evt, diagramFile, trace) {
    self.handleImportError(diagramFile, trace, function(result) {
      self.browserWindow.webContents.send('editor.import.error.response', result);

      self.browserWindow.webContents.send('editor.actions', { event: 'editor.close' });
    });
  });

  Ipc.on('editor.ready', function(evt) {
    app.emit('editor:ready');
  });
}

FileSystem.prototype.open = function(callback) {
  var self = this;

  this.showOpenDialog(function(filenames) {
    if (!filenames) {
      return callback(new Error(errorUtil.CANCELLATION_MESSAGE));
    }

    self._openFile(filenames[0], callback);
  });
};

FileSystem.prototype._openFile = function(filePath, callback) {
  var self = this;

  var diagramFile;

  try {
    diagramFile = readDiagram(filePath);

    if (!diagramFile.notation) {
      self.showUnrecognizedFileDialog(diagramFile.name);

      return self.open(callback);
    }
  } catch (err) {
    return callback(err);
  }

  if (parseUtil.hasActivitiURL(diagramFile.contents)) {

    self.showNamespaceDialog(function(answer) {
      if (answer === 0) {
        diagramFile.contents = parseUtil.replaceNamespace(diagramFile.contents);
      }

      callback(null, diagramFile);
    });
  } else {
    callback(null, diagramFile);
  }
};

FileSystem.prototype.addFile = function(filePath) {
  var self = this,
      browserWindow = this.browserWindow;

  this._openFile(filePath, function(err, diagramFile) {
    if (err) {
      return self.showGeneralErrorDialog();
    }

    browserWindow.webContents.send('editor.actions', {
      event: 'file.add',
      data: {
        diagram: diagramFile
      }
    });
  });
};

FileSystem.prototype.save = function(newDirectory, diagramFile, callback) {
  var self = this;

  // Save as..
  if (newDirectory || diagramFile.path === '[unsaved]') {
    this.showSaveAsDialog(diagramFile, function(filename) {
      if (!filename) {
        return callback(new Error(errorUtil.CANCELLATION_MESSAGE));
      }

      filename = self.sanitizeFilename(filename, diagramFile.notation);

      self._save(filename, diagramFile, callback);
    });
  } else {
    this._save(diagramFile.path, diagramFile, callback);
  }
};

FileSystem.prototype._save = function(filePath, diagramFile, callback) {

  try {
    var newDiagramFile = writeDiagram(filePath, diagramFile);

    callback(null, newDiagramFile);
  } catch (err) {
    callback(err);
  }
};

FileSystem.prototype.close = function(diagramFile, callback) {
  var self = this;

  this.showCloseDialog(diagramFile.name, function(result) {
    if (result === 2) {
      return callback(new Error(errorUtil.CANCELLATION_MESSAGE));
    }
    else if (result === 1) {
      // omitting the diagram to indicate that
      // stuff was not saved...
      return callback(null);
    }
    else {
      self.save(null, diagramFile, callback);
    }
  });
};

FileSystem.prototype.handleImportError = function(diagramFile, trace, callback) {

  this.showImportErrorDialog(diagramFile.name, trace, function(answer) {
    switch (answer) {
      case 1:
        browserOpen('https://forum.bpmn.io/');
        callback('forum');
        break;
      case 2:
        browserOpen('https://github.com/bpmn-io/bpmn-js/issues');
        callback('tracker');
        break;
      default:
        callback('close');
    }
  });
};

/**
 * Handle errors that the IPC has to deal with.
 *
 * @param  {String} event
 * @param  {Error} err
 */
FileSystem.prototype.handleError = function(event, err) {
  if (!errorUtil.isCancel(err)) {
    this.showGeneralErrorDialog();
  }
  this.browserWindow.webContents.send(event, errorUtil.normalizeError(err));
};

FileSystem.prototype.showOpenDialog = function(callback) {
  var config = this.config,
      defaultPath = config.get('defaultPath', app.getPath('userDesktop')),
      filenames;

  var opts = {
    title: 'Open diagram',
    defaultPath: defaultPath,
    properties: [ 'openFile' ],
    filters: SUPPORTED_EXT_FILTER,
    noLink: true
  };

  filenames = Dialog.showOpenDialog(this.browserWindow, opts);

  if (filenames) {
    config.set('defaultPath', path.dirname(filenames[0]));
  }

  callback(filenames);
};

FileSystem.prototype.showSaveAsDialog = function(diagramFile, callback) {
  var config = this.config,
      defaultPath = config.get('defaultPath', app.getPath('userDesktop'));

  var notation = diagramFile.notation,
      name = diagramFile.name,
      filters = [];

  if (notation === 'bpmn') {
    filters.push(SUPPORTED_EXT_BPMN);
  } else {
    filters.push(SUPPORTED_EXT_DMN);
  }

  var opts = {
    title: 'Save ' + name + ' as..',
    filters: filters,
    defaultPath: defaultPath,
    noLink: true
  };

  var filePath = Dialog.showSaveDialog(this.browserWindow, opts);

  if (filePath) {
    config.set('defaultPath', path.dirname(filePath));
  }

  callback(filePath);
};

FileSystem.prototype.showCloseDialog = function(name, callback) {
  var opts = {
    title: 'Close diagram',
    message: 'Save changes to ' + name + ' before closing?',
    type: 'question',
    buttons: [ 'Save', 'Don\'t Save', 'Cancel' ],
    noLink: true
  };

  callback(Dialog.showMessageBox(this.browserWindow, opts));
};

FileSystem.prototype.showImportErrorDialog = function(fileName, trace, callback) {
  var opts = {
    type: 'error',
    title: 'Importing Error',
    buttons: [ 'Close', 'Forum', 'Issue Tracker' ],
    message: 'Ooops, we could not display this diagram!',
    detail: [
      'Do you believe "' + fileName + '" is valid BPMN or DMN diagram?',
      'If so, please consult our forum or file an issue in our issue tracker.',
      '',
      trace
    ].join('\n'),
    noLink: true
  };

  callback(Dialog.showMessageBox(this.browserWindow, opts));
};

FileSystem.prototype.showUnrecognizedFileDialog = function(name) {
  Dialog.showMessageBox({
    type: 'warning',
    title: 'Unrecognized file format',
    buttons: [ 'Close' ],
    message: 'The file "' + name + '" is not a BPMN or DMN file.',
    noLink: true
  });
};

FileSystem.prototype.showNamespaceDialog = function(callback) {
  var opts = {
    type: 'warning',
    title: 'Deprecated <activiti> namespace detected',
    buttons: [ 'Yes', 'No' ],
    message: 'Would you like to convert your diagram to the <camunda> namespace?',
    detail: [
      'This will allow you to maintain execution related properties.',
      '',
      '<camunda> namespace support works from Camunda BPM version 7.4.0, 7.3.3, 7.2.6 onwards.'
    ].join('\n'),
    noLink: true
  };

  callback(Dialog.showMessageBox(this.browserWindow, opts));
};

FileSystem.prototype.showGeneralErrorDialog = function() {
  Dialog.showErrorBox('Error', 'There was an internal error.' + '\n' + 'Please try again.');
};

FileSystem.prototype.sanitizeFilename = function(filename, notation) {
  var extension = path.extname(filename);

  if (extension === '') {
    return filename + '.' + notation;
  }

  return filename;
};

module.exports = FileSystem;

function readDiagram(diagramPath) {

  var contents = fs.readFileSync(diagramPath, FILE_ENCODING);

  // trim leading and trailing whitespace
  // this fixes obscure import errors for non-strict
  // xml exports
  contents = contents.replace(/(^\s*|\s*$)/g, '');

  return createDiagramFile(diagramPath, contents);
}

module.exports.readDiagram = readDiagram;

var assign = require('lodash/object/assign');

function writeDiagram(diagramPath, diagramFile) {
  fs.writeFileSync(diagramPath, diagramFile.contents, FILE_ENCODING);

  return assign({}, diagramFile, {
    name: path.basename(diagramPath),
    path: diagramPath
  });
}

module.exports.writeDiagram = writeDiagram;<|endoftext|>


<commit_before>// DEBUG FUNCTIONS
function wicketAjaxDebugEnabled() {
    if (typeof(wicketAjaxDebugEnable)=="undefined") {
        return false;
    } else {
        return wicketAjaxDebugEnable==true;
    }
}

// MISC FUNCTIONS
function wicketKeyCode(event) {
    if (typeof(event.keyCode)=="undefined") {
        return event.which;
    } else {
        return event.keyCode;
    }
}

function wicketGet(id) {
    return document.getElementById(id);
}

function wicketShow(id) {
    wicketGet(id).style.display = "inline";
}
function wicketHide(id) {
    wicketGet(id).style.display = "none";
}

// AJAX FUNCTIONS
function wicketAjaxGetTransport() {
    var transport = null;
    if (window.XMLHttpRequest) {
        transport = new XMLHttpRequest();
    } else {
        if (window.ActiveXObject) {
            transport = new ActiveXObject("Microsoft.XMLHTTP");
        }
    }

    if (transport==null&&wicketAjaxDebugEnabled()) {
        var log=WicketAjaxDebug.logError;
        log("Could not locate ajax transport. Your browser does not support the required XMLHttpRequest object or wicket could not gain access to it.");
    }
    return transport;
}

function wicketAjaxGet(url, successHandler, failureHandler) {
    if (wicketAjaxDebugEnabled()) {
        var log=WicketAjaxDebug.logInfo;
        log("");
        log("initiating ajax GET request with...");
        log("url: "+url);
        log("successHandler:"+successHandler);
        log("failureHandler:"+failureHandler);
    }

    var transport = wicketAjaxGetTransport();
    if (transport == null) {
        return false;
    }
    transport.onreadystatechange = function () {
        wicketAjaxOnStateChange(transport, successHandler, failureHandler);
    };
    transport.open("GET", url + "&random=" + Math.random(), true);
    transport.send(null);
    return true;
}
function wicketAjaxPost(url, body, successHandler, failureHandler) {
    if (wicketAjaxDebugEnabled()) {
        var log=WicketAjaxDebug.logInfo;
        log("");
        log("initiating ajax POST request with...");
        log("url: "+url);
        log("body: "+body);
        log("successHandler:"+successHandler);
        log("failureHandler:"+failureHandler);
    }

    var transport = wicketAjaxGetTransport();
    if (transport == null) {
        return false;
    }
    transport.onreadystatechange = function () {
        wicketAjaxOnStateChange(transport, successHandler, failureHandler);
    };
    transport.open("POST", url + "&random=" + Math.random(), true);
    transport.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    transport.send(body);
    return true;
}
function wicketSubmitForm(form, url, submitButton, successHandler, failureHandler) {
    var body = wicketSerializeForm(form);
    if (submitButton != null) {
        body += wicketEncode(submitButton) + "=1";
    }
    return wicketAjaxPost(url, body, successHandler, failureHandler);
}
function wicketSubmitFormById(formId, url, submitButton, successHandler, failureHandler) {
    var form = document.getElementById(formId);
    return wicketSubmitForm(form, url, submitButton, successHandler, failureHandler);
}
function wicketAjaxOnStateChange(transport, successHandler, failureHandler) {
    if (transport.readyState == 4) {
        if (transport.status == 200) {
            if (wicketAjaxDebugEnabled()) {
                var log=WicketAjaxDebug.logInfo;
                log("received ajax response. "+transport.responseText.length+" characters, envelope following...");
                log("");
                log(transport.responseText);
            }
            wicketAjaxProcess(transport.responseXML, successHandler, failureHandler);
        } else {
            if (wicketAjaxDebugEnabled()) {
                var log=WicketAjaxDebug.logError;
                log("received ajax response with code: "+transport.status);
            }
			wicketAjaxCallFailureHandler(failureHandler);
		}
    }
}
function wicketAjaxProcess(envelope, successHandler, failureHandler) {
	try {
	    var root = envelope.getElementsByTagName("ajax-response");
	    root = root[0];
	    if (root == null || root.tagName != "ajax-response") {
	        if (wicketAjaxDebugEnabled()) {
	            var log=WicketAjaxDebug.logError;
	            log("malformed response envelope: could not find root <ajax-response> element");
	        }
	       	wicketAjaxCallFailureHandler(failureHandler);
	    }
	    for (var i = 0; i < root.childNodes.length; i++) {
	        var node = root.childNodes[i];
	        if (node.tagName == "component") {
	            wicketAjaxProcessComponent(node);
	        } else if (node.tagName == "evaluate") {
	                wicketAjaxProcessEvaluation(node);
	        }
	    }

	    if (wicketAjaxDebugEnabled()) {
	        var log=WicketAjaxDebug.logInfo;
	        log("response envelope successfully processed");
	    }

	    if (successHandler!=undefined && successHandler != null) {
	        if (wicketAjaxDebugEnabled()) {
	            var log=WicketAjaxDebug.logInfo;
	            log("invoking success handler...");
	        }
	        successHandler();
	    }

	    if (wicketAjaxDebugEnabled()) {
	        var log=WicketAjaxDebug.logInfo;
	        log("request successfully processed");
	    }
	} catch (e) {
		if (wicketAjaxDebugEnabled()) {
			var log=WicketAjaxDebug.logError;
			log("error while processing response: "+e);
		}
		wicketAjaxCallFailureHandler(failureHandler);
	}

}

function wicketAjaxCallFailureHandler(failureHandler) {
	if (failureHandler!=undefined && failureHandler!=null) {
		if (wicketAjaxDebugEnabled()) {
			var log=WicketAjaxDebug.logInfo;
			log("invoking failure handler...");
		}
		failureHandler();
	}

	if (wicketGlobalAjaxErrorHandler!=undefined&&wicketGlobalAjaxErrorHandler!=null) {
		if (wicketAjaxDebugEnabled()) {
			var log=WicketAjaxDebug.logInfo;
			log("invoking wicketGlobalAjaxErrorHandler failure handler...");
		}
		wicketGlobalAjaxErrorHandler();
	}
}

function wicketAjaxProcessComponent(node) {
    var compId = node.getAttribute("id");

    var text="";
    if (node.hasChildNodes()) {
       text = node.firstChild.nodeValue;
    }

    var encoding = node.getAttribute("encoding");
    if (encoding != null&&encoding!="") {
        text = wicketDecode(encoding, text);
    }
    var element=document.getElementById(compId);
    if (element.outerHTML) {
        element.outerHTML = text;
    } else {
        var range = element.ownerDocument.createRange();
        range.selectNode(element);
        element.parentNode.replaceChild(
        range.createContextualFragment(text), element);
    }

}
function wicketAjaxProcessEvaluation(node) {
    var text = node.firstChild.nodeValue;
    var encoding = node.getAttribute("encoding");
    if (encoding != null) {
        text = wicketDecode(encoding, text);
    }
    eval(text);
}
function wicketDecode(encoding, text) {
    if (encoding == "wicket1") {
        return wicketDecode1(text);
    }
}
function wicketDecode1(text) {
    return wicketReplaceAll(text, "]^", "]");
}
function wicketReplaceAll(str, from, to) {
    var idx = str.indexOf(from);
    while (idx > -1) {
        str = str.replace(from, to);
        idx = str.indexOf(from);
    }
    return str;
}

//FORM SERIALIZATION FUNCTIONS
function wicketEncode(text) {
    if (encodeURIComponent) {
        return encodeURIComponent(text);
    } else {
        return escape(text);
    }
}
function wicketSerializeSelect(select) {
    var result = "";
    for (var i = 0; i < select.options.length; ++i) {
        var option = select.options[i];
        if (option.selected) {
            result += wicketEncode(select.name) + "=" + wicketEncode(option.value) + "&";
        }
    }
    return result;
}

// this function intentionally ignores image and submit inputs
function wicketSerializeInput(input) {
    var type = input.type.toLowerCase();
    if ((type == "checkbox" || type == "radio") && input.checked) {
        return wicketEncode(input.name) + "=" + wicketEncode(input.value) + "&";
    } else {
        if (type == "text" || type == "password" || type == "hidden" || type == "textarea") {
            return wicketEncode(input.name) + "=" + wicketEncode(input.value) + "&";
        } else {
            return "";
        }
    }
}

// returns url/post-body fragment representing element (e)
function wicketSerialize(e) {
    var tag = e.tagName.toLowerCase();
    if (tag == "select") {
        return wicketSerializeSelect(e);
    } else {
        if (tag == "input" || tag == "textarea") {
            return wicketSerializeInput(e);
        }
    }
}
function wicketSerializeForm(form) {
    var result = "";
    for (var i = 0; i < form.elements.length; ++i) {
        var e = form.elements[i];
        if (!e.disabled) {
            result += wicketSerialize(e);
        }
    }
    return result;
}

// THROTTLE FUNCTIONS
function WicketThrottlerEntry(func) {
	this.func=func;
	this.timestamp=new Date().getTime();
}

WicketThrottlerEntry.prototype.getTimestamp=function() {
	return this.timestamp;
}

WicketThrottlerEntry.prototype.getFunc=function() {
	return this.func;
}

WicketThrottlerEntry.prototype.setFunc=function(func) {
	this.func=func;
}

function WicketThrottler() {
	this.entries=new Array();
}

WicketThrottler.prototype.throttle=function(id, millis, func) {
	var entry=this.entries[id];
	var me=this;
	if (entry==undefined) {
		entry=new WicketThrottlerEntry(func);
		this.entries[id]=entry;
		window.setTimeout(function() { me.execute(id); }, millis);
	} else {
		entry.setFunc(func);
	}
}

WicketThrottler.prototype.execute=function(id) {
	var entry=this.entries[id];
	if (entry!=undefined) {
		var func=entry.getFunc();
		var tmp=func();
	}

	this.entries[id]=undefined;
}

var wicketThrottler=new WicketThrottler();
<commit_msg>uhm...screw the edge case, it breaks more then it fixes<commit_after>// DEBUG FUNCTIONS
function wicketAjaxDebugEnabled() {
    if (typeof(wicketAjaxDebugEnable)=="undefined") {
        return false;
    } else {
        return wicketAjaxDebugEnable==true;
    }
}

// MISC FUNCTIONS
function wicketKeyCode(event) {
    if (typeof(event.keyCode)=="undefined") {
        return event.which;
    } else {
        return event.keyCode;
    }
}

function wicketGet(id) {
    return document.getElementById(id);
}

function wicketShow(id) {
    wicketGet(id).style.display = "";
}
function wicketHide(id) {
    wicketGet(id).style.display = "none";
}

// AJAX FUNCTIONS
function wicketAjaxGetTransport() {
    var transport = null;
    if (window.XMLHttpRequest) {
        transport = new XMLHttpRequest();
    } else {
        if (window.ActiveXObject) {
            transport = new ActiveXObject("Microsoft.XMLHTTP");
        }
    }

    if (transport==null&&wicketAjaxDebugEnabled()) {
        var log=WicketAjaxDebug.logError;
        log("Could not locate ajax transport. Your browser does not support the required XMLHttpRequest object or wicket could not gain access to it.");
    }
    return transport;
}

function wicketAjaxGet(url, successHandler, failureHandler) {
    if (wicketAjaxDebugEnabled()) {
        var log=WicketAjaxDebug.logInfo;
        log("");
        log("initiating ajax GET request with...");
        log("url: "+url);
        log("successHandler:"+successHandler);
        log("failureHandler:"+failureHandler);
    }

    var transport = wicketAjaxGetTransport();
    if (transport == null) {
        return false;
    }
    transport.onreadystatechange = function () {
        wicketAjaxOnStateChange(transport, successHandler, failureHandler);
    };
    transport.open("GET", url + "&random=" + Math.random(), true);
    transport.send(null);
    return true;
}
function wicketAjaxPost(url, body, successHandler, failureHandler) {
    if (wicketAjaxDebugEnabled()) {
        var log=WicketAjaxDebug.logInfo;
        log("");
        log("initiating ajax POST request with...");
        log("url: "+url);
        log("body: "+body);
        log("successHandler:"+successHandler);
        log("failureHandler:"+failureHandler);
    }

    var transport = wicketAjaxGetTransport();
    if (transport == null) {
        return false;
    }
    transport.onreadystatechange = function () {
        wicketAjaxOnStateChange(transport, successHandler, failureHandler);
    };
    transport.open("POST", url + "&random=" + Math.random(), true);
    transport.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    transport.send(body);
    return true;
}
function wicketSubmitForm(form, url, submitButton, successHandler, failureHandler) {
    var body = wicketSerializeForm(form);
    if (submitButton != null) {
        body += wicketEncode(submitButton) + "=1";
    }
    return wicketAjaxPost(url, body, successHandler, failureHandler);
}
function wicketSubmitFormById(formId, url, submitButton, successHandler, failureHandler) {
    var form = document.getElementById(formId);
    return wicketSubmitForm(form, url, submitButton, successHandler, failureHandler);
}
function wicketAjaxOnStateChange(transport, successHandler, failureHandler) {
    if (transport.readyState == 4) {
        if (transport.status == 200) {
            if (wicketAjaxDebugEnabled()) {
                var log=WicketAjaxDebug.logInfo;
                log("received ajax response. "+transport.responseText.length+" characters, envelope following...");
                log("");
                log(transport.responseText);
            }
            wicketAjaxProcess(transport.responseXML, successHandler, failureHandler);
        } else {
            if (wicketAjaxDebugEnabled()) {
                var log=WicketAjaxDebug.logError;
                log("received ajax response with code: "+transport.status);
            }
			wicketAjaxCallFailureHandler(failureHandler);
		}
    }
}
function wicketAjaxProcess(envelope, successHandler, failureHandler) {
	try {
	    var root = envelope.getElementsByTagName("ajax-response");
	    root = root[0];
	    if (root == null || root.tagName != "ajax-response") {
	        if (wicketAjaxDebugEnabled()) {
	            var log=WicketAjaxDebug.logError;
	            log("malformed response envelope: could not find root <ajax-response> element");
	        }
	       	wicketAjaxCallFailureHandler(failureHandler);
	    }
	    for (var i = 0; i < root.childNodes.length; i++) {
	        var node = root.childNodes[i];
	        if (node.tagName == "component") {
	            wicketAjaxProcessComponent(node);
	        } else if (node.tagName == "evaluate") {
	                wicketAjaxProcessEvaluation(node);
	        }
	    }

	    if (wicketAjaxDebugEnabled()) {
	        var log=WicketAjaxDebug.logInfo;
	        log("response envelope successfully processed");
	    }

	    if (successHandler!=undefined && successHandler != null) {
	        if (wicketAjaxDebugEnabled()) {
	            var log=WicketAjaxDebug.logInfo;
	            log("invoking success handler...");
	        }
	        successHandler();
	    }

	    if (wicketAjaxDebugEnabled()) {
	        var log=WicketAjaxDebug.logInfo;
	        log("request successfully processed");
	    }
	} catch (e) {
		if (wicketAjaxDebugEnabled()) {
			var log=WicketAjaxDebug.logError;
			log("error while processing response: "+e);
		}
		wicketAjaxCallFailureHandler(failureHandler);
	}

}

function wicketAjaxCallFailureHandler(failureHandler) {
	if (failureHandler!=undefined && failureHandler!=null) {
		if (wicketAjaxDebugEnabled()) {
			var log=WicketAjaxDebug.logInfo;
			log("invoking failure handler...");
		}
		failureHandler();
	}

	if (wicketGlobalAjaxErrorHandler!=undefined&&wicketGlobalAjaxErrorHandler!=null) {
		if (wicketAjaxDebugEnabled()) {
			var log=WicketAjaxDebug.logInfo;
			log("invoking wicketGlobalAjaxErrorHandler failure handler...");
		}
		wicketGlobalAjaxErrorHandler();
	}
}

function wicketAjaxProcessComponent(node) {
    var compId = node.getAttribute("id");

    var text="";
    if (node.hasChildNodes()) {
       text = node.firstChild.nodeValue;
    }

    var encoding = node.getAttribute("encoding");
    if (encoding != null&&encoding!="") {
        text = wicketDecode(encoding, text);
    }
    var element=document.getElementById(compId);
    if (element.outerHTML) {
        element.outerHTML = text;
    } else {
        var range = element.ownerDocument.createRange();
        range.selectNode(element);
        element.parentNode.replaceChild(
        range.createContextualFragment(text), element);
    }

}
function wicketAjaxProcessEvaluation(node) {
    var text = node.firstChild.nodeValue;
    var encoding = node.getAttribute("encoding");
    if (encoding != null) {
        text = wicketDecode(encoding, text);
    }
    eval(text);
}
function wicketDecode(encoding, text) {
    if (encoding == "wicket1") {
        return wicketDecode1(text);
    }
}
function wicketDecode1(text) {
    return wicketReplaceAll(text, "]^", "]");
}
function wicketReplaceAll(str, from, to) {
    var idx = str.indexOf(from);
    while (idx > -1) {
        str = str.replace(from, to);
        idx = str.indexOf(from);
    }
    return str;
}

//FORM SERIALIZATION FUNCTIONS
function wicketEncode(text) {
    if (encodeURIComponent) {
        return encodeURIComponent(text);
    } else {
        return escape(text);
    }
}
function wicketSerializeSelect(select) {
    var result = "";
    for (var i = 0; i < select.options.length; ++i) {
        var option = select.options[i];
        if (option.selected) {
            result += wicketEncode(select.name) + "=" + wicketEncode(option.value) + "&";
        }
    }
    return result;
}

// this function intentionally ignores image and submit inputs
function wicketSerializeInput(input) {
    var type = input.type.toLowerCase();
    if ((type == "checkbox" || type == "radio") && input.checked) {
        return wicketEncode(input.name) + "=" + wicketEncode(input.value) + "&";
    } else {
        if (type == "text" || type == "password" || type == "hidden" || type == "textarea") {
            return wicketEncode(input.name) + "=" + wicketEncode(input.value) + "&";
        } else {
            return "";
        }
    }
}

// returns url/post-body fragment representing element (e)
function wicketSerialize(e) {
    var tag = e.tagName.toLowerCase();
    if (tag == "select") {
        return wicketSerializeSelect(e);
    } else {
        if (tag == "input" || tag == "textarea") {
            return wicketSerializeInput(e);
        }
    }
}
function wicketSerializeForm(form) {
    var result = "";
    for (var i = 0; i < form.elements.length; ++i) {
        var e = form.elements[i];
        if (!e.disabled) {
            result += wicketSerialize(e);
        }
    }
    return result;
}

// THROTTLE FUNCTIONS
function WicketThrottlerEntry(func) {
	this.func=func;
	this.timestamp=new Date().getTime();
}

WicketThrottlerEntry.prototype.getTimestamp=function() {
	return this.timestamp;
}

WicketThrottlerEntry.prototype.getFunc=function() {
	return this.func;
}

WicketThrottlerEntry.prototype.setFunc=function(func) {
	this.func=func;
}

function WicketThrottler() {
	this.entries=new Array();
}

WicketThrottler.prototype.throttle=function(id, millis, func) {
	var entry=this.entries[id];
	var me=this;
	if (entry==undefined) {
		entry=new WicketThrottlerEntry(func);
		this.entries[id]=entry;
		window.setTimeout(function() { me.execute(id); }, millis);
	} else {
		entry.setFunc(func);
	}
}

WicketThrottler.prototype.execute=function(id) {
	var entry=this.entries[id];
	if (entry!=undefined) {
		var func=entry.getFunc();
		var tmp=func();
	}

	this.entries[id]=undefined;
}

var wicketThrottler=new WicketThrottler();
<|endoftext|>


<commit_before>import { StyleSheet } from 'react-native'

export default styles = StyleSheet.create({
  container: {
    flex: 1
  },
  background: {
    flex: 1,
    backgroundColor: '#008530'
  },
  logoContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  },
  loginForm: {
    flex: 2
  },
  appName: {
    color: 'white',
    fontSize: 60,
    fontWeight: 'bold'
  },
  appDescription: {
    color: 'white'
  },
  textInput: {
    backgroundColor: 'white',
    borderColor: 'red',
    marginTop: 10,
    marginLeft: 40,
    marginRight: 40,
    borderRadius: 30,
    textAlign: 'center',
    height: 52
  },
  button: {
    backgroundColor: 'white',
    marginTop: 20,
    height: 52,
    marginLeft: 40,
    marginRight: 40,
    borderRadius: 26,
    overflow: 'hidden',
    justifyContent: 'center',
    alignItems: 'center'
  },
  buttonText: {
    backgroundColor: 'red',
    textAlign: 'center',
    color: '#008530',
    fontWeight: 'bold',
    overflow: 'hidden'
  },
  textSignIn: {
    color: 'white',
    textAlign: 'center',
    marginTop: 10
  },
  iconTab: {
    width: 48,
    height: 48,
    resizeMode: 'stretch'
  }
})<commit_msg>remove background of the text of the button login<commit_after>import { StyleSheet } from 'react-native'

export default styles = StyleSheet.create({
  container: {
    flex: 1
  },
  background: {
    flex: 1,
    backgroundColor: '#008530'
  },
  logoContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  },
  loginForm: {
    flex: 2
  },
  appName: {
    color: 'white',
    fontSize: 60,
    fontWeight: 'bold'
  },
  appDescription: {
    color: 'white'
  },
  textInput: {
    backgroundColor: 'white',
    borderColor: 'red',
    marginTop: 10,
    marginLeft: 40,
    marginRight: 40,
    borderRadius: 30,
    textAlign: 'center',
    height: 52
  },
  button: {
    backgroundColor: 'white',
    marginTop: 20,
    height: 52,
    marginLeft: 40,
    marginRight: 40,
    borderRadius: 26,
    overflow: 'hidden',
    justifyContent: 'center',
    alignItems: 'center'
  },
  buttonText: {
    textAlign: 'center',
    color: '#008530',
    fontWeight: 'bold',
    overflow: 'hidden'
  },
  textSignIn: {
    color: 'white',
    textAlign: 'center',
    marginTop: 10
  },
  iconTab: {
    width: 48,
    height: 48,
    resizeMode: 'stretch'
  }
})<|endoftext|>


<commit_before>const express = require('express')
const app = express()
console.log(express);

app.set('port', process.env.PORT || 8080);

app.get('/', (req, res) => {
    res.send('Hello World!')
})

app.get('/time', (req, res)=>{
  let isodate = new Date().toISOString()
  res.send(isodate)
})

app.listen(app.get('port'));
<commit_msg>removed console.log of express<commit_after>const express = require('express')
const app = express()
// console.log(express);

app.set('port', process.env.PORT || 8080);

app.get('/', (req, res) => {
    res.send('Hello World!')
})

app.get('/time', (req, res)=>{
  let isodate = new Date().toISOString()
  res.send(isodate)
})

app.listen(app.get('port'));
<|endoftext|>


<commit_before>'use strict';

var path = require('path');

var autoprefixer = require('autoprefixer'),
    csswring = require('csswring'),
    mqpacker = require('css-mqpacker');

module.exports = [

    'build stylesheets',

    function() {
        return this.gulp

            .src(path.join(this.paths.css, '*.styl'))

            .pipe(this.plugins.sourcemaps.init())

            .pipe(this.plugins.stylus({
                paths: [
                    path.join(this.paths.css, 'imports'),
                    path.join(this.paths.assets, 'img'),
                    this.paths.node
                ],
                'include css': true,
                url: {
                    name: 'inline-url',
                    limit: false
                }
            }).on('error', this.log.error))

            .pipe(this.plugins.postcss([
                autoprefixer({
                    browsers: [
                        'last 2 versions',
                        '> 2%',
                        'Opera 11.1',
                        'Firefox ESR'
                    ]
                }),
                mqpacker
            ].concat(this.env === 'production' ?
                [csswring({
                    preserveHacks: true
                })] : []
            )))

            .pipe(this.plugins.sourcemaps.write('.', {
                includeContent: true,
                sourceRoot: '.'
            }))

            .pipe(this.gulp.dest(this.paths.cssDest))

            .on('error', this.log.error);

    }

];
<commit_msg>support more browsers with autoprefixer<commit_after>'use strict';

var path = require('path');

var autoprefixer = require('autoprefixer'),
    csswring = require('csswring'),
    mqpacker = require('css-mqpacker');

module.exports = [

    'build stylesheets',

    function() {
        return this.gulp

            .src(path.join(this.paths.css, '*.styl'))

            .pipe(this.plugins.sourcemaps.init())

            .pipe(this.plugins.stylus({
                paths: [
                    path.join(this.paths.css, 'imports'),
                    path.join(this.paths.assets, 'img'),
                    this.paths.node
                ],
                'include css': true,
                url: {
                    name: 'inline-url',
                    limit: false
                }
            }).on('error', this.log.error))

            .pipe(this.plugins.postcss([
                autoprefixer({
                    browsers: ['> 0.01%']
                }),
                mqpacker
            ].concat(this.env === 'production' ?
                [csswring({
                    preserveHacks: true
                })] : []
            )))

            .pipe(this.plugins.sourcemaps.write('.', {
                includeContent: true,
                sourceRoot: '.'
            }))

            .pipe(this.gulp.dest(this.paths.cssDest))

            .on('error', this.log.error);

    }

];
<|endoftext|>


<commit_before>/**
 * @jsx React.DOM
 */
'use strict';

var assert = require('assert');
var React = require('react');
var merge = require('react/lib/merge');
var cloneWithProps = require('react/lib/cloneWithProps');
var TestUtils = require('react/lib/ReactTestUtils');
var Link = require('../Link');
var route = require('../route');
var Routes = route.Routes;
var Route = route.Route;

function makeMatchTrace(routes, ref) {
  return route.getTraceByName(routes, ref).map((route) => {
    return {route, match: {}};
  });
}

describe('Link', function() {

  var App = React.createClass({

    childContextTypes: {
      routes: React.PropTypes.object,
      match: React.PropTypes.object
    },

    getChildContext: function() {
      return {
        routes: this.props.routes,
        match: this.props.match
      };
    },

    render: function() {
      return cloneWithProps(this.props.children, {ref: 'link'});
    }
  });

  var users = (
    <Routes path="/users" name="users">
      <Route path=":user" name="user" />
      <Route path=":user/albums" name="user-albums" />
    </Routes>
  );

  var routes = (
    <Route>
      <Route path="/" name="main" />
      <Route path="/about" name="about" />
      {users}
    </Route>
  );

  function renderLink(link, match) {
    match = match || {route: routes, trace: [{route: routes, match: {}}]};
    var app = App({routes, match}, link);
    app = TestUtils.renderIntoDocument(app);
    return app.refs.link;
  }

  describe('markup generation', function() {

    function itGeneratesHrefTo(routeName, href, props, match) {
      it(`generate href ${href} by referring to ${routeName}`, function() {
        props = merge(props, {to: routeName});
        var link = renderLink(Link(props), match);
        assert.equal(link.getDOMNode().attributes.href.value, href);
      });
    }

    it('generates markup with href passed as a prop', function() {
      var link = renderLink(<Link href="/href">link</Link>);
      assert.equal(link.getDOMNode().attributes.href.value, '/href');
    });

    describe('generating href by referring to an absolute route name', function() {
      itGeneratesHrefTo('/main', '/');
      itGeneratesHrefTo('/about', '/about');
      itGeneratesHrefTo('/users', '/users');
      itGeneratesHrefTo('/users/user', '/users/me', {user: 'me'});
      itGeneratesHrefTo('/users/user-albums', '/users/me/albums', {user: 'me'});
    });

    describe('generating href by referring to a relative route name', function() {
      itGeneratesHrefTo('main', '/', {});
      itGeneratesHrefTo('about', '/about', {});
      itGeneratesHrefTo('users', '/users', {});

      var matchUsers = {
        route: users,
        trace: makeMatchTrace(routes, 'users')
      };
      itGeneratesHrefTo('users/user', '/users/me', {user: 'me'}, matchUsers);
      itGeneratesHrefTo('users/user-albums', '/users/me/albums', {user: 'me'}, matchUsers);

      var matchUser = {
        route: users.children[0],
        trace: makeMatchTrace(routes, 'users/user')
      };

      itGeneratesHrefTo('users/user', '/users/me', {user: 'me'}, matchUser);
      itGeneratesHrefTo('users/user-albums', '/users/me/albums', {user: 'me'}, matchUser);
    });

  });

  describe('onClick behaviour', function() {

  });

});
<commit_msg>Link: tests on onClick and unresolved route ref<commit_after>/**
 * @jsx React.DOM
 */
'use strict';

var assert = require('assert');
var sinon = require('sinon');
var React = require('react');
var merge = require('react/lib/merge');
var cloneWithProps = require('react/lib/cloneWithProps');
var TestUtils = require('react/lib/ReactTestUtils');
var Link = require('../Link');
var route = require('../route');
var Routes = route.Routes;
var Route = route.Route;

function makeMatchTrace(routes, ref) {
  return route.getTraceByName(routes, ref).map((route) => {
    return {route, match: {}};
  });
}

describe('Link', function() {

  var App = React.createClass({

    childContextTypes: {
      routes: React.PropTypes.object,
      match: React.PropTypes.object,
      routing: React.PropTypes.object
    },

    getChildContext: function() {
      return {
        routes: this.props.routes,
        match: this.props.match,
        routing: this.props.routing
      };
    },

    render: function() {
      return cloneWithProps(this.props.children, {ref: 'link'});
    }
  });

  var users = (
    <Routes path="/users" name="users">
      <Route path=":user" name="user" />
      <Route path=":user/albums" name="user-albums" />
    </Routes>
  );

  var routes = (
    <Route>
      <Route path="/" name="main" />
      <Route path="/about" name="about" />
      {users}
    </Route>
  );

  var routing;

  function renderLink(link, match) {
    routing = {navigate: sinon.spy()};
    match = match || {route: routes, trace: [{route: routes, match: {}}]};
    var app = App({routes, match, routing}, link);
    app = TestUtils.renderIntoDocument(app);
    return app.refs.link;
  }

  describe('markup generation', function() {

    function itGeneratesHrefTo(routeName, href, props, match) {
      it(`generate href ${href} by referring to ${routeName}`, function() {
        props = merge(props, {to: routeName});
        var link = renderLink(Link(props), match);
        assert.equal(link.getDOMNode().attributes.href.value, href);
      });
    }

    it('generates markup with href passed as a prop', function() {
      var link = renderLink(<Link href="/href">link</Link>);
      assert.equal(link.getDOMNode().attributes.href.value, '/href');
    });

    describe('generating href by referring to an absolute route name', function() {
      itGeneratesHrefTo('/main', '/');
      itGeneratesHrefTo('/about', '/about');
      itGeneratesHrefTo('/users', '/users');
      itGeneratesHrefTo('/users/user', '/users/me', {user: 'me'});
      itGeneratesHrefTo('/users/user-albums', '/users/me/albums', {user: 'me'});
    });

    describe('generating href by referring to a relative route name', function() {
      itGeneratesHrefTo('main', '/', {});
      itGeneratesHrefTo('about', '/about', {});
      itGeneratesHrefTo('users', '/users', {});

      var matchUsers = {
        route: users,
        trace: makeMatchTrace(routes, 'users')
      };
      itGeneratesHrefTo('users/user', '/users/me', {user: 'me'}, matchUsers);
      itGeneratesHrefTo('users/user-albums', '/users/me/albums', {user: 'me'}, matchUsers);

      var matchUser = {
        route: users.children[0],
        trace: makeMatchTrace(routes, 'users/user')
      };

      itGeneratesHrefTo('users/user', '/users/me', {user: 'me'}, matchUser);
      itGeneratesHrefTo('users/user-albums', '/users/me/albums', {user: 'me'}, matchUser);
    });

    it('throws meaningful error if it cannot resolve route reference', function() {
      assert.throws(
        () => renderLink(<Link to="/x">link</Link>),
        Error,
        'Error: Invariant Violation: cannot resolve "/x" route reference'
      );
    });

  });

  describe('onClick behaviour', function() {

    it('navigates using routing', function() {
      var link = renderLink(<Link to="/users/user" user="me" />);
      var e = {preventDefault: sinon.spy()};
      TestUtils.Simulate.click(link.getDOMNode(), e);
      sinon.assert.calledOnce(e.preventDefault);
      sinon.assert.calledOnce(routing.navigate);
      sinon.assert.calledWith(routing.navigate, '/users/me');
    });

  });

});
<|endoftext|>


<commit_before>/* See license.txt for terms of usage */

// ************************************************************************************************
// Constants

const Cc = Components.classes;
const Ci = Components.interfaces;
const Cr = Components.results;
const Cu = Components.utils;

var EXPORTED_SYMBOLS = ["traceConsoleService"];

// ************************************************************************************************
// Service implementation

/**
 * This implementation serves as a proxy to the FBTrace extension. All logs are forwarded
 * to the FBTrace service.
 */
try
{
    Cu["import"]("resource://fbtrace/firebug-trace-service.js");
}
catch (err)
{
    var traceConsoleService =
    {
        getTracer: function(prefDomain)
        {
            var TraceAPI = ["dump", "sysout", "setScope", "matchesNode", "time", "timeEnd"];
            var TraceObj = {};
            for (var i=0; i<TraceAPI.length; i++)
                TraceObj[TraceAPI[i]] = function() {};

            TraceObj.sysout = function(msg)
            {
                try
                {
                    Cu.import("resource://fbtrace/firebug-trace-service.js", scope);
                    var FBTrace = scope.traceConsoleService.getTracer("extensions.firebug");
                    FBTrace.sysout.apply(FBTrace, arguments);
                }
                catch (err)
                {
                    //Cu.reportError(getStackDump());
                    Cu.reportError(msg);
                }
            }

            return TraceObj;
        }
    };
}

// ********************************************************************************************* //

function getStackDump()
{
    var lines = [];
    for (var frame = Components.stack; frame; frame = frame.caller)
        lines.push(frame.filename + " (" + frame.lineNumber + ")");

    return lines.join("\n");
};
<commit_msg>Fix tracing<commit_after>/* See license.txt for terms of usage */

// ************************************************************************************************
// Constants

const Cc = Components.classes;
const Ci = Components.interfaces;
const Cr = Components.results;
const Cu = Components.utils;

var EXPORTED_SYMBOLS = ["traceConsoleService"];

// ************************************************************************************************
// Service implementation

/**
 * This implementation serves as a proxy to the FBTrace extension. All logs are forwarded
 * to the FBTrace service.
 */
try
{
    Cu["import"]("resource://fbtrace/firebug-trace-service.js");
}
catch (err)
{
    var traceConsoleService =
    {
        getTracer: function(prefDomain)
        {
            var TraceAPI = ["dump", "sysout", "setScope", "matchesNode", "time", "timeEnd"];
            var TraceObj = {};
            for (var i=0; i<TraceAPI.length; i++)
                TraceObj[TraceAPI[i]] = function() {};

            var optionsSet = false;

            TraceObj.sysout = function(msg)
            {
                try
                {
                    var scope = {};
                    Cu.import("resource://fbtrace/firebug-trace-service.js", scope);
                    var FBTrace = scope.traceConsoleService.getTracer("extensions.firebug");
                    FBTrace.sysout.apply(FBTrace, arguments);

                    // Copy all options from real FBTrace object into the one that has
                    // been already created.
                    if (!optionsSet)
                    {
                        for (var p in FBTrace)
                            TraceObj[p] = FBTrace[p];
                        optionsSet = true;
                    }
                }
                catch (err)
                {
                    //Cu.reportError(getStackDump());
                    Cu.reportError(msg);
                }
            }

            return TraceObj;
        }
    };
}

// ********************************************************************************************* //

function getStackDump()
{
    var lines = [];
    for (var frame = Components.stack; frame; frame = frame.caller)
        lines.push(frame.filename + " (" + frame.lineNumber + ")");

    return lines.join("\n");
};
<|endoftext|>