Skip to content
main.js 10.7 KiB
Newer Older
(function () {

    var modelNames = ['schemas', 'schemaValues', 'tables', 'tableValues', 'columns', 'columnValues'];

    var models = {};
    var addablesModelCompiled;
    var searchUCDModelCompiled;

    function valuesDirectiveClassFactory(entity, value) {
        return function (ctx) {
            if (ctx.context) {
                var attrValues = ['form-control'];
                if (ctx.context[value].isChanged) {
                    attrValues.push('changed');
                }
                return attrValues.join(' ');
            }
        };
    }

    function getValuesDirective(entity, values) {
        var directive = {};
        for (var i = 0; i < values.length; i++) {
            var value = values[i];
            directive['[data-edit="' + entity + '.' + value + '"]@value'] = value + ".value";
            directive['[data-edit="' + entity + '.' + value + '"]@class'] = valuesDirectiveClassFactory(entity, value);
        return directive;

    function compileModels() {
        for (var i = 0; i < modelNames.length; i++) {
            var name = modelNames[i];
            var directive;
            switch (name) {
                case 'schemas':
                case 'tables':
                    directive = {
                        'li.removable-tab': {
                            'tab<-': {
                                '.entityName': 'tab.title',
                                '@class': function (ctx) {
                                    var attrValues = ['removable-tab'];
                                    if (ctx.item.toRemove) {
                                        attrValues.push('strikeout');
                                    }
                                    if (ctx.item.active) {
                                        attrValues.push('active');
                                    }
                                    return attrValues.join(' ');
                    };
                    break;
                case 'columns':
                    directive = {
                        'li': {
                            'column<-': {
                                '.entityName': 'column.title',
                                '@class': function (ctx) {
                                    return ctx.item.active ? 'active' : '';
                                }
                            }
                    break;
                case 'schemaValues':
                    directive = getValuesDirective('schema', ['utype', 'description']);
                    break;
                case 'tableValues':
                    directive = getValuesDirective('table', ['utype', 'description']);
                    break;
                case 'columnValues':
                    directive = getValuesDirective('column', ['description', 'ucd', 'unit', 'utype']);
                    break;
            }

            models[name] = {
                name: name,
                value: null,
                compiled: $p('#' + name).compile(directive)
            };
        }

        addablesModelCompiled = $p('#addablesModal').compile({
            '.addables': {
                'entity<-': {
                    '.addablesName': 'entity'
            }
        });
        
        searchUCDModelCompiled = $p('#ucdDialog').compile({
            '#UCDnotFoundAlert@class': function(ctx) {
                return ctx.context.UCDnotFound ? '' : 'hide'
            },
            '#selectedUCD@class': function(ctx) {
                return ctx.context.selectedUCD === null ? 'hide' : ''
            },
            '#selectedUCD span': 'selectedUCD',
            '#suggestedUcdResults .result': {
                'ucdInfo<-suggestedUCDs': {
                    '.resultScore': 'ucdInfo.score',
                    '.resultFlag': 'ucdInfo.flag',
                    '.resultWord': 'ucdInfo.word',
                } 
            }
        });
    }

    var entityOf = {
        tapSchema: 'schema',
        schema: 'table',
        table: 'column'
    };

    function renderPage(result) {
        var resultModels = result.elementsToUpdate;
        for (var key in resultModels) {
            var model = models[key];
            model.value = resultModels[key];
            $p('#' + model.name).render(model.value, model.compiled);
        }

        var allStatus = result.status;
        for (var container in allStatus) {
            var status = allStatus[container];
            var entity = entityOf[container];

            $('#' + entity + 'Wrapper').toggle(status.hasChildren);
            $('#' + entity + 'ToRemoveAlert').toggle(status.selectedToRemove);
            $('#' + entity + 'Content').toggle(!status.selectedToRemove);
            $('[data-open-addables="' + container + '"]').toggle(status.hasAddables);
        }
    }

    // container target of current opened addables dialog
    var addablesDialogTarget = null;

    // Page init
    $(document).ready(function () {
        
        // Here only delegates events are used because all elements are dinamically builded in the page.
               
        $('body').on('keyup', '[data-edit]', function (event) {
            $field = $(event.target).closest('[data-edit]');
            var values = $field.attr('data-edit').split('.');
            $.ajax({
                type: "post",
                url: 'webresources/tapschema/edit',
                contentType: 'application/json',
                dataType: 'json',
                data: JSON.stringify({
                    container: values[0],
                    key: values[1],
                    value: $field.val()
                }),
                success: function (res) {
                    $field.toggleClass('changed', res);
            });
        });

        // Search UCD Dialog
        $('body').on('click', '[data-edit="column.ucd"]', function (event) {
            console.log(models.columnValues.value.description.value);
            $.ajax({
                type: "post",
                url: 'webresources/tapschema/searchUCD',
                data: {
                    description: models.columnValues.value.description.value
                },
                dataType: 'json',
                success: function(result) {
                    $p('#ucdDialog').render(result, searchUCDModelCompiled);
                    $('#ucdDialog').modal('show');
            });            
        });

        $('body').on('click', 'a[data-selector]', function (event) {
            $a = $(event.target).closest('a');
            $a.closest('ul').find('li.active').removeClass('active');
            $a.closest('li').addClass('active');
            $.ajax({
                type: "post",
                url: 'webresources/tapschema/select',
                data: {
                    containerName: $a.attr('data-selector'),
                    entityName: $.trim($a.text())
                },
                dataType: 'json',
                success: renderPage
            });
        });

        $('body').on('click', '[data-remover]', function (event) {
            event.preventDefault();
            event.stopPropagation();
            $a = $(event.target).closest('[data-selector]');
            var containerName = $a.attr('data-selector');
            var entityName = $.trim($a.find('.entityName').text());
            $.ajax({
                type: "post",
                url: 'webresources/tapschema/remove',
                data: {
                    containerName: containerName,
                    entityName: entityName
                },
                dataType: 'json',
                success: function (result) {
                    if (containerName === 'table') {
                        renderPage(result.pageModelUpdates);
                        if (result.toRemove) { // column state is TO_REMOVE
                            $a.addClass('strikeout');
                        } else { // column state is NOT_SELECTED
                            $a.closest('ul').find('li:first-child').addClass('active')
                            $a.remove();
                        }
                    } else {
                        renderPage(result);
                    }
        $('body').on('click', '[data-undo-remove]', function (event) {
            $btn = $(event.target).closest('[data-undo-remove]');
            $btn.attr('data-undo-remove');
            $.ajax({
                type: "post",
                url: 'webresources/tapschema/undoremove',
                data: {
                    containerName: $btn.attr('data-undo-remove'),
                },
                dataType: 'json',
                success: renderPage
            });
        });
        $('body').on('click', '[data-open-addables]', function (event) {
            var containerName = $(event.target).closest('[data-open-addables]').attr('data-open-addables');
            $.ajax({
                type: "post",
                url: 'webresources/tapschema/addables',
                data: {
                    containerName: containerName,
                },
                dataType: 'json',
                success: function (res) {
                    $p('#addablesModal').render(res, addablesModelCompiled);
                    $('#addablesModal').modal('show');
                    addablesDialogTarget = containerName;
                }
            });
        });
        $('#addablesModal').on('hidden.bs.modal', function () {
            addablesDialogTarget = null;
        });
        $('body').on('click', '#addEntitiesBtn', function () {
            var selected = [];
            $('#addablesModal .addablesName').each(function (index, element) {
                if ($(element).prev().is(':checked')) {
                    selected.push($.trim($(element).text()));
                }
            });
            $.ajax({
                type: "post",
                url: 'webresources/tapschema/add',
                contentType: 'application/json',
                dataType: 'json',
                data: JSON.stringify({
                    containerName: addablesDialogTarget,
                    entities: selected
                }),
                success: function (result) {
                    renderPage(result);
                    $('#addablesModal').modal('hide');
                }
            });
        });

        compileModels();

        // Init page model
            url: 'webresources/tapschema/model',
            success: renderPage