2
\$\begingroup\$

I have a Spring app that is used to create patches for another application. My client retrieves a list of branches from a SVN repo through the initial AJAX call, then if one branch is chosen, another AJAX call returns the tags associated with the specific branch. When a tag is selected, a list of commits is shown after being returned by another AJAX call. The user can select multiple commits and generate a patch description by clicking on a submit button that also uses an AJAX call to the server. The app also can show the commits grouped by akuiteo numbers (which are a kind of JIRA like files).

I am new to front end development and to JavaScript, I am learning it on the fly so I chose to firstly go with javascript+JQuery instead of any framework, such as Angular or react, because my app doesn't have so many interactive features.

My script is mostly making AJAX calls to Spring MVC controllers(as mapped by the url parameter in the AJAX calls) and printing the results.

I feel though that my code is rather messy as I am not well accustomed to the JavaScript syntax or form.

var branch;
var branches=[];
var tag;
var tags=[];
var commits=[];
//var akuiteo=[];
var selectedCommits=[];

function getBranches(){
    $.ajax({
       url: 'branch',
       dataType: 'json',
       success: function (data) {
           branches=data;
           printBranches(branches);
       },
       error: function (data) {
           $('.branches').html('<p> error </p>');
       }
    });
}

function printBranches(branches){
    for(i=0;i<branches.length;i++){
           $('.branches').append($('<option>',{
               value: branches[i].name,
               text: branches[i].name,
               class: "form-control"
           }));
       }
}

function getTags(branch){
    $.ajax({
        url: 'tag',
        dataType: 'json',
        data:{
            branch: branch,
        },
        success: function(data){
            tags=data;
            printTags(tags);
        }
    });
}

function printTags(tags){
    $.each(tags,function(i,tag){
        $('.tags').append($('<option>',{
            value: tag.name,
            text: tag.name,
            class: "form-control"
        }));
    });
}

function getCommitDescription(commit,akuiteo,i){
    lines = commit.comment.match(/[^\r\n]+/g);
    if(!akuiteo)
        var list='<ul id="commitComment'+i+'">';
    else 
        var list='<ul id="commitCommentAkuiteo'+i+'">';
    list+='Revision: '+commit.revision;
    list+='<li> Made on: '+commit.date+'</li>';
    for(j=0;j<lines.length;j++){
        list+='<li>'+lines[j]+'</li>';
    }
    list+='</ul>';
    return list;
}

function getCommits(branch, tag){
    $.ajax({
        url: 'commit',
        dataType: 'json',
        data:{
            branch: branch,
            tag: tag,
        },
        success: function(data){
            commits=data;
            $('.commits').empty();
            $('.akuiteo').empty();
            if (data.length==0){
                $('.commits').append('<p>There are no commits for this     tag</p>');
                $('.akuiteo').append('<p>There are no akuiteo files for this     tag</p>');
            }
            else{
                printCommits(commits);
            }
            //ajax call for akuiteo Map
            getAkuiteoMap(commits);
        }
    });
}



function getAkuiteoMap(commits){
    $.ajax({
        url: 'akuiteoMap',
        method: 'POST',
        dataType: 'json',
        contentType: 'application/json',
        data : JSON.stringify(commits),
        success: function(data){
            akuiteo=data;
            printAkuiteo(akuiteo);
        }
    })
}

function printAkuiteo(akuiteo){
console.log(akuiteo);
$('.akuiteo').empty();
akuiteoMap=akuiteo.akuiteoMap;
let i=1;
for(var key in akuiteoMap){
    console.log('i='+i);
    console.log('key: '+key+' values: '+akuiteoMap[key]);
    $('<li>',{
        class:"list-group-item akuiteo-list-item list-group",
        id:'akuiteo'+i,
        text:'Akuiteo file number: '+key,
    }).appendTo($('.akuiteo'));
    let j=1;
    for(var key2 in akuiteoMap[key]){
        console.log('j='+j);
        console.log(akuiteoMap[key][key2]);
        commitDescription=getCommitDescription(akuiteoMap[key][key2],true,""+i+j);
        $('<button>',{
            class:'list-group-item list-group-item-action akuiteo-commit-list-item',
            id:'commitAkuiteo'+i+j,
        }).appendTo($('#akuiteo'+i));
        $('#commitAkuiteo'+i+j).append(commitDescription);
        $('#commitCommentAkuiteo'+i+j).append($('<span>',{
            class:'badge',
            id:'badgeAkuiteo'+i+j,
            text:'changed files:'+akuiteoMap[key][key2].changedPathList.length
        }));
        $('#badgeAkuiteo'+i+j).attr('data-toggle','collapse');
        $('#badgeAkuiteo'+i+j).attr('data-target','#ulAkuiteo'+i+j);
        $('#commitAkuiteo'+i+j).append($('<ul>',{
            class:'list-group changed-files-list collapse',
            id:'ulAkuiteo'+i+j,
        }));
        for(k=0;k<akuiteoMap[key][key2].changedPathList.length;k++){
            $('<li>',{
                class:'list-group-item changed-file',
                text:akuiteoMap[key][key2].changedPathList[k].path,
            }).appendTo($('#ulAkuiteo'+i+j));
        };
        j++;
    }
    i++;
}
}

function printCommits(commits){
for(i=0;i<commits.length;i++){
    commitDescription=getCommitDescription(commits[i],false,i);
    $('<button>',{
        class:"commit-list-item list-group-item list-group-item-action",
        id:'commit'+i,
    }).appendTo($('.commits'));
    $('#commit'+i).append(commitDescription);
    $('#commitComment'+i).append($('<span>',{
        class:'badge',
        id:'badge'+i,
        text:'changed files:'+commits[i].changedPathList.length
    }));
    $('#badge'+i).attr('data-toggle','collapse');
    $('#badge'+i).attr('data-target','#ul'+i);
    $('#commit'+i).append($('<ul>',{
        class:'list-group changed-files-list collapse',
        id:'ul'+i,
    }));
    for(j=0;j<commits[i].changedPathList.length;j++){
        $('<li>',{
            class:'list-group-item changed-file',
            text:commits[i].changedPathList[j].path,
        }).appendTo($('#ul'+i));
    };
};
$('.list-group-item-action.commit-list-item').on('click', function(e){
    if($(this).hasClass('active')){
        $(this).removeClass('active');
    }
    else
        $(this).toggleClass('active');
    selectedCommits = [];
    var counter=0;
    $('.list-group-item.active.commit-list-item').each(function(){
        counter++;
        selectedCommits.push(commits[this.id.substring(6)]);
    });
    if(counter!=0){
        $('#buttonCommit').prop('disabled', false);
    }
    else{
        $('#buttonCommit').prop('disabled', true);
    }
});

$('.badge').click( function(e){
    $('#ul'+this.id.substring(5)).collapse("toggle");
    e.stopPropagation();
});
}

function getPatch(selectedCommits){
$.ajax({
    url:'selectedCommits?branch='+branch+'&tag='+tag,
    method: 'POST',
    dataType: 'json',
    contentType: 'application/json',
    data:JSON.stringify(selectedCommits),
    success:function(data){
        sessionStorage.removeItem("selectedCommits");
        sessionStorage.removeItem("commits");
        sessionStorage.removeItem("branch");
        sessionStorage.removeItem("tag");
        sessionStorage.setItem("selectedCommits",JSON.stringify(selectedCommits));
        sessionStorage.setItem("commits", JSON.stringify(data));
        sessionStorage.setItem("branch",branch);
        sessionStorage.setItem("tag",tag);
        alert('Patch details generated!');
        window.location.href="/patchdetails";
    }
})
}

function updateBranchMap(){
$("#updateMapButton").prop('disabled',true);
$.ajax({
    url: 'asyncUpdateBranchMap',
    method: 'GET',
    dataType: 'json',
    complete: function (data) {
        alert("Branch map JSON updated");
        $("#button").prop('disabled',true);
    },
 });
}

//on document load up
$(document).ready(function() {
    $('#buttonCommit').prop('disabled', true);
    getBranches();
});

//on branch change
$('.branches').on('change',function(){
    $('#buttonCommit').prop('disabled', true);
    branch=this.value;
    $('.tags').empty();
    tags=[];
    $('.tags').html('<option value="0" disabled="disabled" selected="selected">Please select a tag</option>');
    $('.tags').prop('disabled',this.value=="0");
    $('.commits').empty();
    commits=[];
    $('.commits').append('<p>Please select a tag</p>');
    $('.akuiteo').empty();
    akuiteo=[];
    $('.akuiteo').append('<p>Please select a tag</p>');
    getTags(branch);
});

//on tag change
$('.tags').on('change',function(){
    tag=this.value;
    $('#buttonCommit').prop('disabled', true);
    $('.commits').empty();
    $('.akuiteo').empty();
    $('.commits').append('<p>Commit list loading</p>');
    $('.akuiteo').append('<p>Akuiteo list loading</p>');
    commits=[];
    akuiteo=[];
    getCommits(branch, tag);
});


//on prepare button click
$("#buttonCommit").click(function(e){
    $("#buttonCommit").prop('disabled',true);
    $('.form-group').append('<p>Generating patch details...</p>');
    getPatch(selectedCommits);
});

//on update branch button click
$("#updateMapButton").click(function (e){
    updateBranchMap();
});

What can I do to improve the readability of this code? How can I separate it into more functional bits? I feel like I am building something that is not well sustainable for the future as it is in the current form.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.