<commit_before>/*
 *
 * Copyright (c) 2015 EBo (https://github.com/E-Bo)
 *
 * Version 0.1
 *
 * Work with jQuery
 *
 */

var fullScreenHelper = function(options){
    options = options || {};
    window.fullScreenHelperCounter = window.fullScreenHelperCounter? window.fullScreenHelperCounter + 1 : 1;
    window.UserAgent = window.UserAgent || this.clients[this.getUserAgent()];
    this.fullScreenHelperID = window.fullScreenHelperCounter;
    this.RequestFullCallBack = options.RequestFullCallBack || null;
    this.CancelFullCallBack = options.CancelFullCallBack || null;
    this.targetElement = options.target || document.getElementsByTagName('html')[0];
    window.fullScreenChangeEvents = window.fullScreenChangeEvents || {};
    window.fullScreenChangeEvents['fullScreenChangeEvent_' + this.fullScreenHelperID] = $.proxy(function(){
        if(document[window.UserAgent.stateName]){
            if(this.RequestFullCallBack && typeof(this.RequestFullCallBack) == 'function'){
                this.RequestFullCallBack();
            }
        }else{
            if(this.CancelFullCallBack && typeof(this.CancelFullCallBack) == 'function'){
                this.CancelFullCallBack();
            }
        }
    },this);
    this.bindEvent();
}

fullScreenHelper.prototype = {
    clients: {
        'default' : {
            eventName: 'fullscreenchange',
            stateName: 'fullScreen',
            requestFullScreen: 'requestFullScreen',
            cancelFullScreen: 'exitFullscreen'
        },
        'firefox' : {
            eventName: 'mozfullscreenchange',
            stateName: 'mozFullScreen',
            requestFullScreen: 'mozRequestFullScreen',
            cancelFullScreen: 'webkitCancelFullScreen'
        },
        'webkit' : {
            eventName: 'webkitfullscreenchange',
            stateName: 'webkitIsFullScreen',
            requestFullScreen: 'webkitRequestFullScreen',
            cancelFullScreen: 'webkitExitFullscreen'
        },
        'msie' : {
            eventName: 'msfullscreenchange',
            stateName: 'msFullScreen',
            requestFullScreen: 'msRequestFullScreen',
            cancelFullScreen: 'msExitFullscreen'
        }
    },
    getUserAgent: function(){
        var _ua = 'default';
        for(var key in this.clients){
            if(RegExp(key).test(navigator.userAgent.toLowerCase())){
                _ua = key;
            }
        }
        return _ua;
    },
    bindEvent: function(){
        $(document).on(window.UserAgent.eventName,window.fullScreenChangeEvents['fullScreenChangeEvent_' + this.fullScreenHelperID]);
    },
    unbindEvent: function(){
        $(document).unbind(window.UserAgent.eventName,window.fullScreenChangeEvents['fullScreenChangeEvent_' + this.fullScreenHelperID]);
    },
    fullScreen: function(){
        if(this.targetElement[window.UserAgent.requestFullScreen]){
            this.targetElement[window.UserAgent.requestFullScreen]();
        }else{
            //浏览器不支持全屏API或已被禁用
        }
    },
    exitFullScreen: function(){
        if(document[window.UserAgent.cancelFullScreen]){
            document[window.UserAgent.cancelFullScreen]();
        }else{
            //浏览器不支持全屏API或已被禁用
        }
    },
    toggleFullScreen: function(){
        if(document[window.UserAgent.stateName]){
            this.exitFullScreen();
        }else{
            this.fullScreen();
        }
    }
}
<commit_msg>fix bug<commit_after>/*
 *
 * Copyright (c) 2015 EBo (https://github.com/E-Bo)
 *
 * Version 0.1
 *
 * Work with jQuery
 *
 */

var fullScreenHelper = function(options){
    options = options || {};
    window.fullScreenHelperCounter = window.fullScreenHelperCounter? window.fullScreenHelperCounter + 1 : 1;
    window.UserAgent = window.UserAgent || this.clients[this.getUserAgent()];
    this.fullScreenHelperID = window.fullScreenHelperCounter;
    this.RequestFullCallBack = options.RequestFullCallBack || null;
    this.CancelFullCallBack = options.CancelFullCallBack || null;
    this.targetElement = options.target || document.getElementsByTagName('html')[0];
    window.fullScreenChangeEvents = window.fullScreenChangeEvents || {};
    window.fullScreenChangeEvents['fullScreenChangeEvent_' + this.fullScreenHelperID] = $.proxy(function(){
        if(document[window.UserAgent.stateName]){
            if(this.RequestFullCallBack && typeof(this.RequestFullCallBack) == 'function'){
                this.RequestFullCallBack();
            }
        }else{
            if(this.CancelFullCallBack && typeof(this.CancelFullCallBack) == 'function'){
                this.CancelFullCallBack();
            }
        }
    },this);
    this.bindEvent();
}

fullScreenHelper.prototype = {
    clients: {
        'default' : {
            eventName: 'fullscreenchange',
            stateName: 'fullScreen',
            requestFullScreen: 'requestFullScreen',
            cancelFullScreen: 'exitFullscreen'
        },
        'firefox' : {
            eventName: 'mozfullscreenchange',
            stateName: 'mozFullScreen',
            requestFullScreen: 'mozRequestFullScreen',
            cancelFullScreen: 'mozCancelFullScreen'
        },
        'webkit' : {
            eventName: 'webkitfullscreenchange',
            stateName: 'webkitIsFullScreen',
            requestFullScreen: 'webkitRequestFullScreen',
            cancelFullScreen: 'webkitExitFullscreen'
        },
        'msie' : {
            eventName: 'msfullscreenchange',
            stateName: 'msFullScreen',
            requestFullScreen: 'msRequestFullScreen',
            cancelFullScreen: 'msExitFullscreen'
        }
    },
    getUserAgent: function(){
        var _ua = 'default';
        for(var key in this.clients){
            if(RegExp(key).test(navigator.userAgent.toLowerCase())){
                _ua = key;
            }
        }
        return _ua;
    },
    bindEvent: function(){
        $(document).on(window.UserAgent.eventName,window.fullScreenChangeEvents['fullScreenChangeEvent_' + this.fullScreenHelperID]);
    },
    unbindEvent: function(){
        $(document).unbind(window.UserAgent.eventName,window.fullScreenChangeEvents['fullScreenChangeEvent_' + this.fullScreenHelperID]);
    },
    fullScreen: function(){
        if(this.targetElement[window.UserAgent.requestFullScreen]){
            this.targetElement[window.UserAgent.requestFullScreen]();
        }else{
            //浏览器不支持全屏API或已被禁用
        }
    },
    exitFullScreen: function(){
        if(document[window.UserAgent.cancelFullScreen]){
            document[window.UserAgent.cancelFullScreen]();
        }else{
            //浏览器不支持全屏API或已被禁用
        }
    },
    toggleFullScreen: function(){
        if(document[window.UserAgent.stateName]){
            this.exitFullScreen();
        }else{
            this.fullScreen();
        }
    }
}
<|endoftext|>


<commit_before>'use strict';

/*
  Block Table
*/

var _ = require('../lodash');
var $ = require('jquery');
var Block = require('../block');
var template = '' +
  '
' +
    '

' +
    '
' +
      '
' +
        '	' +
        '	' +
      '
' +
    '
' +
    '
' +
      '
' +
        '	' +
        '	' +
      '
' +
    '
' +
  '
';
var instruction = '' + i18n.t('blocks:table:helper-merge') + '';
function addCell(row, cellTag) {
    var tag_template = _.template('<<%= tag %>>');

    if (cellTag === undefined) {
        cellTag = tag_template(
            { tag: $(row).children().first().prop('tagName').toLowerCase() }
        );
    }
    $(row).append($(cellTag, { contenteditable: '' }));
}
function addColumnHandler(ev, scope) {
    ev.preventDefault();
    scope.find('tr').each(function() {
        addCell(this);
    });
}

function mergeCellHandler(ev, scope) {
    ev.preventDefault();
    var table = scope;
    var activated = true;

    $('.st-block-control-ui-btn--unmerge-cell').css('pointer-events', 'none');
    table.find('td').each(function() {
        $(this).addClass('mergeable');
        if (undefined === $(this).attr('colspan')){
            $(this).attr('colspan', 1);
        }
    });
    $('tr').children('td').on('click', function(){
        if (activated === true){

            if ($(this).next('td').index() !== -1){
                var nextWidth = parseInt($(this).next('td').attr('colspan'));
                $(this).next('td').remove();
                var colspanValue = parseInt($(this).attr('colspan'));
                $(this).attr('colspan', colspanValue + nextWidth);
                table.find('td').each(function() {
                    $(this).addClass('mergeable');
                    if (undefined === $(this).attr('colspan')){
                        $(this).attr('colspan', 1);
                    }
                });
            }
        }
    });
    $('.st-block-control-ui-btn--merge-cell').on('click', function(evt) {
        evt.preventDefault();
        evt.stopPropagation();
        // Desactivate unmerge button
        $('.st-block-control-ui-btn--unmerge-cell').css('pointer-events', 'none');
        //Toggle actual button state
        activated = (activated === true) ? false : true;
        addHelper(ev, scope, instruction);
        $('.st-block-control-ui-btn--merge-cell').toggleClass('activated');
        if (false === activated) {
            $('.st-block-control-ui-btn--unmerge-cell').css('pointer-events', 'all');
            deleteHelper(ev, scope);
            table.find('td').each(function() {
                $(this).removeClass('mergeable');
            });
        }
        else {
            table.find('td').each(function() {
            $(this).addClass('mergeable');
                if (undefined === $(this).attr('colspan')){
                    $(this).attr('colspan', 1);
                }
            });
        }
    });
}
function unMergeCellHandler(ev, scope){
    ev.preventDefault();
    var activated = true;
    var table = scope;
    $('.st-block-control-ui-btn--merge-cell').css('pointer-events', 'none');

    table.find('td').each(function(){
        var colspanValue = parseInt($(this).attr('colspan'));
        if (colspanValue > 1){
            $(this).addClass('unmergeable');
        }
    });
    $('tr').children('td').on('click', function(){
        if (activated === true){
            var colspanValue = parseInt($(this).attr('colspan'));
            if (colspanValue > 1){
                $(this).attr('colspan', colspanValue - 1);
                $(this).parent().append('	');
            }
            table.find('td').each(function() {
                $(this).removeClass('unmergeable');
                $(this).attr('contenteditable', '');
            });
        }
    });
    $('.st-block-control-ui-btn--unmerge-cell').on('click', function(evt) {
        evt.preventDefault();
        evt.stopPropagation();
        $('.st-block-control-ui-btn--merge-cell').css('pointer-events', 'none');
        activated = (activated === true) ? false : true;
        addHelper(ev, scope, instruction);
        $('.st-block-control-ui-btn--unmerge-cell').toggleClass('activated');
        if (false === activated) {
            $('.st-block-control-ui-btn--merge-cell').css('pointer-events', 'all');
            deleteHelper(ev, scope);
            table.find('td').each(function() {
                $(this).removeClass('unmergeable');
            });
        }
        else {
            table.find('td').each(function() {
                var colspanValue = parseInt($(this).attr('colspan'));
                if (colspanValue > 1){
                    $(this).addClass('unmergeable');
                }
                if (undefined === $(this).attr('colspan')){
                    $(this).attr('colspan', 1);
                }
            });
        }
    });
}
function deleteColumnHandler(ev, scope) {
    ev.preventDefault();

    scope.find('tr').each(function() {
        if ($(this).children().length > 1) {
            var colspanValue = parseInt($(this).children().last().attr('colspan'));
            if (colspanValue > 1){
                $(this).children().last().attr('colspan', colspanValue - 1);
            }
            else {
                $(this).children().last().remove();
            }
        }

    });
}
function addRowHandler(ev, scope) {
    var row = $('
');

    ev.preventDefault();
    scope.find('th').each(function() {
        addCell(row, '');
    });
    scope.find('tbody').append(row);
}
function deleteRowHandler(ev, block) {
    ev.preventDefault();

    if (block.find('tbody tr').length > 1) {
        block.find('tbody tr:last').remove();
    }
}
function changeTheme(ev, block) {
    var table = block.find('table');
    var themeSelector = $('.theme-selector select');
    themeSelector.on('change', function(){
        var themeClass = $(this).find(':selected').val();
        table.removeClass();
        table.addClass(themeClass);
    });
}
function addHelper(ev, block, content) {
  var table = block.find('table');
  table.before(content);
}
function deleteHelper(ev, block) {
  var helper = block.find('.helper');
  helper.remove();
}

module.exports = Block.extend({
    type: 'table',
    title: function() { return 'Table'; },
    icon_name: 'text table',
    scope: function(){
        this.getTextBlock().find('table');
    },
    activable: true,
    controllable: true,
    controls_position: 'bottom',
    controls_visible: true,
    controls: [
        {
            slug: 'theme-toggle',
            eventTrigger: 'click',
            fn: function(e) {
                 e.preventDefault();
                 var block = this.getTextBlock();
                 changeTheme(e, block);
             },
            html: '
<select><option class="theme edt-theme-default"  value="edt-theme-default">' + i18n.t('blocks:table:default') + '</option> <option class="theme edt-theme-blue" value="edt-theme-blue">' + i18n.t('blocks:table:blue-theme') + '</option><option class="theme edt-theme-red" value="edt-theme-red">' + i18n.t('blocks:table:red-theme') + '</option></select>
'
        },
        {
            slug: 'add-column',
            icon: 'add',
            fn: function(e) {
                e.preventDefault();
                var block = this.getTextBlock();
                addColumnHandler(e, block);
            }
        },
        {
            slug: 'del-column',
            icon: 'bin1',
            fn: function(e) {
                e.preventDefault();
                var block = this.getTextBlock();
                deleteColumnHandler(e, block);
            }
        },
        {
            slug: 'add-row',
            icon: 'add col',
            fn: function(e) {
                e.preventDefault();
                var block = this.getTextBlock();
                addRowHandler(e, block);
            }
        },
        {
            slug: 'del-row',
            icon: 'bin2',
            fn: function(e) {
                e.preventDefault();
                var block = this.getTextBlock();
                deleteRowHandler(e, block);
            }
        },
        {
            slug: 'merge-cell',
            icon: 'add cell',
            activable: true,
            fn: function(e) {
                e.preventDefault();
                var content= '' + i18n.t('blocks:table:helper-merge') + '';
                var block = this.getTextBlock();
                deleteHelper(e, block, content);
                addHelper(e, block, content);
                mergeCellHandler(e, block);
            }
        },
        {
            slug: 'unmerge-cell',
            icon: 'binopen',
            activable: true,
            fn: function(e) {
                e.preventDefault();
                var block = this.getTextBlock();
                var content = '' + i18n.t('blocks:table:helper-unmerge') + '';
                deleteHelper(e, block, content);
                addHelper(e, block, content);
                unMergeCellHandler(e, block);
            }
        }

    ],

    editorHTML: function() {
        var editor_template = '
' + template + '
';
        return _.template(editor_template, this);
    },
    onBlockRender: function() {
        this.$table = this.getTextBlock().find('table');
    },
    loadData: function(data){
        this.getTextBlock().html(data.text, this.type);
    },
    toMarkdown: function(html) {
        function rowToMarkdown(row) {
        var cells = $(row).children(),
            md = cells.map(function() { return $(this).text(); }).get().join(' | ');
        if (cells[0].tagName === 'TH') {
            md += '\n';
            md += cells.map(function() { return '---'; }).get().join(' | ');
        }
        return md;
    }
    var markdown = $(html).find('tr').map(function(){
        return rowToMarkdown(this);
        }).get().join('\n');
        if ($(html).find('caption').text() !== '') {
        markdown += '\n[' + $(html).find('caption').text() + ']';
        }
        return markdown;
    },
    toHTML: function(markdown) {
        var html = $('

'),
        lines = markdown.split('\n'),
        caption_re = /\[(.*)\]/,
        lastline;
        lastline = lines[lines.length - 1];
        if (lastline.match(caption_re)) {
            html.find('caption').text(lastline.match(caption_re)[1]);
            lines = lines.slice(0, lines.length - 1);
        }
        // Add header row
        _.each(lines[0].split(' | '), function(content) {
            html.find('thead tr').append('' + content + '	');
        });
        // Add remaining rows
        _.each(lines.slice(2, lines.length), function(line) {
            var row = $('
');
            _.each(line.split(' | '), function(content) {
                row.append('' + content + '	');
            });
        html.find('tbody').append(row);
        });
    return html[0].outerHTML;
    },

    isEmpty: function() {
        return _.isEmpty(this.saveAndGetData().text);
    }

});
<commit_msg>Mode merge included<commit_after>'use strict';

/*
  Block Table
*/

var _ = require('../lodash');
var $ = require('jquery');
var Block = require('../block');
var template = '' +
  '
' +
    '

' +
    '
' +
      '
' +
        '	' +
        '	' +
      '
' +
    '
' +
    '
' +
      '
' +
        '	' +
        '	' +
      '
' +
    '
' +
  '
';
var instruction = '' + i18n.t('blocks:table:helper-merge') + '';
function addCell(row, cellTag) {
    var tag_template = _.template('<<%= tag %>>');

    if (cellTag === undefined) {
        cellTag = tag_template(
            { tag: $(row).children().first().prop('tagName').toLowerCase() }
        );
    }
    $(row).append($(cellTag, { contenteditable: '' }));
}
function addColumnHandler(ev, scope) {
    ev.preventDefault();
    scope.find('tr').each(function() {
        addCell(this);
    });
    scope.find('td').each(function() {
        if (undefined === $(this).attr('colspan')){
            $(this).attr('colspan', 1);
        }
    });
}

function mergeCellHandler(ev, scope) {
    ev.preventDefault();
    var table = scope;
    var activated = true;

    $('.st-block-control-ui-btn--unmerge-cell').css('pointer-events', 'none');
    table.find('td').each(function() {
        $(this).addClass('mergeable');
        if (undefined === $(this).attr('colspan')){
            $(this).attr('colspan', 1);
        }
    });
    $('tr').children('td').on('click', function(){
        if (activated === true){
            if ($(this).next('td').index() !== -1){
                var nextWidth = parseInt($(this).next('td').attr('colspan'));
                $(this).next('td').remove();
                var colspanValue = parseInt($(this).attr('colspan'));
                $(this).attr('colspan', colspanValue + nextWidth);
                table.find('td').each(function() {
                    $(this).addClass('mergeable');
                    if (undefined === $(this).attr('colspan')){
                        $(this).attr('colspan', 1);
                    }
                });
            }
        }
    });
    // Handle the controls
    $('.st-block-control-ui-btn--merge-cell').on('click', function(evt) {
        evt.preventDefault();
        evt.stopPropagation();
        $('.st-block-control-ui-btn--merge-cell').toggleClass('activated');
        if ($('.st-block-control-ui-btn--merge-cell').hasClass('activated')){
            activated = true;
            // Desactivate unmerge button
            $('.st-block-control-ui-btn--unmerge-cell').css('pointer-events', 'none');
            addHelper(ev, scope, instruction);
            table.find('td').each(function() {
                $(this).addClass('mergeable');
                if (undefined === $(this).attr('colspan')){
                    $(this).attr('colspan', 1);
                }
            });
        }
        else {
            activated = false;
            $('.st-block-control-ui-btn--unmerge-cell').css('pointer-events', 'all');
            deleteHelper(ev, scope, instruction);
            table.find('td').each(function() {
                $(this).removeClass('mergeable');
            });
        }

    });
}
function unMergeCellHandler(ev, scope){
    ev.preventDefault();
    var activated = true;
    var table = scope;
    $('.st-block-control-ui-btn--merge-cell').css('pointer-events', 'none');

    table.find('td').each(function(){
        var colspanValue = parseInt($(this).attr('colspan'));
        if (colspanValue > 1){
            $(this).addClass('unmergeable');
        }
    });
    //Perform actions inside the table
    $('tr').children('td').on('click', function(){
        if (activated === true){
            var colspanValue = parseInt($(this).attr('colspan'));
            if (colspanValue > 1){
                $(this).attr('colspan', colspanValue - 1);
                $(this).parent().append('	');
            }
            table.find('td').each(function() {
                $(this).removeClass('unmergeable');
                $(this).attr('contenteditable', '');
                colspanValue = parseInt($(this).attr('colspan'));
                if (colspanValue > 1){
                    $(this).addClass('unmergeable');
                }
            });
        }
    });
    // Handle the controls
    $('.st-block-control-ui-btn--unmerge-cell').on('click', function(evt) {
        evt.preventDefault();
        evt.stopPropagation();
        $('.st-block-control-ui-btn--unmerge-cell').toggleClass('activated');
        if ($('.st-block-control-ui-btn--unmerge-cell').hasClass('activated')){
            activated = true;
            // Desactivate unmerge button
            $('.st-block-control-ui-btn--merge-cell').css('pointer-events', 'none');
            addHelper(ev, scope, instruction);
            table.find('td').each(function() {
                var colspanValue = parseInt($(this).attr('colspan'));
                if (colspanValue > 1){
                    $(this).addClass('unmergeable');
                }
                if (undefined === $(this).attr('colspan')){
                    $(this).attr('colspan', 1);
                }
            });
        }
        else {
            activated = false;
            $('.st-block-control-ui-btn--merge-cell').css('pointer-events', 'all');
            deleteHelper(ev, scope);
            table.find('td').each(function() {
                $(this).removeClass('unmergeable');
            });
        }

    });
}
function deleteColumnHandler(ev, scope) {
    ev.preventDefault();

    scope.find('tr').each(function() {
        if ($(this).children().length > 1) {
            var colspanValue = parseInt($(this).children().last().attr('colspan'));
            if (colspanValue > 1){
                $(this).children().last().attr('colspan', colspanValue - 1);
            }
            else {
                $(this).children().last().remove();
            }
        }

    });
}
function addRowHandler(ev, scope) {
    var row = $('
');

    ev.preventDefault();
    scope.find('th').each(function() {
        addCell(row, '');
    });

    scope.find('tbody').append(row);
    //Really important allow us to merge
    scope.find('td').each(function() {
        if (undefined === $(this).attr('colspan')){
            $(this).attr('colspan', 1);
        }
    });
}
function deleteRowHandler(ev, block) {
    ev.preventDefault();

    if (block.find('tbody tr').length > 1) {
        block.find('tbody tr:last').remove();
    }
}
function changeTheme(ev, block) {
    var table = block.find('table');
    var themeSelector = $('.theme-selector select');
    themeSelector.on('change', function(){
        var themeClass = $(this).find(':selected').val();
        table.removeClass();
        table.addClass(themeClass);
    });
}
function addHelper(ev, block, content) {
  var table = block.find('table');
  table.before(content);
}
function deleteHelper(ev, block) {
  var helper = block.find('.helper');
  helper.remove();
}

module.exports = Block.extend({
    type: 'table',
    title: function() { return 'Table'; },
    icon_name: 'text table',
    scope: function(){
        this.getTextBlock().find('table');
    },
    activable: true,
    controllable: true,
    controls_position: 'bottom',
    controls_visible: true,
    controls: [
        {
            slug: 'theme-toggle',
            eventTrigger: 'click',
            fn: function(e) {
                 e.preventDefault();
                 var block = this.getTextBlock();
                 changeTheme(e, block);
             },
            html: '
<select><option class="theme edt-theme-default"  value="edt-theme-default">' + i18n.t('blocks:table:default') + '</option> <option class="theme edt-theme-blue" value="edt-theme-blue">' + i18n.t('blocks:table:blue-theme') + '</option><option class="theme edt-theme-red" value="edt-theme-red">' + i18n.t('blocks:table:red-theme') + '</option></select>
'
        },
        {
            slug: 'add-column',
            icon: 'add',
            fn: function(e) {
                e.preventDefault();
                var block = this.getTextBlock();
                addColumnHandler(e, block);
            }
        },
        {
            slug: 'del-column',
            icon: 'bin1',
            fn: function(e) {
                e.preventDefault();
                var block = this.getTextBlock();
                deleteColumnHandler(e, block);
            }
        },
        {
            slug: 'add-row',
            icon: 'add col',
            fn: function(e) {
                e.preventDefault();
                var block = this.getTextBlock();
                addRowHandler(e, block);
            }
        },
        {
            slug: 'del-row',
            icon: 'bin2',
            fn: function(e) {
                e.preventDefault();
                var block = this.getTextBlock();
                deleteRowHandler(e, block);
            }
        },
        {
            slug: 'merge-cell',
            icon: 'add cell',
            activable: true,
            fn: function(e) {
                e.preventDefault();
                var content= '' + i18n.t('blocks:table:helper-merge') + '';
                var block = this.getTextBlock();
                deleteHelper(e, block, content);
                addHelper(e, block, content);
                mergeCellHandler(e, block);
            }
        },
        {
            slug: 'unmerge-cell',
            icon: 'binopen',
            activable: true,
            fn: function(e) {
                e.preventDefault();
                var block = this.getTextBlock();
                var content = '' + i18n.t('blocks:table:helper-unmerge') + '';
                deleteHelper(e, block, content);
                addHelper(e, block, content);
                unMergeCellHandler(e, block);
            }
        }

    ],

    editorHTML: function() {
        var editor_template = '
' + template + '
';
        return _.template(editor_template, this);
    },
    onBlockRender: function() {
        this.$table = this.getTextBlock().find('table');
    },
    loadData: function(data){
        this.getTextBlock().html(data.text, this.type);
    },
    toMarkdown: function(html) {
        function rowToMarkdown(row) {
        var cells = $(row).children(),
            md = cells.map(function() { return $(this).text(); }).get().join(' | ');
        if (cells[0].tagName === 'TH') {
            md += '\n';
            md += cells.map(function() { return '---'; }).get().join(' | ');
        }
        return md;
    }
    var markdown = $(html).find('tr').map(function(){
        return rowToMarkdown(this);
        }).get().join('\n');
        if ($(html).find('caption').text() !== '') {
        markdown += '\n[' + $(html).find('caption').text() + ']';
        }
        return markdown;
    },
    toHTML: function(markdown) {
        var html = $('

'),
        lines = markdown.split('\n'),
        caption_re = /\[(.*)\]/,
        lastline;
        lastline = lines[lines.length - 1];
        if (lastline.match(caption_re)) {
            html.find('caption').text(lastline.match(caption_re)[1]);
            lines = lines.slice(0, lines.length - 1);
        }
        // Add header row
        _.each(lines[0].split(' | '), function(content) {
            html.find('thead tr').append('' + content + '	');
        });
        // Add remaining rows
        _.each(lines.slice(2, lines.length), function(line) {
            var row = $('
');
            _.each(line.split(' | '), function(content) {
                row.append('' + content + '	');
            });
        html.find('tbody').append(row);
        });
    return html[0].outerHTML;
    },

    isEmpty: function() {
        return _.isEmpty(this.saveAndGetData().text);
    }

});
<|endoftext|>


<commit_before>"use strict";

var _ = require('../lodash');
var utils = require('../utils');
var Block = require('../block');

module.exports = Block.extend({

  // more providers at https://gist.github.com/jeffling/a9629ae28e076785a14f
  providers: {
    vimeo: {
      regex: /(?:http[s]?:\/\/)?(?:www.)?vimeo\.co(?:.+(?:\/)([^\/].*)+$)/,
      html: "<iframe src=\"<%= protocol %>//player.vimeo.com/video/<%= remote_id %>?title=0&byline=0\" width=\"580\" height=\"320\" frameborder=\"0\">"
    },
    youtube: {
      regex: /^.*(?:(youtu\.be|youtube\.com)\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*)/,
      html: "<iframe src=\"<%= protocol %>//www.youtube.com/embed/<%= remote_id %>\" width=\"580\" height=\"320\" frameborder=\"0\" allowfullscreen>"
    }
  },

  type: 'video',
  title: function() { return i18n.t('blocks:video:title'); },

  droppable: true,
  pastable: true,

  icon_name: 'video',

  loadData: function(data){
    if (!this.providers.hasOwnProperty(data.source)) { return; }

    var source = this.providers[data.source];

    var protocol = window.location.protocol === "file:" ?
      "http:" : window.location.protocol;

    var aspectRatioClass = source.square ?
      'with-square-media' : 'with-sixteen-by-nine-media';

    this.$editor
      .addClass('st-block__editor--' + aspectRatioClass)
      .html(_.template(source.html, {
        protocol: protocol,
        remote_id: data.remote_id,
        width: this.$editor.width() // for videos like vine
      }));
  },

  onContentPasted: function(event){
    this.handleDropPaste(event.target.value);
  },

  matchVideoProvider: function(provider, index, url) {
    var match = provider.regex.exec(url);
    if(match == null || _.isUndefined(match[1])) { return {}; }

    return {
      source: index,
      remote_id: match[1]
    };
  },

  handleDropPaste: function(url){
    if (!utils.isURI(url)) { return; }

    for(var key in this.providers) {
      if (!this.providers.hasOwnProperty(key)) { continue; }
      this.setAndLoadData(
        this.matchVideoProvider(this.providers[key], key, url)
      );
    }
  },

  onDrop: function(transferData){
    var url = transferData.getData('text/plain');
    this.handleDropPaste(url);
  }
});

<commit_msg>Update video.js<commit_after>"use strict";

var _ = require('../lodash');
var utils = require('../utils');
var Block = require('../block');

module.exports = Block.extend({

  // more providers at https://gist.github.com/jeffling/a9629ae28e076785a14f
  providers: {
    vimeo: {
      regex: /(?:http[s]?:\/\/)?(?:www.)?vimeo\.co(?:.+(?:\/)([^\/].*)+$)/,
      html: "<iframe src=\"<%= protocol %>//player.vimeo.com/video/<%= remote_id %>?title=0&byline=0\" width=\"580\" height=\"320\" frameborder=\"0\">"
    },
    youtube: {
      regex: /^.*(?:(?:youtu\.be\/)|(?:youtube\.com)\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*)/,
      html: "<iframe src=\"<%= protocol %>//www.youtube.com/embed/<%= remote_id %>\" width=\"580\" height=\"320\" frameborder=\"0\" allowfullscreen>"
    }
  },

  type: 'video',
  title: function() { return i18n.t('blocks:video:title'); },

  droppable: true,
  pastable: true,

  icon_name: 'video',

  loadData: function(data){
    if (!this.providers.hasOwnProperty(data.source)) { return; }

    var source = this.providers[data.source];

    var protocol = window.location.protocol === "file:" ?
      "http:" : window.location.protocol;

    var aspectRatioClass = source.square ?
      'with-square-media' : 'with-sixteen-by-nine-media';

    this.$editor
      .addClass('st-block__editor--' + aspectRatioClass)
      .html(_.template(source.html, {
        protocol: protocol,
        remote_id: data.remote_id,
        width: this.$editor.width() // for videos like vine
      }));
  },

  onContentPasted: function(event){
    this.handleDropPaste(event.target.value);
  },

  matchVideoProvider: function(provider, index, url) {
    var match = provider.regex.exec(url);
    if(match == null || _.isUndefined(match[1])) { return {}; }

    return {
      source: index,
      remote_id: match[1]
    };
  },

  handleDropPaste: function(url){
    if (!utils.isURI(url)) { return; }

    for(var key in this.providers) {
      if (!this.providers.hasOwnProperty(key)) { continue; }
      this.setAndLoadData(
        this.matchVideoProvider(this.providers[key], key, url)
      );
    }
  },

  onDrop: function(transferData){
    var url = transferData.getData('text/plain');
    this.handleDropPaste(url);
  }
});

<|endoftext|>


<commit_before>

'use strict';

var google = require("googleapis");

exports.fileIsProcessable = function (file) {
  // TODO: make this better. I am sure this is not the only reason to not
  // process a file.
    return (file.resourceState !== "not_exists");
};

exports.queueForFile = function (filename) {
    var key, re, experiment_to_task_queue;
    experiment_to_task_queue = {
        "switch": "etl-disco-queue",
        "ndt": "etl-ndt-queue",
        "ndt/traceroute": "etl-scamper-queue",
        "sidestream": "etl-sidestream-queue",
        "paris-traceroute": "etl-traceroute-queue"
    };
    // TODO - fix this.
    for (key in experiment_to_task_queue) {
        re = new RegExp("^" + key + "/\\d{4}/\\d{2}/\\d{2}/[0-9a-z_a-z:.-]+");
        if (re.test(filename)) {
            return experiment_to_task_queue[key];
        }
    }
    return null;
};

exports.enqueueFileTask = function (project, bucket, filename, callback) {
    var http, gsFilename, safeFilename;
    http = require('http');
    gsFilename = "gs://" + bucket + "/" + filename;
    safeFilename = new Buffer(gsFilename).toString("base64");
    http.get('http://queue-pusher-dot-' + project +
        '.appspot.com/receiver?filename=' + safeFilename,
        function (res) {
            res.on('data', function (data) {});
            res.on('end',
                function () {
                    console.log('Enqueue GET done', gsFilename);
                    callback();
                });
        });
};

/**
 * Cloud Function to be triggered by Cloud Storage, enqueues the file to the
 * proper task queue (or none at all).
 *
 * @param {object} event The Cloud Functions event.
 * @param {function} The callback function.
 */
exports.createSandboxTaskOnFileNotification = function (event, callback) {
    var file = event.data;

    if (exports.fileIsProcessable(file) && exports.queueForFile(file.name)) {
        exports.enqueueFileTask('mlab-sandbox', file.bucket, file.name, callback);
    } else {
        callback();
    }
};

/**
 * Cloud Function to be triggered by Cloud Storage, enqueues the file to the
 * proper task queue (or none at all).
 *
 * @param {object} event The Cloud Functions event.
 * @param {function} The callback function.
 */
exports.createStagingTaskOnFileNotification = function (event, callback) {
    var file = event.data;

    if (exports.fileIsProcessable(file) && exports.queueForFile(file.name)) {
        exports.enqueueFileTask('mlab-staging', file.bucket, file.name, callback);
    } else {
        callback();
    }
};

/**
 * Cloud Function to be triggered by Cloud Storage, enqueues the file to the
 * proper task queue (or none at all).
 *
 * @param {object} event The Cloud Functions event.
 * @param {function} The callback function.
 */
exports.createProdTaskOnFileNotification = function (event, callback) {
    var file = event.data;

    if (exports.fileIsProcessable(file) && exports.queueForFile(file.name)) {
        exports.enqueueFileTask('mlab-oti', file.bucket, file.name, callback);
    } else {
        callback();
    }
};

exports.createSandboxTaskOnEmbargoFileNotification = exports.createSandboxTaskOnFileNotification
exports.createStagingTaskOnEmbargoFileNotification = exports.createStagingTaskOnFileNotification
exports.createProdTaskOnEmbargoFileNotification = exports.createProdTaskOnFileNotification
<commit_msg>Update enqueue.js (#744)<commit_after>

'use strict';

var google = require("googleapis");

exports.fileIsProcessable = function (file) {
  // TODO: make this better. I am sure this is not the only reason to not
  // process a file.
    return (file.resourceState !== "not_exists");
};

exports.queueForFile = function (filename) {
    var key, re, experiment_to_task_queue;
    experiment_to_task_queue = {
        "switch": "etl-disco-queue",
        "ndt": "etl-ndt-queue",
        "ndt/traceroute": "etl-scamper-queue",
        "host/traceroute": "etl-scamper-queue",
        "bismark/traceroute": "etl-scamper-queue",
        "neubot/traceroute": "etl-scamper-queue",
        "sidestream": "etl-sidestream-queue",
        "paris-traceroute": "etl-traceroute-queue"
    };
    // TODO - fix this.
    for (key in experiment_to_task_queue) {
        re = new RegExp("^" + key + "/\\d{4}/\\d{2}/\\d{2}/[0-9a-z_a-z:.-]+");
        if (re.test(filename)) {
            return experiment_to_task_queue[key];
        }
    }
    return null;
};

exports.enqueueFileTask = function (project, bucket, filename, callback) {
    var http, gsFilename, safeFilename;
    http = require('http');
    gsFilename = "gs://" + bucket + "/" + filename;
    safeFilename = new Buffer(gsFilename).toString("base64");
    http.get('http://queue-pusher-dot-' + project +
        '.appspot.com/receiver?filename=' + safeFilename,
        function (res) {
            res.on('data', function (data) {});
            res.on('end',
                function () {
                    console.log('Enqueue GET done', gsFilename);
                    callback();
                });
        });
};

/**
 * Cloud Function to be triggered by Cloud Storage, enqueues the file to the
 * proper task queue (or none at all).
 *
 * @param {object} event The Cloud Functions event.
 * @param {function} The callback function.
 */
exports.createSandboxTaskOnFileNotification = function (event, callback) {
    var file = event.data;

    if (exports.fileIsProcessable(file) && exports.queueForFile(file.name)) {
        exports.enqueueFileTask('mlab-sandbox', file.bucket, file.name, callback);
    } else {
        callback();
    }
};

/**
 * Cloud Function to be triggered by Cloud Storage, enqueues the file to the
 * proper task queue (or none at all).
 *
 * @param {object} event The Cloud Functions event.
 * @param {function} The callback function.
 */
exports.createStagingTaskOnFileNotification = function (event, callback) {
    var file = event.data;

    if (exports.fileIsProcessable(file) && exports.queueForFile(file.name)) {
        exports.enqueueFileTask('mlab-staging', file.bucket, file.name, callback);
    } else {
        callback();
    }
};

/**
 * Cloud Function to be triggered by Cloud Storage, enqueues the file to the
 * proper task queue (or none at all).
 *
 * @param {object} event The Cloud Functions event.
 * @param {function} The callback function.
 */
exports.createProdTaskOnFileNotification = function (event, callback) {
    var file = event.data;

    if (exports.fileIsProcessable(file) && exports.queueForFile(file.name)) {
        exports.enqueueFileTask('mlab-oti', file.bucket, file.name, callback);
    } else {
        callback();
    }
};

exports.createSandboxTaskOnEmbargoFileNotification = exports.createSandboxTaskOnFileNotification
exports.createStagingTaskOnEmbargoFileNotification = exports.createStagingTaskOnFileNotification
exports.createProdTaskOnEmbargoFileNotification = exports.createProdTaskOnFileNotification
<|endoftext|>


<commit_before>

'use strict';

var google = require("googleapis");

exports.fileIsProcessable = function (file) {
  // TODO: make this better. I am sure this is not the only reason to not
  // process a file.
    return (file.resourceState !== "not_exists");
};

exports.queueForFile = function (filename) {
    var key, re, experiment_to_task_queue;
    experiment_to_task_queue = {
        "switch": "etl-parser-queue",
        "ndt": "etl-ndt-queue",
        "sidestream": "etl-sidestream-queue",
        "paris-traceroute": "etl-paris-traceroute-queue"
    };
    for (key in experiment_to_task_queue) {
        re = new RegExp("^" + key + "/\\d{4}/\\d{2}/\\d{2}/[0-9a-z_a-z:.-]+");
        if (re.test(filename)) {
            return experiment_to_task_queue[key];
        }
    }
    return null;
};

exports.enqueueFileTask = function (project, bucket, filename, callback) {
    var http, gsFilename, safeFilename;
    http = require('http');
    gsFilename = "gs://" + bucket + "/" + filename;
    safeFilename = new Buffer(gsFilename).toString("base64");
    http.get('http://queue-pusher-dot-' + project +
        '.appspot.com/receiver?filename=' + safeFilename,
        function (res) {
            res.on('data', function (data) {});
            res.on('end',
                function () {
                    console.log('Enqueue GET done', gsFilename);
                    callback();
                });
        });
};

/**
 * Cloud Function to be triggered by Cloud Storage, enqueues the file to the
 * proper task queue (or none at all).
 *
 * @param {object} event The Cloud Functions event.
 * @param {function} The callback function.
 */
exports.createSandboxTaskOnFileNotification = function createTaskOnFileNotification(event, callback) {
    var file = event.data;

    if (exports.fileIsProcessable(file) && exports.queueForFile(file.name)) {
        exports.enqueueFileTask('mlab-sandbox', file.bucket, file.name, callback);
    } else {
        callback();
    }
};

/**
 * Cloud Function to be triggered by Cloud Storage, enqueues the file to the
 * proper task queue (or none at all).
 *
 * @param {object} event The Cloud Functions event.
 * @param {function} The callback function.
 */
exports.createStagingTaskOnFileNotification = function createTaskOnFileNotification(event, callback) {
    var file = event.data;

    if (exports.fileIsProcessable(file) && exports.queueForFile(file.name)) {
        exports.enqueueFileTask('mlab-staging', file.bucket, file.name, callback);
    } else {
        callback();
    }
};

/**
 * Cloud Function to be triggered by Cloud Storage, enqueues the file to the
 * proper task queue (or none at all).
 *
 * @param {object} event The Cloud Functions event.
 * @param {function} The callback function.
 */
exports.createProdTaskOnFileNotification = function createTaskOnFileNotification(event, callback) {
    var file = event.data;

    if (exports.fileIsProcessable(file) && exports.queueForFile(file.name)) {
        exports.enqueueFileTask('mlab-oti', file.bucket, file.name, callback);
    } else {
        callback();
    }
};
<commit_msg>Add TODO to fix for loop<commit_after>

'use strict';

var google = require("googleapis");

exports.fileIsProcessable = function (file) {
  // TODO: make this better. I am sure this is not the only reason to not
  // process a file.
    return (file.resourceState !== "not_exists");
};

exports.queueForFile = function (filename) {
    var key, re, experiment_to_task_queue;
    experiment_to_task_queue = {
        "switch": "etl-parser-queue",
        "ndt": "etl-ndt-queue",
        "sidestream": "etl-sidestream-queue",
        "paris-traceroute": "etl-paris-traceroute-queue"
    };
    // TODO - fix this.
    for (key in experiment_to_task_queue) {
        re = new RegExp("^" + key + "/\\d{4}/\\d{2}/\\d{2}/[0-9a-z_a-z:.-]+");
        if (re.test(filename)) {
            return experiment_to_task_queue[key];
        }
    }
    return null;
};

exports.enqueueFileTask = function (project, bucket, filename, callback) {
    var http, gsFilename, safeFilename;
    http = require('http');
    gsFilename = "gs://" + bucket + "/" + filename;
    safeFilename = new Buffer(gsFilename).toString("base64");
    http.get('http://queue-pusher-dot-' + project +
        '.appspot.com/receiver?filename=' + safeFilename,
        function (res) {
            res.on('data', function (data) {});
            res.on('end',
                function () {
                    console.log('Enqueue GET done', gsFilename);
                    callback();
                });
        });
};

/**
 * Cloud Function to be triggered by Cloud Storage, enqueues the file to the
 * proper task queue (or none at all).
 *
 * @param {object} event The Cloud Functions event.
 * @param {function} The callback function.
 */
exports.createSandboxTaskOnFileNotification = function createTaskOnFileNotification(event, callback) {
    var file = event.data;

    if (exports.fileIsProcessable(file) && exports.queueForFile(file.name)) {
        exports.enqueueFileTask('mlab-sandbox', file.bucket, file.name, callback);
    } else {
        callback();
    }
};

/**
 * Cloud Function to be triggered by Cloud Storage, enqueues the file to the
 * proper task queue (or none at all).
 *
 * @param {object} event The Cloud Functions event.
 * @param {function} The callback function.
 */
exports.createStagingTaskOnFileNotification = function createTaskOnFileNotification(event, callback) {
    var file = event.data;

    if (exports.fileIsProcessable(file) && exports.queueForFile(file.name)) {
        exports.enqueueFileTask('mlab-staging', file.bucket, file.name, callback);
    } else {
        callback();
    }
};

/**
 * Cloud Function to be triggered by Cloud Storage, enqueues the file to the
 * proper task queue (or none at all).
 *
 * @param {object} event The Cloud Functions event.
 * @param {function} The callback function.
 */
exports.createProdTaskOnFileNotification = function createTaskOnFileNotification(event, callback) {
    var file = event.data;

    if (exports.fileIsProcessable(file) && exports.queueForFile(file.name)) {
        exports.enqueueFileTask('mlab-oti', file.bucket, file.name, callback);
    } else {
        callback();
    }
};
<|endoftext|>


<commit_before>'use strict';
const app = require('app');
const path = require('path');
const BrowserWindow = require('browser-window');

// report crashes to the Electron project
require('crash-reporter').start();

// prevent window being GC'd
let mainWindow = null;
let resource_path = path.resolve(__dirname, '..', '..', 'resource');

app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('ready', function () {
  mainWindow = new BrowserWindow({
    width: 600,
    height: 400,
    resizable: false
  });

  mainWindow.loadUrl(`file://${resource_path}/index.html`);

  mainWindow.on('closed', function () {
    // deref the window
    // for multiple windows store them in an array
    mainWindow = null;
  });
});
<commit_msg>Mofify main.js<commit_after>'use strict';
const app = require('app');
const BrowserWindow = require('browser-window');
const path = require('path');

// report crashes to the Electron project
require('crash-reporter').start();

// prevent window being GC'd
let mainWindow = null;
let static_path = path.resolve(__dirname, '..', '..', 'static');

app.on('window-all-closed', function() {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('ready', function() {
  mainWindow = new BrowserWindow({
    width: 600,
    height: 400,
    resizable: false
  });

  mainWindow.loadUrl(`file://${static_path}/index.html`);

  mainWindow.on('closed', function() {
    // deref the window
    // for multiple windows store them in an array
    mainWindow = null;
  });
});
<|endoftext|>


<commit_before>/* eslint-env amd */

define(['underscore', 'backbone', 'jquery'], function(_, Backbone, $) {
    var Ping = function() {
        _.extend(this, Backbone.Events);
        this._send();
    };

    /**
     * Whether it has finished (whether succesfully or not)
     *
     * @type {boolean}
     */
    Ping.prototype.done = false;

    /**
     * Whether it finished failing
     *
     * @type {boolean}
     */
    Ping.prototype.failed = false;

    Ping.prototype.lag = function() {
        return (this.end || Date.now()) - this.start;
    };

    /**
     * Cancels the ping
     */
    Ping.prototype.abort = function () {
        this._request.abort();
        this.done = true;
        this.failed = true;
    };

    Ping.prototype.toString = function () {
        return 'Ping started at ' + new Date(this.start);
    };

    Ping.prototype._send = function() {
        var ping = this;

        // Here we have a copy of the site in a CDN close to the user. Ensure the
        // CDN is configured to not forward query strings to reduce latency.
        var url = 'http://d18ks85av1x0pi.cloudfront.net/scripts/blank.js';

        this.start = Date.now();
        this._request = $.ajax({url: url, dataType: 'script'});
        this._request.then(this._onLoad.bind(this));
        this._request.then(null, function () { ping.abort(); });
    };

    Ping.prototype._onLoad = function() {
        this.done = true;
        this.end = Date.now();
        this.trigger('pong');
    };

    return Ping;
});
<commit_msg>Ping from AMD to CommonJS<commit_after>/* eslint-env node */

var _ = require('underscore');
var Backbone = require('backbone');
var $ = require('jquery');

var Ping = module.exports = function() {
    _.extend(this, Backbone.Events);
    this._send();
};

/**
 * Whether it has finished (whether succesfully or not)
 *
 * @type {boolean}
 */
Ping.prototype.done = false;

/**
 * Whether it finished failing
 *
 * @type {boolean}
 */
Ping.prototype.failed = false;

Ping.prototype.lag = function() {
    return (this.end || Date.now()) - this.start;
};

/**
 * Cancels the ping
 */
Ping.prototype.abort = function () {
    this._request.abort();
    this.done = true;
    this.failed = true;
};

Ping.prototype.toString = function () {
    return 'Ping started at ' + new Date(this.start);
};

Ping.prototype._send = function() {
    var ping = this;

    // Here we have a copy of the site in a CDN close to the user. Ensure the
    // CDN is configured to not forward query strings to reduce latency.
    var url = 'http://d18ks85av1x0pi.cloudfront.net/scripts/blank.js';

    this.start = Date.now();
    this._request = $.ajax({url: url, dataType: 'script'});
    this._request.then(this._onLoad.bind(this));
    this._request.then(null, function () { ping.abort(); });
};

Ping.prototype._onLoad = function() {
    this.done = true;
    this.end = Date.now();
    this.trigger('pong');
};
<|endoftext|>


<commit_before>window.c.AdminUser = (function(m, h){
  return {
    view: function(ctrl, args) {
      var user = args.item;
      return m('.w-row.admin-user',[
        m('.w-col.w-col-3.w-col-small-3.u-marginbottom-10',[
          m('img.user-avatar[src="' + h.useAvatarOrDefault(user.user_profile_img) + '"]')
        ]),
        m('.w-col.w-col-9.w-col-small-9',[
          m('.fontweight-semibold.fontsize-smaller.lineheight-tighter.u-marginbottom-10', [
            m('a.alt-link[target="_blank"][href="/users/' + user.user_id + '/edit"]', user.user_name)
          ]),
          m('.fontsize-smallest', 'Usuário: ' + user.user_id),
          m('.fontsize-smallest.fontcolor-secondary', 'Catarse: ' + user.email),
          m('.fontsize-smallest.fontcolor-secondary', 'Gateway: ' + user.payer_email)
        ])
      ]);
    }
  };
}(window.m, window.c.h));
<commit_msg>Use same component for users list<commit_after>window.c.AdminUser = (function(m, h){
  return {
    view: function(ctrl, args) {
      //TODO: So, one component with IFs or two duplicated components?
      var item = args.item;
      if (item.user) {
        var user = item.user;
        return m('.w-row.admin-user',[
          m('.w-col.w-col-3.w-col-small-3.u-marginbottom-10',[
            m('img.user-avatar[src="' + h.useAvatarOrDefault(user.user_profile_img) + '"]')
          ]),
          m('.w-col.w-col-9.w-col-small-9',[
            m('.fontweight-semibold.fontsize-smaller.lineheight-tighter.u-marginbottom-10', [
              m('a.alt-link[target="_blank"][href="/users/' + user.user_id + '/edit"]', user.user_name)
            ]),
            m('.fontsize-smallest', 'Usuário: ' + user.user_id),
            m('.fontsize-smallest.fontcolor-secondary', 'Catarse: ' + user.email),
            m('.fontsize-smallest.fontcolor-secondary', 'Gateway: ' + user.payer_email)
          ])
        ]);
      } else {
        var user = item;
        return m('.w-row.admin-user',[
          m('.w-col.w-col-3.w-col-small-3.u-marginbottom-10',[
            m('img.user-avatar[src="' + h.useAvatarOrDefault(user.profile_img_thumbnail) + '"]')
          ]),
          m('.w-col.w-col-9.w-col-small-9',[
            m('.fontweight-semibold.fontsize-smaller.lineheight-tighter.u-marginbottom-10', [
              m('a.alt-link[target="_blank"][href="/users/' + user.id + '/edit"]', user.name)
            ]),
            m('.fontsize-smallest', 'Usuário: ' + user.id),
            m('.fontsize-smallest.fontcolor-secondary', 'Email: ' + user.email)
          ])
        ]);
      }
    }
  };
}(window.m, window.c.h));
<|endoftext|>


<commit_before>const app = require('electron').app
const autoUpdater = require('electron').autoUpdater
const ChildProcess = require('child_process')
const Menu = require('electron').Menu
const path = require('path')
const configFile = require('./package.json')
var state = 'checking'

exports.initialize = function (options) {
  if (process.mas) return

  autoUpdater.on('checking-for-update', function () {
    state = 'checking'
    exports.updateMenu()
  })

  autoUpdater.on('update-available', function () {
    state = 'checking'
    exports.updateMenu()
  })

  autoUpdater.on('update-downloaded', function () {
    state = 'installed'
    exports.updateMenu()
  })

  autoUpdater.on('update-not-available', function () {
    state = 'no-update'
    exports.updateMenu()
  })

  autoUpdater.on('error', function () {
    state = 'no-update'
    exports.updateMenu()
  })
  options.refDb.get("autoupdate").then(function(doc){
    if(doc.enable){
        var http = require("http");
        var serverOptions = {
            hostname: configFile["hostname"],
            path: '/updates/latest/version?v='+app.getVersion(),
            method: 'GET',
            headers: {
              'Content-Type': 'text/html',
              'Content-Length': Buffer.byteLength("")
            }
          };
          var req = http.request(serverOptions, (res) => {
            var body = '';
            res.on('data', (chunk) => {
              body += chunk;
            });
            res.on('end', () => {
              try{
                var resData = JSON.parse(body);
                if(resData["update"] ){
                    options.updateDownloaded = true;
                    autoUpdater.setFeedURL(`${configFile["autoupdate-endpoint"]}/${resData["version"]}`);
                    autoUpdater.checkForUpdates();
                }
              }catch(e){
                console.log(e);
              }
            });
          });
          req.on('error', function(error) {
            // Error handling here
              console.log("Error Occured to check for updates. Please try later..");
          });
        req.end();

    }
  }).catch(function(err){
    console.log(err)
  })
}

exports.updateMenu = function () {
  if (process.mas) return

  var menu = Menu.getApplicationMenu()
  if (!menu) return

  menu.items.forEach(function (item) {
    if (item.submenu) {
      item.submenu.items.forEach(function (item) {
        switch (item.key) {
          case 'checkForUpdate':
            item.visible = state === 'no-update'
            break
          case 'checkingForUpdate':
            item.visible = state === 'checking'
            break
          case 'restartToUpdate':
            item.visible = state === 'installed'
            break
        }
      })
    }
  })
}

exports.createShortcut = function (callback) {
  spawnUpdate([
    '--createShortcut',
    path.basename(process.execPath),
    '--shortcut-locations',
    'StartMenu'
  ], callback)
}

exports.removeShortcut = function (callback) {
  spawnUpdate([
    '--removeShortcut',
    path.basename(process.execPath)
  ], callback)
}

function spawnUpdate (args, callback) {
  var updateExe = path.resolve(path.dirname(process.execPath), '..', 'Update.exe')
  var stdout = ''
  var spawned = null

  try {
    spawned = ChildProcess.spawn(updateExe, args)
  } catch (error) {
    if (error && error.stdout == null) error.stdout = stdout
    process.nextTick(function () { callback(error) })
    return
  }

  var error = null

  spawned.stdout.on('data', function (data) { stdout += data })

  spawned.on('error', function (processError) {
    if (!error) error = processError
  })

  spawned.on('close', function (code, signal) {
    if (!error && code !== 0) {
      error = new Error('Command failed: ' + code + ' ' + signal)
    }
    if (error && error.code == null) error.code = code
    if (error && error.stdout == null) error.stdout = stdout
    callback(error)
  })
}
<commit_msg>auto-updater moved to src<commit_after><|endoftext|>


<commit_before>import { LightningElement, api, track, wire } from 'lwc';
import { fireEvent } from 'c/pubsubNoPageRef';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';

import { getNestedProperty } from 'c/utilCommon';
import { getObjectInfo } from 'lightning/uiObjectInfoApi';
import { getRecord} from 'lightning/uiRecordApi';

import RECURRING_DONATION_INFO from '@salesforce/schema/npe03__Recurring_Donation__c';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';
import CONTACT_OBJECT from '@salesforce/schema/Contact';

import FIELD_NAME from '@salesforce/schema/npe03__Recurring_Donation__c.Name';
import FIELD_ACCOUNT from '@salesforce/schema/npe03__Recurring_Donation__c.npe03__Organization__c';
import FIELD_CONTACT from '@salesforce/schema/npe03__Recurring_Donation__c.npe03__Contact__c';
import FIELD_DATE_ESTABLISHED from '@salesforce/schema/npe03__Recurring_Donation__c.npe03__Date_Established__c';
import FIELD_STATUS from '@salesforce/schema/npe03__Recurring_Donation__c.Status__c';
import FIELD_RECURRING_TYPE from '@salesforce/schema/npe03__Recurring_Donation__c.RecurringType__c';
import FIELD_INSTALLMENT from '@salesforce/schema/npe03__Recurring_Donation__c.npe03__Installments__c';
import FIELD_AMOUNT from '@salesforce/schema/npe03__Recurring_Donation__c.npe03__Amount__c';
import FIELD_PAYMENT_METHOD from '@salesforce/schema/npe03__Recurring_Donation__c.PaymentMethod__c';
import FIELD_INSTALLMENT_PERIOD from '@salesforce/schema/npe03__Recurring_Donation__c.npe03__Installment_Period__c';
import FIELD_INSTALLMENT_FREQUENCY from '@salesforce/schema/npe03__Recurring_Donation__c.InstallmentFrequency__c';
import FIELD_DAY_OF_MONTH from '@salesforce/schema/npe03__Recurring_Donation__c.Day_of_Month__c';
import FIELD_START_DATE from '@salesforce/schema/npe03__Recurring_Donation__c.StartDate__c';
import FIELD_CAMPAIGN from '@salesforce/schema/npe03__Recurring_Donation__c.npe03__Recurring_Donation_Campaign__c';

import cancelButtonLabel from '@salesforce/label/c.stgBtnCancel';
import saveButtonLabel from '@salesforce/label/c.stgBtnSave';
import unknownErrorLabel from '@salesforce/label/c.commonUnknownError';
import newHeaderLabel from '@salesforce/label/c.RD2_EntryFormHeader';
import editHeaderLabel from '@salesforce/label/c.commonEdit';
import currencyFieldLabel from '@salesforce/label/c.lblCurrency';
import donationSectionHeader from '@salesforce/label/c.RD2_EntryFormDonationSectionHeader';
import donorSectionHeader from '@salesforce/label/c.RD2_EntryFormDonorSectionHeader';
import otherSectionHeader from '@salesforce/label/c.RD2_EntryFormOtherSectionHeader';
import insertSuccessMessage from '@salesforce/label/c.RD2_EntryFormInsertSuccessMessage';
import updateSuccessMessage from '@salesforce/label/c.RD2_EntryFormUpdateSuccessMessage';

import getSetting from '@salesforce/apex/RD2_entryFormController.getSetting';

export default class rdEntryForm extends LightningElement {

    @api parentId;
    @api recordId;
    listenerEvent = 'rdEntryFormEvent';

    customLabels = Object.freeze({
        cancelButtonLabel,
        saveButtonLabel,
        donationSectionHeader,
        donorSectionHeader,
        otherSectionHeader
    });

    @track fields = {};
    @track record;
    recurringDonationInfo;
    fieldInfos;

    @track isAutoNamingEnabled;
    @track isMultiCurrencyEnabled;

    @track header = newHeaderLabel;

    @track contactId;
    @track accountId;

    @track isLoading = true;

    isSettingReady = false;
    isRecordReady = false;

    @track hasError = false;
    @track errorMessage = {};

    /*******************************************************************************
    * @description Dynamic render edit form CSS to show/hide the edit form
    */
    get cssEditForm() {
        return (this.isLoading && this.isSettingReady && this.isRecordReady)
            ? 'slds-hide'
            : '';
    }

    /*******************************************************************************
    * @description Boolean to control if every server call is loaded
    */
    get isDataReady() {
        return this.isSettingReady && this.isRecordReady;
    }

    /*******************************************************************************
    * @description Get Recurring Donation SObject API name
    */
    get recurringDonationName() {
        return getNestedProperty(RECURRING_DONATION_INFO, 'objectApiName');
    }

    /*******************************************************************************
    * @description Retrieve Recurring Donation Object info
    */
    @wire(getObjectInfo, {objectApiName: '$recurringDonationName' })
    wiredRDObjectInfo(response) {
        if (response.data) {
            this.recurringDonationInfo = response.data;
            this.buildDisplayedFields(this.recurringDonationInfo.fields);
            this.fieldInfos = this.buildFieldDescribesForWiredMethod(
                this.recurringDonationInfo.fields,
                this.recurringDonationInfo.apiName);

            if (!this.recorId) {
                this.isRecordReady = true;
                this.isLoading = false;
            }

        }

        if (response.error) {
            handleError(response.error);
        }
    }

    /*******************************************************************************
    * @description Method converts field describe info into objects that the
    * getRecord method can accept into its 'fields' parameter.
    */
    buildFieldDescribesForWiredMethod(fields, objectApiName) {
        return Object.keys(fields).map((fieldApiName) => {
            return {
                fieldApiName: fieldApiName,
                objectApiName: objectApiName
            }
        });
    }

    /*******************************************************************************
    * @description Contrcut any needed field info from the Sobject Info
    */
    buildDisplayedFields(fieldInfos) {
        this.fields.name = this.extractFieldInfo(fieldInfos[FIELD_NAME.fieldApiName]);
        this.fields.account = this.extractFieldInfo(fieldInfos[FIELD_ACCOUNT.fieldApiName]);
        this.fields.contact = this.extractFieldInfo(fieldInfos[FIELD_CONTACT.fieldApiName]);
        this.fields.recurringType = this.extractFieldInfo(fieldInfos[FIELD_RECURRING_TYPE.fieldApiName]);
        this.fields.dateEstablished = this.extractFieldInfo(fieldInfos[FIELD_DATE_ESTABLISHED.fieldApiName]);
        this.fields.status = this.extractFieldInfo(fieldInfos[FIELD_STATUS.fieldApiName]);
        this.fields.amount = this.extractFieldInfo(fieldInfos[FIELD_AMOUNT.fieldApiName]);
        this.fields.paymentMethod = this.extractFieldInfo(fieldInfos[FIELD_PAYMENT_METHOD.fieldApiName]);
        this.fields.period = this.extractFieldInfo(fieldInfos[FIELD_INSTALLMENT_PERIOD.fieldApiName]);
        this.fields.installmentFrequency = this.extractFieldInfo(fieldInfos[FIELD_INSTALLMENT_FREQUENCY.fieldApiName]);
        this.fields.dayOfMonth = this.extractFieldInfo(fieldInfos[FIELD_DAY_OF_MONTH.fieldApiName]);
        this.fields.startDate = this.extractFieldInfo(fieldInfos[FIELD_START_DATE.fieldApiName]);
        this.fields.campaign = this.extractFieldInfo(fieldInfos[FIELD_CAMPAIGN.fieldApiName]);
        this.fields.currency = {label: currencyFieldLabel, apiName: 'CurrencyIsoCode'};
        this.fields.installment = this.extractFieldInfo(fieldInfos[FIELD_INSTALLMENT.fieldApiName]);
    }

    /*******************************************************************************
    * @description Method converts field describe info into a object that is easily accessiable from the front end
    */
    extractFieldInfo(field) {
        return {
            apiName : field.apiName,
            label : field.label,
            inlineHelpText : field.inlineHelpText,
            dataType : field.dataType
        };
    }

    /*******************************************************************************
    * @description Retrieve Recurring Donation record value
    */
    @wire(getRecord, { recordId: '$recordId', fields: '$fieldInfos' })
    wiredRecurringDonationRecord(response) {
        if (response.data) {
            this.record = response.data;
            this.modidifyEditHeader();

            this.isRecordReady = true;
            this.isLoading = false;
        }

        if (response.error) {
            handleError(response.error);
        }
    }

    /*******************************************************************************
    * @description Modify edit modal header
    */
    modidifyEditHeader() {
        this.header = editHeaderLabel + ' ' + this.record.fields.Name.value;
    }

    async connectedCallback() {
        getSetting({parentId: this.parentId})
        .then(response => {
            this.isAutoNamingEnabled = response.isAutoNamingEnabled;
            this.isMultiCurrencyEnabled = response.isMultiCurrencyEnabled;
            this.handleParentIdType(response.parentSObjectType);
            this.isSettingReady = true;
        })
        .catch((error) => {
            this.handleError(error);
        });
    }

    /*******************************************************************************
    * @description Determine the parentId Sobject Type
    */
    handleParentIdType(parentSObjecType) {
        if (parentSObjecType == null) {
            return;
        }

        if (parentSObjecType === ACCOUNT_OBJECT.objectApiName) {
            this.accountId = this.parentId;
        } else if (parentSObjecType === CONTACT_OBJECT.objectApiName) {
            this.contactId = this.parentId;
        }
    }

    /*******************************************************************************
    * @description Override the standard submit. Add any fields before the submittion
    */
    handleSubmit(event){
        this.isLoading = true;
        event.preventDefault();
        const fields = event.detail.fields;
        this.template.querySelector('lightning-record-edit-form').submit(fields);
        this.template.querySelector("[data-id='submitButton']").disabled = true;
    }

    handleLoad(event) {
        this.isLoading = false;
    }
    /*******************************************************************************
    * @description Handle error
    */
    handleError(error) {
        this.errorMessage.header = unknownErrorLabel;
        let message = unknownErrorLabel;

        // error.body is the error from apex calls
        // error.detail.output.errors is the error from record-edit-forms
        // error.body.output.errors is for AuraHandledException messages
        // error.body.message errors is the error from wired service
        if (typeof error === 'string' || error instanceof String) {
            message = error;

        } else if (error.message) {

            message = error.message;
        } else if ((error.body && error.body.output)) {
            if (Array.isArray(error.body) &&
                !error.body.output.errors) {
                message = error.body.map(e => e.message).join(', ');

            } else if (typeof error.body.message === 'string' &&
                !error.body.output.errors) {
                message = error.body.message;

            } else if (error.body.output &&
                Array.isArray(error.body.output.errors)) {
                message = error.body.output.errors.map(e => e.message).join(', ');

            }
        } else if (error.detail && error.detail.output && Array.isArray(error.detail.output.errors)) {
            this.errorMessage.header = error.detail.message;
            message = error.detail.output.errors.map(e => e.message).join(', ');

        } else if (error.body && error.body.message) {
            message = error.body.message;
        }

        this.errorMessage.detail = message;
        this.isLoading = false
        this.hasError = true;
        this.template.querySelector("[data-id='submitButton']").disabled = false;
    }

    /*******************************************************************************
    * @description Fires an event to utilDedicatedListener with the cancel action
    */
    handleCancel() {
        fireEvent(this.pageRef, this.listenerEvent, { action: 'cancel' });
    }

    /*******************************************************************************
    * @description Fires an event to utilDedicatedListener with the success action
    */
    handleSuccess(event) {
        this.showToast(event.detail.fields.Name.value);
        fireEvent(this.pageRef, this.listenerEvent, { action: 'success', recordId: event.detail.id});
    }

    /*******************************************************************************
    * @description Fires a toast event to display success message
    */
    showToast(recordName) {
        let succeedMessage = (this.recordId)
            ? updateSuccessMessage.replace("{0}", recordName)
            : insertSuccessMessage.replace("{0}", recordName);

        const event = new ShowToastEvent({
            title: succeedMessage,
            variant: 'success',
        });
        this.dispatchEvent(event);
    }
}<commit_msg>error boolean change + add semi column<commit_after>import { LightningElement, api, track, wire } from 'lwc';
import { fireEvent } from 'c/pubsubNoPageRef';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';

import { getNestedProperty } from 'c/utilCommon';
import { getObjectInfo } from 'lightning/uiObjectInfoApi';
import { getRecord} from 'lightning/uiRecordApi';

import RECURRING_DONATION_INFO from '@salesforce/schema/npe03__Recurring_Donation__c';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';
import CONTACT_OBJECT from '@salesforce/schema/Contact';

import FIELD_NAME from '@salesforce/schema/npe03__Recurring_Donation__c.Name';
import FIELD_ACCOUNT from '@salesforce/schema/npe03__Recurring_Donation__c.npe03__Organization__c';
import FIELD_CONTACT from '@salesforce/schema/npe03__Recurring_Donation__c.npe03__Contact__c';
import FIELD_DATE_ESTABLISHED from '@salesforce/schema/npe03__Recurring_Donation__c.npe03__Date_Established__c';
import FIELD_STATUS from '@salesforce/schema/npe03__Recurring_Donation__c.Status__c';
import FIELD_RECURRING_TYPE from '@salesforce/schema/npe03__Recurring_Donation__c.RecurringType__c';
import FIELD_INSTALLMENT from '@salesforce/schema/npe03__Recurring_Donation__c.npe03__Installments__c';
import FIELD_AMOUNT from '@salesforce/schema/npe03__Recurring_Donation__c.npe03__Amount__c';
import FIELD_PAYMENT_METHOD from '@salesforce/schema/npe03__Recurring_Donation__c.PaymentMethod__c';
import FIELD_INSTALLMENT_PERIOD from '@salesforce/schema/npe03__Recurring_Donation__c.npe03__Installment_Period__c';
import FIELD_INSTALLMENT_FREQUENCY from '@salesforce/schema/npe03__Recurring_Donation__c.InstallmentFrequency__c';
import FIELD_DAY_OF_MONTH from '@salesforce/schema/npe03__Recurring_Donation__c.Day_of_Month__c';
import FIELD_START_DATE from '@salesforce/schema/npe03__Recurring_Donation__c.StartDate__c';
import FIELD_CAMPAIGN from '@salesforce/schema/npe03__Recurring_Donation__c.npe03__Recurring_Donation_Campaign__c';

import cancelButtonLabel from '@salesforce/label/c.stgBtnCancel';
import saveButtonLabel from '@salesforce/label/c.stgBtnSave';
import unknownErrorLabel from '@salesforce/label/c.commonUnknownError';
import newHeaderLabel from '@salesforce/label/c.RD2_EntryFormHeader';
import editHeaderLabel from '@salesforce/label/c.commonEdit';
import currencyFieldLabel from '@salesforce/label/c.lblCurrency';
import donationSectionHeader from '@salesforce/label/c.RD2_EntryFormDonationSectionHeader';
import donorSectionHeader from '@salesforce/label/c.RD2_EntryFormDonorSectionHeader';
import otherSectionHeader from '@salesforce/label/c.RD2_EntryFormOtherSectionHeader';
import insertSuccessMessage from '@salesforce/label/c.RD2_EntryFormInsertSuccessMessage';
import updateSuccessMessage from '@salesforce/label/c.RD2_EntryFormUpdateSuccessMessage';

import getSetting from '@salesforce/apex/RD2_entryFormController.getSetting';

export default class rdEntryForm extends LightningElement {

    @api parentId;
    @api recordId;
    listenerEvent = 'rdEntryFormEvent';

    customLabels = Object.freeze({
        cancelButtonLabel,
        saveButtonLabel,
        donationSectionHeader,
        donorSectionHeader,
        otherSectionHeader
    });

    @track fields = {};
    @track record;
    recurringDonationInfo;
    fieldInfos;

    @track isAutoNamingEnabled;
    @track isMultiCurrencyEnabled;

    @track header = newHeaderLabel;

    @track contactId;
    @track accountId;

    @track isLoading = true;

    isSettingReady = false;
    isRecordReady = false;

    @track hasError = false;
    @track errorMessage = {};

    /*******************************************************************************
    * @description Dynamic render edit form CSS to show/hide the edit form
    */
    get cssEditForm() {
        return (this.isLoading && this.isSettingReady && this.isRecordReady)
            ? 'slds-hide'
            : '';
    }

    /*******************************************************************************
    * @description Boolean to control if every server call is loaded
    */
    get isDataReady() {
        return this.isSettingReady && this.isRecordReady;
    }

    /*******************************************************************************
    * @description Get Recurring Donation SObject API name
    */
    get recurringDonationName() {
        return getNestedProperty(RECURRING_DONATION_INFO, 'objectApiName');
    }

    /*******************************************************************************
    * @description Retrieve Recurring Donation Object info
    */
    @wire(getObjectInfo, {objectApiName: '$recurringDonationName' })
    wiredRDObjectInfo(response) {
        if (response.data) {
            this.recurringDonationInfo = response.data;
            this.buildDisplayedFields(this.recurringDonationInfo.fields);
            this.fieldInfos = this.buildFieldDescribesForWiredMethod(
                this.recurringDonationInfo.fields,
                this.recurringDonationInfo.apiName);

            if (!this.recorId) {
                this.isRecordReady = true;
                this.isLoading = false;
            }

        }

        if (response.error) {
            this.isRecordReady = true;
            handleError(response.error);
        }
    }

    /*******************************************************************************
    * @description Method converts field describe info into objects that the
    * getRecord method can accept into its 'fields' parameter.
    */
    buildFieldDescribesForWiredMethod(fields, objectApiName) {
        return Object.keys(fields).map((fieldApiName) => {
            return {
                fieldApiName: fieldApiName,
                objectApiName: objectApiName
            }
        });
    }

    /*******************************************************************************
    * @description Contrcut any needed field info from the Sobject Info
    */
    buildDisplayedFields(fieldInfos) {
        this.fields.name = this.extractFieldInfo(fieldInfos[FIELD_NAME.fieldApiName]);
        this.fields.account = this.extractFieldInfo(fieldInfos[FIELD_ACCOUNT.fieldApiName]);
        this.fields.contact = this.extractFieldInfo(fieldInfos[FIELD_CONTACT.fieldApiName]);
        this.fields.recurringType = this.extractFieldInfo(fieldInfos[FIELD_RECURRING_TYPE.fieldApiName]);
        this.fields.dateEstablished = this.extractFieldInfo(fieldInfos[FIELD_DATE_ESTABLISHED.fieldApiName]);
        this.fields.status = this.extractFieldInfo(fieldInfos[FIELD_STATUS.fieldApiName]);
        this.fields.amount = this.extractFieldInfo(fieldInfos[FIELD_AMOUNT.fieldApiName]);
        this.fields.paymentMethod = this.extractFieldInfo(fieldInfos[FIELD_PAYMENT_METHOD.fieldApiName]);
        this.fields.period = this.extractFieldInfo(fieldInfos[FIELD_INSTALLMENT_PERIOD.fieldApiName]);
        this.fields.installmentFrequency = this.extractFieldInfo(fieldInfos[FIELD_INSTALLMENT_FREQUENCY.fieldApiName]);
        this.fields.dayOfMonth = this.extractFieldInfo(fieldInfos[FIELD_DAY_OF_MONTH.fieldApiName]);
        this.fields.startDate = this.extractFieldInfo(fieldInfos[FIELD_START_DATE.fieldApiName]);
        this.fields.campaign = this.extractFieldInfo(fieldInfos[FIELD_CAMPAIGN.fieldApiName]);
        this.fields.currency = {label: currencyFieldLabel, apiName: 'CurrencyIsoCode'};
        this.fields.installment = this.extractFieldInfo(fieldInfos[FIELD_INSTALLMENT.fieldApiName]);
    }

    /*******************************************************************************
    * @description Method converts field describe info into a object that is easily accessiable from the front end
    */
    extractFieldInfo(field) {
        return {
            apiName : field.apiName,
            label : field.label,
            inlineHelpText : field.inlineHelpText,
            dataType : field.dataType
        };
    }

    /*******************************************************************************
    * @description Retrieve Recurring Donation record value
    */
    @wire(getRecord, { recordId: '$recordId', fields: '$fieldInfos' })
    wiredRecurringDonationRecord(response) {
        if (response.data) {
            this.record = response.data;
            this.modidifyEditHeader();

            this.isRecordReady = true;
            this.isLoading = false;
        }

        if (response.error) {
            this.isRecordReady = true;
            handleError(response.error);
        }
    }

    /*******************************************************************************
    * @description Modify edit modal header
    */
    modidifyEditHeader() {
        this.header = editHeaderLabel + ' ' + this.record.fields.Name.value;
    }

    async connectedCallback() {
        getSetting({parentId: this.parentId})
        .then(response => {
            this.isAutoNamingEnabled = response.isAutoNamingEnabled;
            this.isMultiCurrencyEnabled = response.isMultiCurrencyEnabled;
            this.handleParentIdType(response.parentSObjectType);
            this.isSettingReady = true;
        })
        .catch((error) => {
            this.isSettingReady = true;
            this.handleError(error);
        });
    }

    /*******************************************************************************
    * @description Determine the parentId Sobject Type
    */
    handleParentIdType(parentSObjecType) {
        if (parentSObjecType == null) {
            return;
        }

        if (parentSObjecType === ACCOUNT_OBJECT.objectApiName) {
            this.accountId = this.parentId;
        } else if (parentSObjecType === CONTACT_OBJECT.objectApiName) {
            this.contactId = this.parentId;
        }
    }

    /*******************************************************************************
    * @description Override the standard submit. Add any fields before the submittion
    */
    handleSubmit(event){
        this.isLoading = true;
        event.preventDefault();
        const fields = event.detail.fields;
        this.template.querySelector('lightning-record-edit-form').submit(fields);
        this.template.querySelector("[data-id='submitButton']").disabled = true;
    }

    handleLoad(event) {
        this.isLoading = false;
    }
    /*******************************************************************************
    * @description Handle error
    */
    handleError(error) {
        this.errorMessage.header = unknownErrorLabel;
        let message = unknownErrorLabel;

        // error.body is the error from apex calls
        // error.detail.output.errors is the error from record-edit-forms
        // error.body.output.errors is for AuraHandledException messages
        // error.body.message errors is the error from wired service
        if (typeof error === 'string' || error instanceof String) {
            message = error;

        } else if (error.message) {

            message = error.message;
        } else if ((error.body && error.body.output)) {
            if (Array.isArray(error.body) &&
                !error.body.output.errors) {
                message = error.body.map(e => e.message).join(', ');

            } else if (typeof error.body.message === 'string' &&
                !error.body.output.errors) {
                message = error.body.message;

            } else if (error.body.output &&
                Array.isArray(error.body.output.errors)) {
                message = error.body.output.errors.map(e => e.message).join(', ');

            }
        } else if (error.detail && error.detail.output && Array.isArray(error.detail.output.errors)) {
            this.errorMessage.header = error.detail.message;
            message = error.detail.output.errors.map(e => e.message).join(', ');

        } else if (error.body && error.body.message) {
            message = error.body.message;
        }

        this.errorMessage.detail = message;
        this.isLoading = false;
        this.hasError = true;
        this.template.querySelector("[data-id='submitButton']").disabled = false;
    }

    /*******************************************************************************
    * @description Fires an event to utilDedicatedListener with the cancel action
    */
    handleCancel() {
        fireEvent(this.pageRef, this.listenerEvent, { action: 'cancel' });
    }

    /*******************************************************************************
    * @description Fires an event to utilDedicatedListener with the success action
    */
    handleSuccess(event) {
        this.showToast(event.detail.fields.Name.value);
        fireEvent(this.pageRef, this.listenerEvent, { action: 'success', recordId: event.detail.id});
    }

    /*******************************************************************************
    * @description Fires a toast event to display success message
    */
    showToast(recordName) {
        let succeedMessage = (this.recordId)
            ? updateSuccessMessage.replace("{0}", recordName)
            : insertSuccessMessage.replace("{0}", recordName);

        const event = new ShowToastEvent({
            title: succeedMessage,
            variant: 'success',
        });
        this.dispatchEvent(event);
    }
}<|endoftext|>