<commit_before>/*
 * This file is part of the AlphaLemon CMS Application and it is distributed
 * under the GPL LICENSE Version 2.0. To use this application you must leave
 * intact this copyright notice.
 *
 * Copyright (c) AlphaLemon <webmaster@alphalemon.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * For extra documentation and help please visit http://www.alphalemon.com
 *
 * @license    GPL LICENSE Version 2.0
 *
 */

var stopBlocksMenu = false;

(function( $ ){
    $.fn.PlaceTopRight = function(target)
    {
        var $this = $(this);
        var position = target.offset();
        var left = (position.left + target.outerWidth()) - $this.width();
        $this
            .css('position', 'absolute')
            .css('top', position.top)
            .css('left', left)
            .data('parent',target)
        ;

        return this;
    };

    $.fn.StartToEdit = function()
    {
        $('body').addClass('cms_started');

        this.each(function()
        {
            var $this = $(this);
            $this
                .unbind()
                .HideContentsForEditMode()
                .addClass('al_edit_on')
                .mouseenter(function(event)
                {
                    event.stopPropagation();
                    if (stopBlocksMenu) {
                        return;
                    }

                    var position = $this.offset();
                    var blockWidth = $this.outerWidth();
                    var blockHeight = $this.outerHeight();
                    $('#al_block_menu_top')
                        .width(blockWidth)
                        .css('top', position.top + 'px')
                        .css('left', position.left + 'px')
                        .show()
                    ;

                    $('#al_block_menu_bottom')
                        .width(blockWidth)
                        .css('top', position.top + blockHeight + 'px')
                        .css('left', position.left + 'px')
                        .show()
                    ;
                    $('#al_block_menu_left')
                        .height(blockHeight)
                        .css('top', position.top + 'px')
                        .css('left', position.left + 'px')
                        .show()
                    ;
                    $('#al_block_menu_right')
                        .height(blockHeight)
                        .css('top', position.top + 'px')
                        .css('left', position.left + blockWidth + 'px')
                        .show()
                    ;

                    $('#al_block_menu_toolbar')
                        .PlaceTopRight($this)
                        .show()
                    ;

                    $(this).css('cursor', 'pointer');
                })
                .click(function(event){
                    event.stopPropagation();

                    if(stopBlocksMenu) {
                        return;
                    }
                    stopBlocksMenu = true;

                    $this.find('.al_inline_editable').StartInlineEditor($this);
                    $this.find('.al-data-list').StartListEditing();

                    var editableData = $this.metadata();
                    var idBlock = editableData.id;
                    var slotName = editableData.slotName;
                    $('body').data('idBlock', idBlock).data('slotName', slotName).data('activeBlock', $this);
                    $('#al_block_menu_toolbar').hide();

                    $(document).trigger("blockEditing", [ this ]);
                })
            ;

            $(this).find("a").unbind().click(function(event) {
                event.preventDefault();
            });
        });

        return this;
    };

    $.fn.StopToEdit = function(closeEditor)
    {
        if($('body').hasClass('cms_started'))
        {
            var activeBlock = $('body').data('activeBlock');
            if (activeBlock  != null) {
                activeBlock.StopEditBlock();
            }

            if(closeEditor == null) {
                closeEditor = true;
                $("#al_cms_contents a").unbind();
            }

            $('.al_hide_edit_mode').ShowHiddenContentsFromEditMode();
            if (closeEditor) {
                $('#al_editor_dialog').dialog('close');
            }

            this.each(function() {
                $(this).unbind().removeClass('al_edit_on');
            });

            cmsStartInternalJavascripts();
            $('body').removeClass('cms_started');
        }

        return this;
    };

    $.fn.StopEditBlock = function()
    {
        if (stopBlocksMenu) {
            stopBlocksMenu = false;
            $(this)
                .find('.al_inline_editable')
                .each(function(){
                    $(this).popover('destroy');
                })
                .find('.al-data-list')
                .StopListEditing()
            ;

            $(document).trigger("blockStopEditing", [ this ]);
            $('.al_block_menu').hide();
        }

        return this;
    };

    $.fn.StartInlineEditor = function(parent)
    {
        this.each(function(){
            var $this = $(this);
            var options = {
                placement: function () {
                    var position = $this.position();

                    if (position.top + 400 < $('#al_cms_contents').height()){
                        return "bottom";
                    }

                    return "top";
                },
                template: '

'
            }
            $this.popover(options).click(function()
            {
                $('.al-popover:visible').each(function(){
                    var pos = $this.offset();
                    var popover = $(this);

                    var actualWidth = popover.width();
                    var actualLeft = pos.left;

                    if (actualLeft + actualWidth < $('#al_cms_contents').width()) {
                        popover.offset({left: actualLeft}).find('.arrow').css('left', '10%');
                    } else {
                        popover.offset({left: actualLeft + (actualWidth / 5) - actualWidth}).find('.arrow').css('left', '90%');
                    }
                });

                $('.al_editor_save').each(function(){
                    var $this = $(this);
                    $this.unbind().click(function(){
                        $('body').EditBlock('Content', $('#al_item_form').serialize());

                        return false;
                    });
                });
                var data = parent.metadata();
                $(document).trigger("popoverShow", [ data.id, data.type ]);
            });
        });

        return this;
    };

    $.fn.HideContentsForEditMode = function()
    {
        this.each(function() {
            if($(this).hasClass('al_hide_edit_mode')) {
                var data = $(this).metadata();
                $(this).html('
A ' + data.type  + ' block is not renderable in edit mode
').addClass('is_hidden_in_edit_mode');
            }
        });

        return this;
    };

    $.fn.ShowHiddenContentsFromEditMode = function()
    {
        this.each(function()
        {
            if($(this).hasClass('is_hidden_in_edit_mode'))
            {
                $(this).removeClass('is_hidden_in_edit_mode').html(decodeURIComponent($(this).data('block')));
            }
        });
    };

    function ChangeSitePage()
    {
        this.each(function()
        {
            Navigate();
        });
    }
})( jQuery );

function Navigate(language, page)
{
    location.href = frontController + 'backend/' + language + '/' + page;
}

$(document).ready(function(){
    try
    {
        $('#al_cms_contents').click(function(){
            var activeBlock = $('body').data('activeBlock');
            if (activeBlock  != null) {
                activeBlock.StopEditBlock();
            }
        });

        $('.al_language_item').each(function(){
            $(this).click(function()
            {
                Navigate($(this).attr('rel'), $('#al_pages_navigator').html());

                return false;
            });
        });

        $('.al_page_item').each(function(){
            $(this).click(function()
            {
                Navigate($('#al_languages_navigator').html(), $(this).attr('rel'));

                return false;
            });
        });

        $('#al_start_editor').click(function()
        {
            $('.al_editable').StartToEdit();

            return false;
        });

        $('#al_stop_editor').click(function()
        {
            $('.al_editable').trigger("editorStapping").StopToEdit();
            $('.al_block_menu').each(function(){ $(this).hide() });
            $('#al_block_menu_toolbar').hide();
            $('#al_blocks_list').hide();

            return false;
        });

        $("#al_tab a").click(function ()
        {
            $("#al_tab a").toggle();

            return false;
	    });

        $("#al_toggle_edit_buttons a").click(function ()
        {
            $("#al_toggle_edit_buttons a").toggle();

            return false;
	    });

        $("#al_tab .al_tab").click(function ()
        {
            $(".al_tab").toggle();

            return false;
	    });

        $(".al_tab_open").click(function ()
        {
            $("#al_control_panel_body").toggle();
            $('#al_tab').css('top', $("#al_control_panel_body").height() + 'px');

            return false;
	    });

        $(".al_tab_close").click(function ()
        {
            $('#al_tab').css('top', '0');
            $("#al_control_panel_body").toggle();

            return false;
	    });

        $('#al_show_navigation').click(function ()
        {
            $("#al_toggle_nav_button").toggle();

            return false;
	    });

        $('#al_open_users_manager').ListUsers();

        $('#al_logout').click(function()
        {
            location.href = frontController + 'backend/logout';
        });

        $('#al_open_pages_panel').click(function()
        {
            $.ajax({
                type: 'POST',
                url: frontController + 'backend/' + $('#al_available_languages option:selected').val() + '/al_showPages',
                data: {
                    'page' :  $('#al_pages_navigator').html(),
                    'language' : $('#al_languages_navigator').html()
                },
                beforeSend: function()
                {
                    $('body').AddAjaxLoader();
                },
                success: function(html)
                {
                    $('#al_panel').OpenPanel(html, function(){InitPagesCommands();ObservePages();});
                },
                error: function(err)
                {
                    $('body').showDialog(err.responseText);
                },
                complete: function()
                {
                    $('body').RemoveAjaxLoader();
                }
            });

            return false;
        });

        $('#al_open_languages_panel').click(function()
        {
            $.ajax({
                type: 'POST',
                url: frontController + 'backend/' + $('#al_available_languages option:selected').val() + '/al_showLanguages',
                data: {
                    'page' :  $('#al_pages_navigator').html(),
                    'language' : $('#al_languages_navigator').html()
                },
                beforeSend: function()
                {
                    $('body').AddAjaxLoader();
                },
                success: function(html)
                {
                    $('#al_panel').OpenPanel(html, function(){InitLanguagesCommands();ObserveLanguages();});
                },
                error: function(err)
                {
                    $('body').showDialog(err.responseText);
                },
                complete: function()
                {
                    $('body').RemoveAjaxLoader();
                }
            });

            return false;
        });

        $('#al_open_themes_panel').click(function()
        {
            $.ajax({
                type: 'POST',
                url: frontController + 'backend/' + $('#al_available_languages option:selected').val() + '/al_showThemes',
                data: {
                    'page' :  $('#al_pages_navigator').html(),
                    'language' : $('#al_languages_navigator').html()
                },
                beforeSend: function()
                {
                    $('body').AddAjaxLoader();
                },
                success: function(html)
                {
                    $('#al_panel').OpenPanel(html, function(){ObserveThemeCommands();});
                },
                error: function(err)
                {
                    $('body').showDialog(err.responseText);
                },
                complete: function()
                {
                    $('body').RemoveAjaxLoader();
                }
            });

            return false;
        });

        $('#al_open_media_library').click(function()
        {
            $.ajax({
                type: 'POST',
                url: frontController + 'backend/' + $('#al_available_languages option:selected').val() + '/al_showFilesManager',
                data: {'page' :  $('#al_pages_navigator').attr('rel'),
                    'language' : $('#al_languages_navigator').attr('rel')},
                beforeSend: function()
                {
                    $('body').AddAjaxLoader();
                },
                success: function(html)
                {
                    InitDialog('al_editor_dialog_tmp');
                    $('#al_editor_dialog_tmp').html(html);
                    $('#al_editor_dialog_tmp')
                        .dialog('open')
                        .delay(100)
                        .fadeOut(function(){ $(this).dialog("close") })
                    ;
                },
                error: function(err)
                {
                    $('body').showDialog(err.responseText);
                },
                complete: function()
                {
                    $('body').RemoveAjaxLoader();
                }
            });

            return false;
        });

        $('.al_deployer').click(function()
        {
            $.ajax({
                type: 'POST',
                url: frontController + 'backend/' + $('#al_available_languages option:selected').val() + '/al_' + $(this).attr('rel')  + '_deploy',
                data: {'page' :  $('#al_pages_navigator').attr('rel'),
                    'language' : $('#al_languages_navigator').attr('rel')},
                beforeSend: function()
                {
                    $('body').AddAjaxLoader();
                },
                success: function(html)
                {
                    $('body').showAlert(html);
                },
                error: function(err)
                {
                    $('body').showDialog(err.responseText);
                },
                complete: function()
                {
                    $('body').RemoveAjaxLoader();
                }
            });

            return false;
        });
    }
    catch(e)
    {
        alert(e);
    }
});
<commit_msg>a block is highligthed using different styles whe in edit mode; inline blocks are immediatly edited, before it was required and additional click<commit_after>/*
 * This file is part of the AlphaLemon CMS Application and it is distributed
 * under the GPL LICENSE Version 2.0. To use this application you must leave
 * intact this copyright notice.
 *
 * Copyright (c) AlphaLemon <webmaster@alphalemon.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * For extra documentation and help please visit http://www.alphalemon.com
 *
 * @license    GPL LICENSE Version 2.0
 *
 */

var stopBlocksMenu = false;

(function( $ ){
    $.fn.PlaceTopRight = function(target)
    {
        var $this = $(this);
        var position = target.offset();
        var left = (position.left + target.outerWidth()) - $this.width();
        $this
            .css('position', 'absolute')
            .css('top', position.top)
            .css('left', left)
            .data('parent',target)
        ;

        return this;
    };

    $.fn.StartToEdit = function()
    {
        $('body').addClass('cms_started');

        this.each(function()
        {
            var $this = $(this);

            $this
                .find('.al_inline_editable')
                .StartInlineEditor($this)
            ;

            $this
                .unbind()
                .HideContentsForEditMode()
                .addClass('al_edit_on')
                .mouseenter(function(event)
                {
                    event.stopPropagation();
                    if (stopBlocksMenu) {
                        return;
                    }

                    var position = $this.offset();
                    var blockWidth = $this.outerWidth();
                    var blockHeight = $this.outerHeight();
                    $('#al_block_menu_top')
                        .width(blockWidth)
                        .css('top', position.top - 1 + 'px')
                        .css('left', position.left + 'px')
                        .addClass('highlight')
                        .show()
                    ;

                    $('#al_block_menu_bottom')
                        .width(blockWidth)
                        .css('top', position.top + blockHeight + 'px')
                        .css('left', position.left + 'px')
                        .addClass('highlight')
                        .show()
                    ;
                    $('#al_block_menu_left')
                        .height(blockHeight)
                        .css('top', position.top  + 'px')
                        .css('left', position.left - 1 + 'px')
                        .addClass('highlight')
                        .show()
                    ;
                    $('#al_block_menu_right')
                        .height(blockHeight)
                        .css('top', position.top + 'px')
                        .css('left', position.left - 1 + blockWidth + 'px')
                        .addClass('highlight')
                        .show()
                    ;

                    $('#al_block_menu_toolbar')
                        .PlaceTopRight($this)
                        .show()
                    ;

                    $(this).css('cursor', 'pointer');
                })
                .click(function(event){
                    event.stopPropagation();

                    if(stopBlocksMenu) {
                        return;
                    }
                    stopBlocksMenu = true;

                    $('#al_block_menu_top')
                        .addClass('on-editing')
                        .removeClass('highlight')
                    ;

                    $('#al_block_menu_bottom')
                        .addClass('on-editing')
                        .removeClass('highlight')
                    ;

                    $('#al_block_menu_left')
                        .addClass('on-editing')
                        .removeClass('highlight')
                    ;

                    $('#al_block_menu_right')
                        .addClass('on-editing')
                        .removeClass('highlight')
                    ;

                    $this.find('.al-data-list').StartListEditing();

                    var editableData = $this.metadata();
                    var idBlock = editableData.id;
                    var slotName = editableData.slotName;
                    $('body').data('idBlock', idBlock).data('slotName', slotName).data('activeBlock', $this);
                    $('#al_block_menu_toolbar').hide();

                    $(document).trigger("blockEditing", [ this ]);
                })
            ;

            $(this).find("a").unbind().click(function(event) {
                event.preventDefault();
            });
        });

        return this;
    };

    $.fn.StopToEdit = function(closeEditor)
    {
        if($('body').hasClass('cms_started'))
        {
            var activeBlock = $('body').data('activeBlock');
            if (activeBlock  != null) {
                activeBlock.StopEditBlock();
            }

            $('body')
                .find('.al_inline_editable')
                .each(function(){
                    $(this)
                        .popover('destroy')
                    ;
                })
            ;

            if(closeEditor == null) {
                closeEditor = true;
                $("#al_cms_contents a").unbind();
            }

            $('.al_hide_edit_mode').ShowHiddenContentsFromEditMode();
            if (closeEditor) {
                $('#al_editor_dialog').dialog('close');
            }

            this.each(function() {
                $(this).unbind().removeClass('al_edit_on');
            });

            cmsStartInternalJavascripts();
            $('body').removeClass('cms_started');
        }

        return this;
    };

    $.fn.StopEditBlock = function()
    {
        if (stopBlocksMenu) {
            stopBlocksMenu = false;
            var $this = $(this);
            $this
                .find('.al_inline_editable')
                .each(function(){
                    $(this)
                        .popover('destroy')
                    ;
                })
                        .StartInlineEditor($this)
                .find('.al-data-list')
                .StopListEditing();
            ;

            $(document).trigger("blockStopEditing", [ this ]);

            $('#al_block_menu_top')
                .addClass('highlight')
                .removeClass('on-editing')
            ;

            $('#al_block_menu_bottom')
                .addClass('highlight')
                .removeClass('on-editing')
            ;

            $('#al_block_menu_left')
                .addClass('highlight')
                .removeClass('on-editing')
            ;

            $('#al_block_menu_right')
                .addClass('highlight')
                .removeClass('on-editing')
            ;

            $('.al_block_menu').hide();
        }

        return this;
    };

    $.fn.StartInlineEditor = function(parent)
    {
        this.each(function(){
            var $this = $(this);
            var options = {
                placement: function () {
                    var position = $this.position();

                    if (position.top + 400 < $('#al_cms_contents').height()){
                        return "bottom";
                    }

                    return "top";
                },
                template: '

'
            }
            $this.popover(options).click(function()
            {
                $('.al-popover:visible').each(function(){
                    var pos = $this.offset();
                    var popover = $(this);

                    var actualWidth = popover.width();
                    var actualLeft = pos.left;

                    if (actualLeft + actualWidth < $('#al_cms_contents').width()) {
                        popover.offset({left: actualLeft}).find('.arrow').css('left', '10%');
                    } else {
                        popover.offset({left: actualLeft + (actualWidth / 5) - actualWidth}).find('.arrow').css('left', '90%');
                    }
                });

                $('.al_editor_save').each(function(){
                    var $this = $(this);
                    $this.unbind().click(function(){
                        $('body').EditBlock('Content', $('#al_item_form').serialize());

                        return false;
                    });
                });
                var data = parent.metadata();
                $(document).trigger("popoverShow", [ data.id, data.type ]);
            });
        });

        return this;
    };

    $.fn.HideContentsForEditMode = function()
    {
        this.each(function() {
            if($(this).hasClass('al_hide_edit_mode')) {
                var data = $(this).metadata();
                $(this).html('
A ' + data.type  + ' block is not renderable in edit mode
').addClass('is_hidden_in_edit_mode');
            }
        });

        return this;
    };

    $.fn.ShowHiddenContentsFromEditMode = function()
    {
        this.each(function()
        {
            if($(this).hasClass('is_hidden_in_edit_mode'))
            {
                $(this).removeClass('is_hidden_in_edit_mode').html(decodeURIComponent($(this).data('block')));
            }
        });
    };

    function ChangeSitePage()
    {
        this.each(function()
        {
            Navigate();
        });
    }
})( jQuery );

function Navigate(language, page)
{
    location.href = frontController + 'backend/' + language + '/' + page;
}

$(document).ready(function(){
    try
    {
        $('#al_cms_contents').click(function(){
            var activeBlock = $('body').data('activeBlock');
            if (activeBlock  != null) {
                activeBlock.StopEditBlock();
            }
        });

        $('.al_language_item').each(function(){
            $(this).click(function()
            {
                Navigate($(this).attr('rel'), $('#al_pages_navigator').html());

                return false;
            });
        });

        $('.al_page_item').each(function(){
            $(this).click(function()
            {
                Navigate($('#al_languages_navigator').html(), $(this).attr('rel'));

                return false;
            });
        });

        $('#al_start_editor').click(function()
        {
            $('.al_editable').StartToEdit();

            return false;
        });

        $('#al_stop_editor').click(function()
        {
            $('.al_editable').trigger("editorStapping").StopToEdit();
            $('.al_block_menu').each(function(){ $(this).hide() });
            $('#al_block_menu_toolbar').hide();
            $('#al_blocks_list').hide();

            return false;
        });

        $("#al_tab a").click(function ()
        {
            $("#al_tab a").toggle();

            return false;
	    });

        $("#al_toggle_edit_buttons a").click(function ()
        {
            $("#al_toggle_edit_buttons a").toggle();

            return false;
	    });

        $("#al_tab .al_tab").click(function ()
        {
            $(".al_tab").toggle();

            return false;
	    });

        $(".al_tab_open").click(function ()
        {
            $("#al_control_panel_body").toggle();
            $('#al_tab').css('top', $("#al_control_panel_body").height() + 'px');

            return false;
	    });

        $(".al_tab_close").click(function ()
        {
            $('#al_tab').css('top', '0');
            $("#al_control_panel_body").toggle();

            return false;
	    });

        $('#al_show_navigation').click(function ()
        {
            $("#al_toggle_nav_button").toggle();

            return false;
	    });

        $('#al_open_users_manager').ListUsers();

        $('#al_logout').click(function()
        {
            location.href = frontController + 'backend/logout';
        });

        $('#al_open_pages_panel').click(function()
        {
            $.ajax({
                type: 'POST',
                url: frontController + 'backend/' + $('#al_available_languages option:selected').val() + '/al_showPages',
                data: {
                    'page' :  $('#al_pages_navigator').html(),
                    'language' : $('#al_languages_navigator').html()
                },
                beforeSend: function()
                {
                    $('body').AddAjaxLoader();
                },
                success: function(html)
                {
                    $('#al_panel').OpenPanel(html, function(){InitPagesCommands();ObservePages();});
                },
                error: function(err)
                {
                    $('body').showDialog(err.responseText);
                },
                complete: function()
                {
                    $('body').RemoveAjaxLoader();
                }
            });

            return false;
        });

        $('#al_open_languages_panel').click(function()
        {
            $.ajax({
                type: 'POST',
                url: frontController + 'backend/' + $('#al_available_languages option:selected').val() + '/al_showLanguages',
                data: {
                    'page' :  $('#al_pages_navigator').html(),
                    'language' : $('#al_languages_navigator').html()
                },
                beforeSend: function()
                {
                    $('body').AddAjaxLoader();
                },
                success: function(html)
                {
                    $('#al_panel').OpenPanel(html, function(){InitLanguagesCommands();ObserveLanguages();});
                },
                error: function(err)
                {
                    $('body').showDialog(err.responseText);
                },
                complete: function()
                {
                    $('body').RemoveAjaxLoader();
                }
            });

            return false;
        });

        $('#al_open_themes_panel').click(function()
        {
            $.ajax({
                type: 'POST',
                url: frontController + 'backend/' + $('#al_available_languages option:selected').val() + '/al_showThemes',
                data: {
                    'page' :  $('#al_pages_navigator').html(),
                    'language' : $('#al_languages_navigator').html()
                },
                beforeSend: function()
                {
                    $('body').AddAjaxLoader();
                },
                success: function(html)
                {
                    $('#al_panel').OpenPanel(html, function(){ObserveThemeCommands();});
                },
                error: function(err)
                {
                    $('body').showDialog(err.responseText);
                },
                complete: function()
                {
                    $('body').RemoveAjaxLoader();
                }
            });

            return false;
        });

        $('#al_open_media_library').click(function()
        {
            $.ajax({
                type: 'POST',
                url: frontController + 'backend/' + $('#al_available_languages option:selected').val() + '/al_showFilesManager',
                data: {'page' :  $('#al_pages_navigator').attr('rel'),
                    'language' : $('#al_languages_navigator').attr('rel')},
                beforeSend: function()
                {
                    $('body').AddAjaxLoader();
                },
                success: function(html)
                {
                    InitDialog('al_editor_dialog_tmp');
                    $('#al_editor_dialog_tmp').html(html);
                    $('#al_editor_dialog_tmp')
                        .dialog('open')
                        .delay(100)
                        .fadeOut(function(){ $(this).dialog("close") })
                    ;
                },
                error: function(err)
                {
                    $('body').showDialog(err.responseText);
                },
                complete: function()
                {
                    $('body').RemoveAjaxLoader();
                }
            });

            return false;
        });

        $('.al_deployer').click(function()
        {
            $.ajax({
                type: 'POST',
                url: frontController + 'backend/' + $('#al_available_languages option:selected').val() + '/al_' + $(this).attr('rel')  + '_deploy',
                data: {'page' :  $('#al_pages_navigator').attr('rel'),
                    'language' : $('#al_languages_navigator').attr('rel')},
                beforeSend: function()
                {
                    $('body').AddAjaxLoader();
                },
                success: function(html)
                {
                    $('body').showAlert(html);
                },
                error: function(err)
                {
                    $('body').showDialog(err.responseText);
                },
                complete: function()
                {
                    $('body').RemoveAjaxLoader();
                }
            });

            return false;
        });
    }
    catch(e)
    {
        alert(e);
    }
});
<|endoftext|>


<commit_before>(function ($) {
    "use strict";

    $.fn.dataTable.ext.errMode = 'throw';

    $.widget("mapbender.mbDigitizer", $.mapbender.mbDataManager, {

        options: {
            classes: {},
            create: null,
            debug: false,
            fileURI: "uploads/featureTypes",
            schemes: {},
            target: null
        },
        mbMap: null,
        printClient: null,
        active: false,
        controlFactory: null,

        _create: function () {
            this._super();
            var widget = this;
            var target = this.options.target;
            Mapbender.elementRegistry.waitReady(target).then(function(mbMap) {
                widget.mbMap = mbMap;
                widget.setup();
                // Let data manager base method trigger "ready" event and start loading data
                widget._start();
            }, function() {
                Mapbender.checkTarget("mbDigitizer", target);
            });
        },
        _afterCreate: function() {
            // Invoked only by data manager _create
            // do nothing; deliberately do NOT call parent method
        },
        _schemaFactory: function(schemaConfig) {
            var schemaConfig_ = this._super(schemaConfig);
            return new Mapbender.Digitizer.Scheme(schemaConfig_, this);
        },
        setup: function() {
            var self = this;
            Mapbender.elementRegistry.waitCreated('.mb-element-printclient').then(function (printClient) {
                self.printClient = printClient;
                $.extend(self.printClient, Mapbender.Digitizer.printPlugin);
            });
            this.widget = new Mapbender.Digitizer(self.element, self.options);
            this.contextMenu = new Mapbender.Digitizer.MapContextMenu({map: this.mbMap.model.olMap});
            this.controlFactory = new Mapbender.Digitizer.DigitizingControlFactory(this.mbMap.getModel().olMap);
            if (this.options.displayOnInactive) {
                this.activate();
            }
        },
        reveal: function() {
            this.activate();
        },
        hide: function() {
            this.deactivate();
        },
        _initializeEvents: function() {
            this._super();
            var self = this;
            this.element.on('click', '.-fn-toggle-tool[data-toolname]', function() {
                var $button = $(this);
                var toolName = $button.attr('data-toolname');
                var schema = $button.data('schema');
                var oldState = $button.hasClass('active');
                if (!oldState) {
                    var $activeOthers = $('.-fn-toggle-tool.active', $button.siblings()).not($button);
                    $activeOthers.each(function() {
                        var $other = $(this);
                        self._toggleDrawingTool(schema, $other.attr('data-toolname'), false);
                    });
                    $activeOthers.removeClass('active');
                }
                $button.toggleClass('active', !oldState);
                self._toggleDrawingTool(schema, toolName, true);
            });
        },
        activate: function() {
            if (!this.active) {
                this.activateSchema(this.widget.getCurrentSchema());
                this.active = true;
            }
        },
        deactivate: function() {
            var schema = this.widget.getCurrentSchema();
            if (schema) {
                this.deactivateSchema(schema);
            }
            this.active = false;
        },
        _activateSchema: function(schema) {
            this._super(schema);
            schema.activateSchema(); // triggers schema event
            // HACK: externally patch renderer onto schema post-construction
            if (!schema.renderer) {
                schema.renderer = new Mapbender.Digitizer.FeatureRenderer(this.mbMap.getModel().olMap, schema);
            }
            // HACK: externally patch editor onto schema post-construction
            if (schema.allowDigitize && !schema.geometryEditor) {
                var layer = schema.renderer.getLayer();
                schema.geometryEditor = new Mapbender.Digitizer.FeatureEditor(layer, this.controlFactory);
            }

            this._toggleSchemaInteractions(schema, true);
            schema.layer.setVisible(true);
        },
        _toggleDrawingTool: function(schema, toolName, state) {
            var interaction = schema.geometryEditor.getDrawingTool(toolName, schema);
            // @todo: disable selectControl if drawing active and vice-versa
            interaction.setActive(!!state);

        },
        _deactivateSchema: function(schema) {
            this._super(schema);
            schema.deactivateSchema();    // triggers schema event
            this._toggleSchemaInteractions(schema, false);
            if (!(this.options.displayOnInactive || !schema.displayPermanent)) {
                schema.layer.setVisible(false);
            }
        },
        _toggleSchemaInteractions: function(schema, state) {
            if (schema.geometryEditor) {
                schema.geometryEditor.setActive(state);
            }
            schema.highlightControl.setActive(state);
            schema.selectControl.setActive(state);
            if (state && schema.useContextMenu) {
                this.contextMenu.enable();
            } else {
                this.contextMenu.disable();
            }
        },
        _updateToolset: function($container, schema) {
            this._super($container, schema);
            var geomType = schema.featureType.geomType;
            var toolButtonConfigs = schema.toolset || Mapbender.Digitizer.Utilities.getDefaultToolsetByGeomType(geomType);
            for (var i = 0; i < toolButtonConfigs.length; ++i) {
                var rawButton = toolButtonConfigs[i];
                var toolName = rawButton.type;
                var toolExists = typeof (Mapbender.Digitizer.DigitizingControlFactory.prototype[toolName]) === 'function';
                if (!toolExists) {
                    console.warn("interaction " + toolName + " does not exist");
                    continue;
                }
                var iconClass = "icon-" + rawButton.type.replace(/([A-Z])+/g, '-$1').toLowerCase(); // @todo: use font awesome css
                var $icon = $(document.createElement('span')).addClass(iconClass);
                var tooltip = Mapbender.trans('mb.digitizer.toolset.' + geomType + '.' + rawButton.type);
                var $button = $(document.createElement('button'))
                    .attr({
                        type: 'button',
                        'data-toolname': toolName,
                        title: tooltip
                    })
                    .addClass('-fn-toggle-tool')
                    .addClass('btn btn-sm') // match DataManager
                    .append($icon)
                    .data({
                        schema: schema
                    })
                ;
                $container.append($button);
           }
        },
        _buildTableRowButtons: function(schema) {
            var schema_ = this.widget.createScheme_(schema);
            var menu = schema_.menu;
            return menu.generateResultDataTableButtons();
        },

        __formatting_dummy: null
    });

})(jQuery);
<commit_msg>Fix schema activation<commit_after>(function ($) {
    "use strict";

    $.fn.dataTable.ext.errMode = 'throw';

    $.widget("mapbender.mbDigitizer", $.mapbender.mbDataManager, {

        options: {
            classes: {},
            create: null,
            debug: false,
            fileURI: "uploads/featureTypes",
            schemes: {},
            target: null
        },
        mbMap: null,
        printClient: null,
        active: false,
        controlFactory: null,

        _create: function () {
            this._super();
            var widget = this;
            var target = this.options.target;
            Mapbender.elementRegistry.waitReady(target).then(function(mbMap) {
                widget.mbMap = mbMap;
                widget.setup();
                // Let data manager base method trigger "ready" event and start loading data
                widget._start();
            }, function() {
                Mapbender.checkTarget("mbDigitizer", target);
            });
        },
        _afterCreate: function() {
            // Invoked only by data manager _create
            // do nothing; deliberately do NOT call parent method
        },
        _schemaFactory: function(schemaConfig) {
            var schemaConfig_ = this._super(schemaConfig);
            return new Mapbender.Digitizer.Scheme(schemaConfig_, this);
        },
        setup: function() {
            var self = this;
            Mapbender.elementRegistry.waitCreated('.mb-element-printclient').then(function (printClient) {
                self.printClient = printClient;
                $.extend(self.printClient, Mapbender.Digitizer.printPlugin);
            });
            this.widget = new Mapbender.Digitizer(self.element, self.options);
            this.contextMenu = new Mapbender.Digitizer.MapContextMenu({map: this.mbMap.model.olMap});
            this.controlFactory = new Mapbender.Digitizer.DigitizingControlFactory(this.mbMap.getModel().olMap);
            if (this.options.displayOnInactive) {
                this.activate();
            }
        },
        reveal: function() {
            this.activate();
        },
        hide: function() {
            this.deactivate();
        },
        _initializeEvents: function() {
            this._super();
            var self = this;
            this.element.on('click', '.-fn-toggle-tool[data-toolname]', function() {
                var $button = $(this);
                var toolName = $button.attr('data-toolname');
                var schema = $button.data('schema');
                var oldState = $button.hasClass('active');
                if (!oldState) {
                    var $activeOthers = $('.-fn-toggle-tool.active', $button.siblings()).not($button);
                    $activeOthers.each(function() {
                        var $other = $(this);
                        self._toggleDrawingTool(schema, $other.attr('data-toolname'), false);
                    });
                    $activeOthers.removeClass('active');
                }
                $button.toggleClass('active', !oldState);
                self._toggleDrawingTool(schema, toolName, true);
            });
        },
        activate: function() {
            if (!this.active) {
                this.activateSchema(this.widget.getCurrentSchema());
                this.active = true;
            }
        },
        deactivate: function() {
            var schema = this.widget.getCurrentSchema();
            if (schema) {
                this.deactivateSchema(schema);
            }
            this.active = false;
        },
        _activateSchema: function(schema) {
            this._super(schema);
            // HACK: externally patch renderer onto schema post-construction
            if (!schema.renderer) {
                schema.renderer = new Mapbender.Digitizer.FeatureRenderer(this.mbMap.getModel().olMap, schema);
            }
            // HACK: externally patch editor onto schema post-construction
            if (schema.allowDigitize && !schema.geometryEditor) {
                var layer = schema.renderer.getLayer();
                schema.geometryEditor = new Mapbender.Digitizer.FeatureEditor(layer, this.controlFactory);
            }

            this._toggleSchemaInteractions(schema, true);
            schema.layer.setVisible(true);
        },
        _toggleDrawingTool: function(schema, toolName, state) {
            var interaction = schema.geometryEditor.getDrawingTool(toolName, schema);
            // @todo: disable selectControl if drawing active and vice-versa
            interaction.setActive(!!state);

        },
        _deactivateSchema: function(schema) {
            this._super(schema);
            this._toggleSchemaInteractions(schema, false);
            if (!(this.options.displayOnInactive || !schema.displayPermanent)) {
                schema.layer.setVisible(false);
            }
        },
        _toggleSchemaInteractions: function(schema, state) {
            if (schema.geometryEditor) {
                schema.geometryEditor.setActive(state);
            }
            schema.highlightControl.setActive(state);
            schema.selectControl.setActive(state);
            if (state && schema.useContextMenu) {
                this.contextMenu.enable();
            } else {
                this.contextMenu.disable();
            }
        },
        _updateToolset: function($container, schema) {
            this._super($container, schema);
            if (!schema.allowDigitize) {
                return;
            }
            var geomType = schema.featureType.geomType;
            var toolButtonConfigs = schema.toolset || Mapbender.Digitizer.Utilities.getDefaultToolsetByGeomType(geomType);
            for (var i = 0; i < toolButtonConfigs.length; ++i) {
                var rawButton = toolButtonConfigs[i];
                var toolName = rawButton.type;
                var toolExists = typeof (Mapbender.Digitizer.DigitizingControlFactory.prototype[toolName]) === 'function';
                if (!toolExists) {
                    console.warn("interaction " + toolName + " does not exist");
                    continue;
                }
                var iconClass = "icon-" + rawButton.type.replace(/([A-Z])+/g, '-$1').toLowerCase(); // @todo: use font awesome css
                var $icon = $(document.createElement('span')).addClass(iconClass);
                var tooltip = Mapbender.trans('mb.digitizer.toolset.' + geomType + '.' + rawButton.type);
                var $button = $(document.createElement('button'))
                    .attr({
                        type: 'button',
                        'data-toolname': toolName,
                        title: tooltip
                    })
                    .addClass('-fn-toggle-tool')
                    .addClass('btn btn-sm') // match DataManager
                    .append($icon)
                    .data({
                        schema: schema
                    })
                ;
                $container.append($button);
           }
        },
        _buildTableRowButtons: function(schema) {
            var schema_ = this.widget.createScheme_(schema);
            var menu = schema_.menu;
            return menu.generateResultDataTableButtons();
        },

        __formatting_dummy: null
    });

})(jQuery);
<|endoftext|>


<commit_before>const Cookies          = require('js-cookie');
const BinarySocket     = require('../../socket');
const Client           = require('../../../base/client');
const localize         = require('../../../base/localize').localize;
const LocalStore       = require('../../../base/storage').LocalStore;
const urlFor           = require('../../../base/url').urlFor;
const getPropertyValue = require('../../../base/utility').getPropertyValue;
const makeOption       = require('../../../common_functions/common_functions').makeOption;
const jpClient         = require('../../../common_functions/country_base').jpClient;
const FormManager      = require('../../../common_functions/form_manager');
const TrafficSource    = require('../../../common_functions/traffic_source');

const VirtualAccOpening = (() => {
    const form = '#virtual-form';
    let jp_client;

    const onLoad = () => {
        jp_client = jpClient();
        if (jp_client) {
            handleJPForm();
        } else {
            BinarySocket.send({ residence_list: 1 }).then(response => handleResidenceList(response.residence_list));
            $('#residence').setVisibility(1);
            bindValidation();
        }

        FormManager.handleSubmit({
            form_selector       : form,
            fnc_response_handler: handleNewAccount,
        });
    };

    const handleResidenceList = (residence_list) => {
        if (residence_list.length > 0) {
            const $residence      = $('#residence');
            const residence_value = Client.get('residence') || '';

            const $options_with_disabled = $('
');
            residence_list.forEach((res) => {
                $options_with_disabled.append(makeOption({
                    text       : res.text,
                    value      : res.value,
                    is_disabled: res.disabled,
                }));
            });
            $residence.html($options_with_disabled.html());

            if (!residence_value) {
                BinarySocket.wait('website_status').then(data => handleWebsiteStatus(data.website_status));
            }
        }
    };

    const handleWebsiteStatus = (website_status) => {
        const clients_country = (website_status || {}).clients_country;
        if (!clients_country) return;
        const $residence = $('#residence');

        // set residence value to client's country, detected by IP address from back-end
        const $clients_country = $residence.find(`option[value="${clients_country}"]`);
        if (!$clients_country.attr('disabled')) {
            $clients_country.prop('selected', true);
        }
        $residence.setVisibility(1);
    };

    const bindValidation = () => {
        // Add TrafficSource parameters
        const utm_data = TrafficSource.getData();

        const req = [
            { selector: '#client_password', validations: ['req', 'password'], re_check_field: '#repeat_password' },
            { selector: '#repeat_password', validations: ['req', ['compare', { to: '#client_password' }]], exclude_request: 1 },

            { selector: '#residence' },
            { selector: '#email_consent' },
            { request_field: 'utm_source',          value: TrafficSource.getSource(utm_data) },
            { request_field: 'new_account_virtual', value: 1 },
        ];

        if (utm_data.utm_medium)   req.push({ request_field: 'utm_medium',   value: utm_data.utm_medium });
        if (utm_data.utm_campaign) req.push({ request_field: 'utm_campaign', value: utm_data.utm_campaign });

        const gclid = LocalStore.get('gclid');
        if (gclid) req.push({ request_field: 'gclid_url', value: gclid });

        if (Cookies.get('affiliate_tracking')) req.push({ request_field: 'affiliate_token', value: Cookies.getJSON('affiliate_tracking').t });

        FormManager.init(form, req, true);
    };

    const handleJPForm = () => {
        // show email consent field for japanese accounts
        // and don't allow them to change residence
        const $residence = $('#residence');
        $residence.replaceWith($('', { id: 'residence', 'data-value': 'jp', text: localize('Japan') }));
        $('#email_consent').parent().parent().setVisibility(1);
        bindValidation();
    };

    const handleNewAccount = (response) => {
        if (!response) return false;
        const error = response.error;
        if (!error) {
            const new_account = response.new_account_virtual;
            const residence   = response.echo_req.residence;
            Client.set('residence', residence, new_account.client_id);
            LocalStore.remove('gclid');
            BinarySocket.send({ landing_company: residence }).then(() => {
                Client.processNewAccount({
                    email       : new_account.email,
                    loginid     : new_account.client_id,
                    token       : new_account.oauth_token,
                    is_virtual  : true,
                    redirect_url: urlFor(`new_account/${jp_client ? 'landing_page' : 'welcome_page'}`),
                });
            });
            return true;
        }

        const showInvalidTokenMessage = () => {
            const message = 'Your token has expired or is invalid. Please click here to restart the verification process.';
            return showFormError(message, '');
        };

        switch (error.code) {
            case 'InputValidationFailed': {
                return getPropertyValue(response, ['error', 'details', 'verification_code']) ? showInvalidTokenMessage() : showError(error.message);
            }
            case 'InvalidToken': {
                return showInvalidTokenMessage();
            }
            case 'duplicate email': {
                const message = 'The email address provided is already in use. If you forgot your password, please try our password recovery tool or contact our customer service.';
                return showFormError(message, 'user/lost_passwordws');
            }
            case 'PasswordError': {
                return showError('Password is not strong enough.');
            }
            default: {
                return showError(error.message);
            }
        }
    };

    const showFormError = (message, url) => {
        $('#virtual-form').html($('
', { html: localize(message, [urlFor(url)]) }));
    };

    const showError = (message) => {
        $('#error-account-opening').setVisibility(1).text(localize(message));
    };

    return {
        onLoad,
    };
})();

module.exports = VirtualAccOpening;
<commit_msg>reverted back from vrtc to account_type page<commit_after>const Cookies          = require('js-cookie');
const BinarySocket     = require('../../socket');
const Client           = require('../../../base/client');
const localize         = require('../../../base/localize').localize;
const LocalStore       = require('../../../base/storage').LocalStore;
const urlFor           = require('../../../base/url').urlFor;
const getPropertyValue = require('../../../base/utility').getPropertyValue;
const makeOption       = require('../../../common_functions/common_functions').makeOption;
const jpClient         = require('../../../common_functions/country_base').jpClient;
const FormManager      = require('../../../common_functions/form_manager');
const TrafficSource    = require('../../../common_functions/traffic_source');

const VirtualAccOpening = (() => {
    const form = '#virtual-form';
    let jp_client;

    const onLoad = () => {
        jp_client = jpClient();
        if (jp_client) {
            handleJPForm();
        } else {
            BinarySocket.send({ residence_list: 1 }).then(response => handleResidenceList(response.residence_list));
            $('#residence').setVisibility(1);
            bindValidation();
        }

        FormManager.handleSubmit({
            form_selector       : form,
            fnc_response_handler: handleNewAccount,
        });
    };

    const handleResidenceList = (residence_list) => {
        if (residence_list.length > 0) {
            const $residence      = $('#residence');
            const residence_value = Client.get('residence') || '';

            const $options_with_disabled = $('
');
            residence_list.forEach((res) => {
                $options_with_disabled.append(makeOption({
                    text       : res.text,
                    value      : res.value,
                    is_disabled: res.disabled,
                }));
            });
            $residence.html($options_with_disabled.html());

            if (!residence_value) {
                BinarySocket.wait('website_status').then(data => handleWebsiteStatus(data.website_status));
            }
        }
    };

    const handleWebsiteStatus = (website_status) => {
        const clients_country = (website_status || {}).clients_country;
        if (!clients_country) return;
        const $residence = $('#residence');

        // set residence value to client's country, detected by IP address from back-end
        const $clients_country = $residence.find(`option[value="${clients_country}"]`);
        if (!$clients_country.attr('disabled')) {
            $clients_country.prop('selected', true);
        }
        $residence.setVisibility(1);
    };

    const bindValidation = () => {
        // Add TrafficSource parameters
        const utm_data = TrafficSource.getData();

        const req = [
            { selector: '#client_password', validations: ['req', 'password'], re_check_field: '#repeat_password' },
            { selector: '#repeat_password', validations: ['req', ['compare', { to: '#client_password' }]], exclude_request: 1 },

            { selector: '#residence' },
            { selector: '#email_consent' },
            { request_field: 'utm_source',          value: TrafficSource.getSource(utm_data) },
            { request_field: 'new_account_virtual', value: 1 },
        ];

        if (utm_data.utm_medium)   req.push({ request_field: 'utm_medium',   value: utm_data.utm_medium });
        if (utm_data.utm_campaign) req.push({ request_field: 'utm_campaign', value: utm_data.utm_campaign });

        const gclid = LocalStore.get('gclid');
        if (gclid) req.push({ request_field: 'gclid_url', value: gclid });

        if (Cookies.get('affiliate_tracking')) req.push({ request_field: 'affiliate_token', value: Cookies.getJSON('affiliate_tracking').t });

        FormManager.init(form, req, true);
    };

    const handleJPForm = () => {
        // show email consent field for japanese accounts
        // and don't allow them to change residence
        const $residence = $('#residence');
        $residence.replaceWith($('', { id: 'residence', 'data-value': 'jp', text: localize('Japan') }));
        $('#email_consent').parent().parent().setVisibility(1);
        bindValidation();
    };

    const handleNewAccount = (response) => {
        if (!response) return false;
        const error = response.error;
        if (!error) {
            const new_account = response.new_account_virtual;
            const residence   = response.echo_req.residence;
            Client.set('residence', residence, new_account.client_id);
            LocalStore.remove('gclid');
            BinarySocket.send({ landing_company: residence }).then(() => {
                Client.processNewAccount({
                    email       : new_account.email,
                    loginid     : new_account.client_id,
                    token       : new_account.oauth_token,
                    is_virtual  : true,
                    redirect_url: urlFor(`new_account/${jp_client ? 'landing_page' : 'account_type'}`),
                });
            });
            return true;
        }

        const showInvalidTokenMessage = () => {
            const message = 'Your token has expired or is invalid. Please click here to restart the verification process.';
            return showFormError(message, '');
        };

        switch (error.code) {
            case 'InputValidationFailed': {
                return getPropertyValue(response, ['error', 'details', 'verification_code']) ? showInvalidTokenMessage() : showError(error.message);
            }
            case 'InvalidToken': {
                return showInvalidTokenMessage();
            }
            case 'duplicate email': {
                const message = 'The email address provided is already in use. If you forgot your password, please try our password recovery tool or contact our customer service.';
                return showFormError(message, 'user/lost_passwordws');
            }
            case 'PasswordError': {
                return showError('Password is not strong enough.');
            }
            default: {
                return showError(error.message);
            }
        }
    };

    const showFormError = (message, url) => {
        $('#virtual-form').html($('
', { html: localize(message, [urlFor(url)]) }));
    };

    const showError = (message) => {
        $('#error-account-opening').setVisibility(1).text(localize(message));
    };

    return {
        onLoad,
    };
})();

module.exports = VirtualAccOpening;
<|endoftext|>


<commit_before>import autoReducer from './autoReducer';

const testStateObject = {
  active: true,
  tags: ['green', 'happy'],
  attributes: [
    { type: 'level', data: 5 },
    { type: 'stacks', data: [32, 40, 101] },
    {
      type: 'characters',
      data: [
        { name: 'janice' },
        { name: 'george', status: 'missing' },
      ],
    },
  ],
};

describe('autoReducer', () => {
  describe('object transformation', () => {
    it('should return the input object if the transform does not change it', () => {
      const result = autoReducer(testStateObject, { type: 'set', path: ['tags', 1], value: 'happy' });

      expect(result === testStateObject).toBe(true);
    });

    it('should replace the root with an empty path array', () => {
      const result = autoReducer(testStateObject, {
        type: 'set',
        path: [],
        value: { title: 'replacement' },
      });

      expect(result).toEqual({ title: 'replacement' });
    });
    it('should replace the root with an missing path array', () => {
      const result = autoReducer(testStateObject, {
        type: 'set',
        value: { title: 'replacement' },
      });

      expect(result).toEqual({ title: 'replacement' });
    });
  });
  describe('set action type', () => {
    it('should be able to set a value in an object', () => {
      const result = autoReducer(testStateObject, {
        type: 'set',
        path: ['attributes', 2, 'data', 0, 'name'],
        value: 'madeline',
      });

      expect(result.attributes[2].data[0].name).toEqual('madeline');
    });

    it('should be able to add an attribute to an object', () => {
      const result = autoReducer(testStateObject, {
        type: 'set',
        path: ['attributes', 0, 'freq'],
        value: 0.25,
      });

      expect(result.attributes[0]).toEqual({ type: 'level', data: 5, freq: 0.25 });
    });

    it('should be able to add an attribute to an object at a key', () => {
      const result = autoReducer(testStateObject, {
        type: 'set',
        path: ['attributes', 0],
        key: 'freq',
        value: 0.25,
      });

      expect(result.attributes[0]).toEqual({ type: 'level', data: 5, freq: 0.25 });
    });

    it('should be able to set a single value in an array', () => {
      const result = autoReducer(testStateObject, { type: 'set', path: ['tags', 1], value: 'altered' });

      expect(result.tags).toEqual(['green', 'altered']);
    });

    it('should be able to set multiple values in an array', () => {
      const result = autoReducer(testStateObject, {
        type: 'set',
        path: ['tags', [0, 1]],
        value: 'duplicate',
      });

      expect(result.tags).toEqual(['duplicate', 'duplicate']);
    });
  });
  describe('merge action type', () => {
    it('should merge the target object with the provided value', () => {
      const result = autoReducer(testStateObject, {
        type: 'merge',
        path: ['attributes', 0],
        value: { type: 'powerLevel', freq: 0.25 },
      });

      expect(result.attributes[0]).toEqual({ type: 'powerLevel', data: 5, freq: 0.25 });
    });
  });
  describe('omit action type', () => {
    it('should remvove the key from the target object', () => {
      const result = autoReducer(testStateObject, {
        type: 'omit',
        path: ['attributes', 0],
        key: 'data',
      });

      expect(result.attributes[0]).toEqual({ type: 'level' });
    });

    it('should remvove all the keys, if an array is provided, from the target object', () => {
      const result = autoReducer(testStateObject, {
        type: 'omit',
        path: ['attributes', 0],
        key: ['type', 'data'],
      });

      expect(result.attributes[0]).toEqual({ });
    });
  });
  describe('insertAt action type', () => {
    it('should insert a value into an array at an index', () => {
      const result = autoReducer(testStateObject, {
        type: 'insertAt',
        path: ['attributes'],
        index: 1,
        value: { name: 'new item' },
      });

      expect(result.attributes).toHaveLength(4);
      expect(result.attributes[1]).toEqual({ name: 'new item' });
    });
  });
  describe('removeAt action type', () => {
    it('should remove a value from an array at an index', () => {
      const result = autoReducer(testStateObject, {
        type: 'removeAt',
        path: ['attributes'],
        index: 1,
      });

      expect(result.attributes).toHaveLength(2);
      expect(result.attributes[1]).toEqual({
        type: 'characters',
        data: [
          { name: 'janice' },
          { name: 'george', status: 'missing' },
        ],
      });
    });
  });
  describe('insertFirst action type', () => {
    it('should add an item to the start of an array', () => {
      const result = autoReducer(testStateObject, {
        type: 'insertFirst',
        path: ['attributes'],
        value: { name: 'new item' },
      });

      expect(result.attributes).toHaveLength(4);
      expect(result.attributes[0]).toEqual({ name: 'new item' });
    });
  });
  describe('removeFirst action type', () => {
    it('should remove an item to the start of an array', () => {
      const result = autoReducer(testStateObject, {
        type: 'removeFirst',
        path: ['attributes'],
      });

      expect(result.attributes).toHaveLength(2);
      expect(result.attributes[0]).toEqual({ type: 'stacks', data: [32, 40, 101] });
    });
  });
  describe('insertLast action type', () => {
    it('should insert an item at the end of an array', () => {
      const result = autoReducer(testStateObject, {
        type: 'insertLast',
        path: ['attributes'],
        value: { name: 'new item' },
      });

      expect(result.attributes).toHaveLength(4);
      expect(result.attributes[3]).toEqual({ name: 'new item' });
    });
  });
  describe('removeLast action type', () => {
    it('should insert an item at the end of an array', () => {
      const result = autoReducer(testStateObject, {
        type: 'removeLast',
        path: ['attributes'],
      });

      expect(result.attributes).toHaveLength(2);
      expect(result.attributes[1]).toEqual({ type: 'stacks', data: [32, 40, 101] });
    });
  });
});
<commit_msg>tweak some test names<commit_after>import autoReducer from './autoReducer';

const testStateObject = {
  active: true,
  tags: ['green', 'happy'],
  attributes: [
    { type: 'level', data: 5 },
    { type: 'stacks', data: [32, 40, 101] },
    {
      type: 'characters',
      data: [
        { name: 'janice' },
        { name: 'george', status: 'missing' },
      ],
    },
  ],
};

describe('autoReducer', () => {
  describe('object transformation', () => {
    it('should return the input object if the transform does not change it', () => {
      const result = autoReducer(testStateObject, { type: 'set', path: ['tags', 1], value: 'happy' });

      expect(result === testStateObject).toBe(true);
    });

    it('should replace the root with an empty path array', () => {
      const result = autoReducer(testStateObject, {
        type: 'set',
        path: [],
        value: { title: 'replacement' },
      });

      expect(result).toEqual({ title: 'replacement' });
    });
    it('should replace the root with an missing path array', () => {
      const result = autoReducer(testStateObject, {
        type: 'set',
        value: { title: 'replacement' },
      });

      expect(result).toEqual({ title: 'replacement' });
    });
  });
  describe('set action', () => {
    it('should be able to set a value in an object', () => {
      const result = autoReducer(testStateObject, {
        type: 'set',
        path: ['attributes', 2, 'data', 0, 'name'],
        value: 'madeline',
      });

      expect(result.attributes[2].data[0].name).toEqual('madeline');
    });

    it('should be able to add an attribute to an object', () => {
      const result = autoReducer(testStateObject, {
        type: 'set',
        path: ['attributes', 0, 'freq'],
        value: 0.25,
      });

      expect(result.attributes[0]).toEqual({ type: 'level', data: 5, freq: 0.25 });
    });

    it('should be able to add an attribute to an object at a key', () => {
      const result = autoReducer(testStateObject, {
        type: 'set',
        path: ['attributes', 0],
        key: 'freq',
        value: 0.25,
      });

      expect(result.attributes[0]).toEqual({ type: 'level', data: 5, freq: 0.25 });
    });

    it('should be able to set a single value in an array', () => {
      const result = autoReducer(testStateObject, { type: 'set', path: ['tags', 1], value: 'altered' });

      expect(result.tags).toEqual(['green', 'altered']);
    });

    it('should be able to set multiple values in an array', () => {
      const result = autoReducer(testStateObject, {
        type: 'set',
        path: ['tags', [0, 1]],
        value: 'duplicate',
      });

      expect(result.tags).toEqual(['duplicate', 'duplicate']);
    });
  });
  describe('merge action', () => {
    it('should merge the target object with the provided value', () => {
      const result = autoReducer(testStateObject, {
        type: 'merge',
        path: ['attributes', 0],
        value: { type: 'powerLevel', freq: 0.25 },
      });

      expect(result.attributes[0]).toEqual({ type: 'powerLevel', data: 5, freq: 0.25 });
    });
  });
  describe('omit action', () => {
    it('should remvove the key from the target object', () => {
      const result = autoReducer(testStateObject, {
        type: 'omit',
        path: ['attributes', 0],
        key: 'data',
      });

      expect(result.attributes[0]).toEqual({ type: 'level' });
    });

    it('should remvove all the keys, if an array is provided, from the target object', () => {
      const result = autoReducer(testStateObject, {
        type: 'omit',
        path: ['attributes', 0],
        key: ['type', 'data'],
      });

      expect(result.attributes[0]).toEqual({ });
    });
  });
  describe('insertAt action', () => {
    it('should insert a value into an array at an index', () => {
      const result = autoReducer(testStateObject, {
        type: 'insertAt',
        path: ['attributes'],
        index: 1,
        value: { name: 'new item' },
      });

      expect(result.attributes).toHaveLength(4);
      expect(result.attributes[1]).toEqual({ name: 'new item' });
    });
  });
  describe('removeAt action', () => {
    it('should remove a value from an array at an index', () => {
      const result = autoReducer(testStateObject, {
        type: 'removeAt',
        path: ['attributes'],
        index: 1,
      });

      expect(result.attributes).toHaveLength(2);
      expect(result.attributes[1]).toEqual({
        type: 'characters',
        data: [
          { name: 'janice' },
          { name: 'george', status: 'missing' },
        ],
      });
    });
  });
  describe('insertFirst action', () => {
    it('should add an item to the start of an array', () => {
      const result = autoReducer(testStateObject, {
        type: 'insertFirst',
        path: ['attributes'],
        value: { name: 'new item' },
      });

      expect(result.attributes).toHaveLength(4);
      expect(result.attributes[0]).toEqual({ name: 'new item' });
    });
  });
  describe('removeFirst action', () => {
    it('should remove an item to the start of an array', () => {
      const result = autoReducer(testStateObject, {
        type: 'removeFirst',
        path: ['attributes'],
      });

      expect(result.attributes).toHaveLength(2);
      expect(result.attributes[0]).toEqual({ type: 'stacks', data: [32, 40, 101] });
    });
  });
  describe('insertLast action', () => {
    it('should insert an item at the end of an array', () => {
      const result = autoReducer(testStateObject, {
        type: 'insertLast',
        path: ['attributes'],
        value: { name: 'new item' },
      });

      expect(result.attributes).toHaveLength(4);
      expect(result.attributes[3]).toEqual({ name: 'new item' });
    });
  });
  describe('removeLast action', () => {
    it('should insert an item at the end of an array', () => {
      const result = autoReducer(testStateObject, {
        type: 'removeLast',
        path: ['attributes'],
      });

      expect(result.attributes).toHaveLength(2);
      expect(result.attributes[1]).toEqual({ type: 'stacks', data: [32, 40, 101] });
    });
  });
});
<|endoftext|>


<commit_before>import { Behavior } from '../behavior.js';

export class BehaviorOrigin extends Behavior {

    constructor(options, valueMap) {
        super();
        this.options = options;
        this.valueMap = valueMap;
    }

    process() {
        let lua = [];

        if (this.options.originType === 'CUSTOMER') {
            lua.push('ngx.var.aka_origin_host = ' + this.value(this.options.hostname));

            let forwardHostHeader = this.switchByVal({
                'ORIGIN_HOSTNAME': this.value(this.options.hostname),
                'REQUEST_HOST_HEADER': 'mapValue(aka_request_host)'
            }, 'aka_request_host', this.options.forwardHostHeader);

            lua.push('ngx.var.aka_origin_host_header = ' + forwardHostHeader);

            if (this.options.enableTrueClientIp) {
                // True-Client-IP request header is set by nginx-edge.conf and passed on here
                lua.push('aka_upstream_headers["' + this.options.trueClientIpHeader + '"] = ' +
                    'ngx.req.get_headers()["True-Client-IP"]');
            }

        } else {
            lua.push('-- unsupported origin type: ' + this.options.originType);
        }

        return lua;
    }
}
Behavior.register('origin', BehaviorOrigin);

<commit_msg>feat(behavior): add support for origin customForwardHostHeader with vars<commit_after>import { Behavior } from '../behavior.js';

export class BehaviorOrigin extends Behavior {

    constructor(options, valueMap) {
        super();
        this.options = options;
        this.valueMap = valueMap;
    }

    process() {
        let lua = [];

        if (this.options.originType === 'CUSTOMER') {
            lua.push('ngx.var.aka_origin_host = ' + this.value(this.options.hostname));

            let forwardHostHeader = this.switchByVal({
                'ORIGIN_HOSTNAME': this.value(this.options.hostname),
                'REQUEST_HOST_HEADER': 'mapValue(aka_request_host)',
                'CUSTOM': this.value(this.options.customForwardHostHeader)
            }, this.value(this.options.hostname), this.options.forwardHostHeader);

            lua.push('ngx.var.aka_origin_host_header = ' + forwardHostHeader);

            if (this.options.enableTrueClientIp) {
                // True-Client-IP request header is set by nginx-edge.conf and passed on here
                lua.push('aka_upstream_headers["' + this.options.trueClientIpHeader + '"] = ' +
                    'ngx.req.get_headers()["True-Client-IP"]');
            }

        } else {
            lua.push('-- unsupported origin type: ' + this.options.originType);
        }

        return lua;
    }
}
Behavior.register('origin', BehaviorOrigin);

<|endoftext|>