<commit_before>// View model for the courses page
function pageViewModel(gvm) {
    // Page specific i18n bindings
    gvm.app  = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectRapportName")}, gvm);
    gvm.title = ko.computed(function(){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("CourseTitle2");}, gvm);
    gvm.pageHeader = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("CourseTitle2");}, gvm);
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectRapportName");}, gvm);

    gvm.availableLocations = ko.observableArray([]);
    gvm.availableTrainings = ko.observableArray([]);
    gvm.availableCourses = ko.observableArray([]);
    // Pagination i18n bindings
    gvm.addBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AddBtn")}, gvm);

    gvm.codeTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("CodeTableTitle");}, gvm);
    gvm.nameTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("NameTableTitle");}, gvm);
    gvm.descTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("DescTableTitle");}, gvm);
    gvm.actionTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ActionTableTitle");}, gvm);

    // The table data observable array
    gvm.tabledata = ko.observableArray([]);

    // Add data to the table
    gvm.addTableData = function(id, code, name, desc) {
        console.log(id + ", " + code + ", " + name + ", " + desc);
        // Push data
        var tblOject = {tid: id, tcode: code, tname: name, tdesc: desc};
        gvm.tabledata.push(tblOject);

        // Attach delete handler to delete button
        $('#removebtn-' + id).bind('click', function(event, data){
            // Delete the table item
            deleteTableItem(id, tblOject);
            event.stopPropagation();
        });

        // Attach edit handler to edit button
        $('#editbtn-' + id).bind('click', function(event, data){
            // Edit the table item
            showEditProjectTypeModal(code, name, desc, id);
            event.stopPropagation();
        });

        //Attach manage handler to manage competences, subcompetences and indicators to manage button
        $('#managebtn-' + id).bind('click', function(event, data) {
            //TODO
        });

        /*$('#studentbtn-' + id).bind('click', function(event, data) {
            showCoupleStudentListModal(id);
            gvm.currentprojectid = id;
            gvm.currentselectedlist = -1;
            event.stopPropagation();
            loadCoupleDropdown();
        });*/
    }

    gvm.clearTable = function() {
        gvm.tabledata.removeAll();
    }
    }
/*
 * Delete item from table given the id.
 */
function deleteTableItem(id, tblOject) {
    showYesNoModal("Bent u zeker dat u dit item wil verwijderen?", function(val){
        if(val){
            $.ajax({
                url: "/api/coursedelete/" + id,
                type: "DELETE",
                success: function() {
                    viewModel.tabledata.remove(tblOject);
                }
            });
        }
    });
}

/*
 * Add a new projecttype
 */
function addNewProjecttypeForm(serialData, callback) {
    $.ajax({
            url: "/api/courserapport",
            type: "POST",
            data: serialData,
            success: function(data) {
                viewModel.addTableData(data['id'], data['code'], data['name'], data['description']);
                callback(true);
            },
            error: function(data) {
                callback(false);
            }
        });
}

/*
 * Add a new projecttype
 */
function addNewProjecttypeRaw(code, name, description, callback) {
    addNewProjecttypeForm("code=" + encodeURIComponent(code) + "&name=" + encodeURIComponent(name) + "&description=" + encodeURIComponent(description), callback);
}

/*
 * Update the projecttype
 * @param {type} id
 * @param {type} code
 * @param {type} name
 * @param {type} description
 * @param {type} callback
 * @returns {undefined}
 */
function updateProjecttypeForm(id, serialData, callback) {
    $.ajax({
        url: "/api/courseupdate/" + id,
        type: "PUT",
        data: serialData,
        success: function(data) {
            //var tblOject = {tid: data['id'], tcode: data['code'], tname: data['name'], tdesc: data['description']};
            //viewModel.addTableData(data['id'], data['code'], data['name'], data['description']);
            loadTablePage(viewModel.currentCourseId); //TODO now it is refreshing table after updating but it redirects to pagenr 1
            callback(true);
        },
        error: function(data) {
            callback(false);
        }
    });
}

/**
 * update project type
 * @param {type} id
 * @param {type} code
 * @param {type} name
 * @param {type} description
 * @param {type} callback
 * @returns {undefined}
 */
function updateProjecttypeRaw(id, code, name, description, callback) {
    updateProjecttypeForm(id, "code=" + encodeURIComponent(code) + "&name=" + encodeURIComponent(name) + "&description=" + encodeURIComponent(description), callback);
}

/*
 * Load page of the table
 */
function loadTablePage(pagenr)
{
    console.log('im in loadTablePage');
    $.getJSON('/api/coursesrapport/page/' + pagenr, function(data){

        /* Clear current table page */
        viewModel.clearTable();

        // Load table data
        $.each(data.data, function(i, item) {
            console.log(item.name);
            viewModel.addTableData(item.id, item.code, item.name, item.description);
        });

        /* Let previous en next buttons work */
        if(data.prev == "none"){
            $('#pager-prev-btn').addClass('disabled');
        } else {
            $('#pager-prev-btn').removeClass('disabled');
            $('#pager-prev-btn a').click(function(){
                loadTablePage(data.prev);
            });
        }

        if(data.next == "none"){
            $('#pager-next-btn').addClass('disabled');
        } else {
            $('#pager-next-btn').removeClass('disabled');
            $('#pager-next-btn a').click(function(){
                loadTablePage(data.next);
            });
        }

        // Number of pager buttons
        var numItems = $('.pager-nr-btn').length;

        /* Calculate for the pager buttons */
        var lowPage = Math.floor(pagenr/numItems) + 1;

        $('.pager-nr-btn').each(function() {
            /* calculate current page number */
            var thispagenr = lowPage++;

            /* Add the page number */
            $(this).html('' + thispagenr + '');

            /* Add active class to current page */
            if(thispagenr == pagenr) {
                $(this).addClass('active');
            } else {
                $(this).removeClass('active');
            }

            /* Disable inactive classes and bind handlers to active classes */
            if(thispagenr > data.pagecount) {
                $(this).addClass('disabled');
            } else {
                /* Add click listener for button */
                $(this).click(function() {
                    loadTablePage(thispagenr);
                });
            }
        });
    });

}

/**
 * Show a new projecttype modal.
 * @returns {undefined}
 */
function showNewProjectTypeModal()
{
    resetGeneralModal();
    setGeneralModalTitle(i18n.__("AddNewCourse"));
    setGeneralModalBody('<form id="newprojectform"> \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('CodeTableTitle') + '" " name="code"> \

 \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('NameTableTitle') + '" name="name"> \

 \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('DescTableTitle') + '" name="description"> \

 \

 \
                <button class="btn btn-wide btn-default dropdown-toggle" type="button" id="teacher" data-toggle="dropdown" aria-expanded="true" placeholder="' + i18n.__('TeacherTableTitle') + '" name="teacher"> \
                    Teacher \
                     \
                </button> \

 \
        </form>');

    addGeneralModalButton(i18n.__("AddBtn"), function(){
        console.log($('#newprojectform').serialize());
       addNewProjecttypeForm($('#newprojectform').serialize(), function(result){
            hideModal();
        });
    });

    showGeneralModal();
}

/**
 * Show the edit projecttype modal.
 * @param {type} code
 * @param {type} name
 * @param {type} description
 * @param {type} tid
 * @returns {undefined}
 */
function showEditProjectTypeModal(code, name, description, tid)
{
  resetGeneralModal();
    setGeneralModalTitle(i18n.__("EditProjectTitle"));
    setGeneralModalBody('<form id="updateprojectform"> \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('CodeTableTitle') + '" " name="code" value="' + code + '"> \

 \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('NameTableTitle') + '" name="name" value="' + name + '"> \

 \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('DescTableTitle') + '" name="description" value="' + description + '"> \

 \
        </form>');
    $.getJSON()

    addGeneralModalButton(i18n.__("SaveBtn"), function(){
        updateProjecttypeForm(tid, $('#updateprojectform').serialize(), function(result){
            hideModal();
        });
    });

    addGeneralModalButton(i18n.__("CancelBtn"), function(){
        hideModal();
    })

    showGeneralModal();
}

function showCoupleStudentListModal(projectid) {
    viewModel.currentselectedlist = -1;
    resetGeneralModal();
    setGeneralModalTitle(i18n.__("CoupleStudentList"));
    setGeneralModalBody(
        '
' +
            '<button class="btn btn-default dropdown-toggle" type="button" id="dropdownStudLists" data-toggle="dropdown" aria-expanded="true">' +
                'Dropdown' +
                '' +
            '</button>' +
            '
' +
            '
' +
        '
');

    addGeneralModalButton(i18n.__("SaveBtn"), function() {
        updateListForm(viewModel.currentselectedlist, $('#coupleform').serialize(), function(result){
            hideModal();
        });
    });

    addGeneralModalButton(i18n.__("CancelBtn"), function(){
        hideModal();
    })
    showGeneralModal();
}
function loadCoupleDropdown() {
    $.getJSON('/rapportapi/studentlists/' + viewModel.userId, function(data) {
        $.each(data, function(i, item) {
            $("#ddlLists").append('
' + item.name + '
')
            $("#dropdownitem-" + item.id).click(function(){
                $(this).parent().parent().parent().removeClass("open");
                $(this).parent().parent().parent().find(".btn").html($(this).text() + '');
                viewModel.currentselectedlist = item.id;
            });
        });
    });
    $("#dropdownStudLists").click(function() {
        $(this).parent().toggleClass("open");
    });
}

function updateListForm(id, serialData, callback) {
    $.ajax({
        url: "/rapportapi/project/" + viewModel.currentprojectid + "/studentlist/" + id,
        type: "POST",
        data: serialData,
        success: function(data) {
            callback(true);
        },
        error: function(data) {
            callback(false);
        }
    });
}

function initPage() {
    // Add button handlers
    $('#addProjectTypeBtn').click(function(){
        showNewProjectTypeModal();
    });

    $.getJSON('/rapportapi/currentuser', function(data) {
        viewModel.userId = data.id;
    });
}
<commit_msg>update course<commit_after>// View model for the courses page
function pageViewModel(gvm) {
    // Page specific i18n bindings
    gvm.app  = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectRapportName")}, gvm);
    gvm.title = ko.computed(function(){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("CourseTitle2");}, gvm);
    gvm.pageHeader = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("CourseTitle2");}, gvm);
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectRapportName");}, gvm);

    gvm.availableLocations = ko.observableArray([]);
    gvm.availableTrainings = ko.observableArray([]);
    gvm.availableCourses = ko.observableArray([]);
    // Pagination i18n bindings
    gvm.addBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AddBtn")}, gvm);

    gvm.codeTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("CodeTableTitle");}, gvm);
    gvm.nameTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("NameTableTitle");}, gvm);
    gvm.descTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("DescTableTitle");}, gvm);
    gvm.actionTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ActionTableTitle");}, gvm);

    // The table data observable array
    gvm.tabledata = ko.observableArray([]);

    // Add data to the table
    gvm.addTableData = function(id, code, name, desc) {
        console.log(id + ", " + code + ", " + name + ", " + desc);
        // Push data
        var tblOject = {tid: id, tcode: code, tname: name, tdesc: desc};
        gvm.tabledata.push(tblOject);

        // Attach delete handler to delete button
        $('#removebtn-' + id).bind('click', function(event, data){
            // Delete the table item
            deleteTableItem(id, tblOject);
            event.stopPropagation();
        });

        // Attach edit handler to edit button
        $('#editbtn-' + id).bind('click', function(event, data){
            // Edit the table item
            showEditProjectTypeModal(code, name, desc, id);
            event.stopPropagation();
        });

        //Attach manage handler to manage competences, subcompetences and indicators to manage button
        $('#managebtn-' + id).bind('click', function(event, data) {
            //TODO
        });

        /*$('#studentbtn-' + id).bind('click', function(event, data) {
            showCoupleStudentListModal(id);
            gvm.currentprojectid = id;
            gvm.currentselectedlist = -1;
            event.stopPropagation();
            loadCoupleDropdown();
        });*/
    }

    gvm.clearTable = function() {
        gvm.tabledata.removeAll();
    }
    }
/*
 * Delete item from table given the id.
 */
function deleteTableItem(id, tblOject) {
    showYesNoModal("Bent u zeker dat u dit item wil verwijderen?", function(val){
        if(val){
            $.ajax({
                url: "/api/coursedelete/" + id,
                type: "DELETE",
                success: function() {
                    viewModel.tabledata.remove(tblOject);
                }
            });
        }
    });
}

/*
 * Add a new projecttype
 */
function addNewProjecttypeForm(serialData, callback) {
    $.ajax({
            url: "/api/courserapport",
            type: "POST",
            data: serialData,
            success: function(data) {
                viewModel.addTableData(data['id'], data['code'], data['name'], data['description']);
                callback(true);
            },
            error: function(data) {
                callback(false);
            }
        });
}

/*
 * Add a new projecttype
 */
function addNewProjecttypeRaw(code, name, description, callback) {
    addNewProjecttypeForm("code=" + encodeURIComponent(code) + "&name=" + encodeURIComponent(name) + "&description=" + encodeURIComponent(description), callback);
}

/*
 * Update the projecttype
 * @param {type} id
 * @param {type} code
 * @param {type} name
 * @param {type} description
 * @param {type} callback
 * @returns {undefined}
 */
function updateProjecttypeForm(id, serialData, callback) {
    $.ajax({
        url: "/api/courseupdate/" + id,
        type: "PUT",
        data: serialData,
        success: function(data) {
            //var tblOject = {tid: data['id'], tcode: data['code'], tname: data['name'], tdesc: data['description']};
            //viewModel.addTableData(data['id'], data['code'], data['name'], data['description']);
            loadTablePage(2); //TODO now it is refreshing table after updating but it redirects to pagenr 1
            callback(true);
        },
        error: function(data) {
            callback(false);
        }
    });
}

/**
 * update project type
 * @param {type} id
 * @param {type} code
 * @param {type} name
 * @param {type} description
 * @param {type} callback
 * @returns {undefined}
 */
function updateProjecttypeRaw(id, code, name, description, callback) {
    updateProjecttypeForm(id, "code=" + encodeURIComponent(code) + "&name=" + encodeURIComponent(name) + "&description=" + encodeURIComponent(description), callback);
}

/*
 * Load page of the table
 */
function loadTablePage(pagenr)
{
    console.log('im in loadTablePage');
    $.getJSON('/api/coursesrapport/page/' + pagenr, function(data){

        /* Clear current table page */
        viewModel.clearTable();

        // Load table data
        $.each(data.data, function(i, item) {
            console.log(item.name);
            viewModel.addTableData(item.id, item.code, item.name, item.description);
        });

        /* Let previous en next buttons work */
        if(data.prev == "none"){
            $('#pager-prev-btn').addClass('disabled');
        } else {
            $('#pager-prev-btn').removeClass('disabled');
            $('#pager-prev-btn a').click(function(){
                loadTablePage(data.prev);
            });
        }

        if(data.next == "none"){
            $('#pager-next-btn').addClass('disabled');
        } else {
            $('#pager-next-btn').removeClass('disabled');
            $('#pager-next-btn a').click(function(){
                loadTablePage(data.next);
            });
        }

        // Number of pager buttons
        var numItems = $('.pager-nr-btn').length;

        /* Calculate for the pager buttons */
        var lowPage = Math.floor(pagenr/numItems) + 1;

        $('.pager-nr-btn').each(function() {
            /* calculate current page number */
            var thispagenr = lowPage++;

            /* Add the page number */
            $(this).html('' + thispagenr + '');

            /* Add active class to current page */
            if(thispagenr == pagenr) {
                $(this).addClass('active');
            } else {
                $(this).removeClass('active');
            }

            /* Disable inactive classes and bind handlers to active classes */
            if(thispagenr > data.pagecount) {
                $(this).addClass('disabled');
            } else {
                /* Add click listener for button */
                $(this).click(function() {
                    loadTablePage(thispagenr);
                });
            }
        });
    });

}

/**
 * Show a new projecttype modal.
 * @returns {undefined}
 */
function showNewProjectTypeModal()
{
    resetGeneralModal();
    setGeneralModalTitle(i18n.__("AddNewCourse"));
    setGeneralModalBody('<form id="newprojectform"> \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('CodeTableTitle') + '" " name="code"> \

 \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('NameTableTitle') + '" name="name"> \

 \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('DescTableTitle') + '" name="description"> \

 \

 \
                <button class="btn btn-wide btn-default dropdown-toggle" type="button" id="teacher" data-toggle="dropdown" aria-expanded="true" placeholder="' + i18n.__('TeacherTableTitle') + '" name="teacher"> \
                    Teacher \
                     \
                </button> \

 \
        </form>');

    addGeneralModalButton(i18n.__("AddBtn"), function(){
        console.log($('#newprojectform').serialize());
       addNewProjecttypeForm($('#newprojectform').serialize(), function(result){
            hideModal();
        });
    });

    showGeneralModal();
}

/**
 * Show the edit projecttype modal.
 * @param {type} code
 * @param {type} name
 * @param {type} description
 * @param {type} tid
 * @returns {undefined}
 */
function showEditProjectTypeModal(code, name, description, tid)
{
  resetGeneralModal();
    setGeneralModalTitle(i18n.__("EditProjectTitle"));
    setGeneralModalBody('<form id="updateprojectform"> \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('CodeTableTitle') + '" " name="code" value="' + code + '"> \

 \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('NameTableTitle') + '" name="name" value="' + name + '"> \

 \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('DescTableTitle') + '" name="description" value="' + description + '"> \

 \
        </form>');
    $.getJSON()

    addGeneralModalButton(i18n.__("SaveBtn"), function(){
        updateProjecttypeForm(tid, $('#updateprojectform').serialize(), function(result){
            hideModal();
        });
    });

    addGeneralModalButton(i18n.__("CancelBtn"), function(){
        hideModal();
    })

    showGeneralModal();
}

function showCoupleStudentListModal(projectid) {
    viewModel.currentselectedlist = -1;
    resetGeneralModal();
    setGeneralModalTitle(i18n.__("CoupleStudentList"));
    setGeneralModalBody(
        '
' +
            '<button class="btn btn-default dropdown-toggle" type="button" id="dropdownStudLists" data-toggle="dropdown" aria-expanded="true">' +
                'Dropdown' +
                '' +
            '</button>' +
            '
' +
            '
' +
        '
');

    addGeneralModalButton(i18n.__("SaveBtn"), function() {
        updateListForm(viewModel.currentselectedlist, $('#coupleform').serialize(), function(result){
            hideModal();
        });
    });

    addGeneralModalButton(i18n.__("CancelBtn"), function(){
        hideModal();
    })
    showGeneralModal();
}
function loadCoupleDropdown() {
    $.getJSON('/rapportapi/studentlists/' + viewModel.userId, function(data) {
        $.each(data, function(i, item) {
            $("#ddlLists").append('
' + item.name + '
')
            $("#dropdownitem-" + item.id).click(function(){
                $(this).parent().parent().parent().removeClass("open");
                $(this).parent().parent().parent().find(".btn").html($(this).text() + '');
                viewModel.currentselectedlist = item.id;
            });
        });
    });
    $("#dropdownStudLists").click(function() {
        $(this).parent().toggleClass("open");
    });
}

function updateListForm(id, serialData, callback) {
    $.ajax({
        url: "/rapportapi/project/" + viewModel.currentprojectid + "/studentlist/" + id,
        type: "POST",
        data: serialData,
        success: function(data) {
            callback(true);
        },
        error: function(data) {
            callback(false);
        }
    });
}

function initPage() {
    // Add button handlers
    $('#addProjectTypeBtn').click(function(){
        showNewProjectTypeModal();
    });

    $.getJSON('/rapportapi/currentuser', function(data) {
        viewModel.userId = data.id;
    });
}
<|endoftext|>


<commit_before>export default class SentenceGetterController {

  constructor($sce,getterService,filterService ) {
  	this.$sce           = $sce;
	  this.getterService  = getterService;
		this.filterService  = filterService;
	  this.sentence       = $sce.trustAsHtml('let\'s get it');
  }

  get(){
  	this.getterService
  		.get()
  		.$promise
  		.then((data)=>{
  			this.sentence = this.$sce.trustAsHtml(data.value.joke);
  		});
  }
}

SentenceGetterController.$inject = [
	'$sce',
	'sentenceGetterService',
	'sentenceFilterService'
];<commit_msg>added limitTo filter to the query<commit_after>export default class SentenceGetterController {

  constructor($sce,getterService,filterService ) {
  	this.$sce           = $sce;
	  this.getterService  = getterService;
		this.filterService  = filterService;
	  this.sentence       = $sce.trustAsHtml('let\'s get it');
  }

  get(){
    this.getterService
  		.get({
        limitTo : this.filterService.get()
      })
  		.$promise
  		.then((data)=>{
  			this.sentence = this.$sce.trustAsHtml(data.value.joke);
  		});
  }
}

SentenceGetterController.$inject = [
	'$sce',
	'sentenceGetterService',
	'sentenceFilterService'
];<|endoftext|>


<commit_before>app.constant('SELECT_SERVICE_URL', '/select');
app.constant('TRUST_SERVICE_URL', '/trustability');
app.constant('TRANSLATION_SERVICE_URL', '/translation');
app.constant('DISAMBIGUATOR_SERVICE_URL', '/khresmoiDisambiguator');
app.constant('NEWS_SERVICE_URL', '/feeds');
app.constant('SUGGEST_SERVICE_URL', '/suggest');
app.constant('QUESTIONS_SERVICE_URL', '/questions');
app.constant('SCREENSHOT_SERVICE_URL', 'http://everyone.khresmoi.eu:3000');
app.constant('VERSION', '0.1.1-app-content');
app.constant('DEFAULT_PREFERENCES', {
  hello: 'world',
  test: true,
  advancedSearch: true,
  advancedNews: false,
});
app.constant('LANGUAGES', {
  bg: {
    name: 'български',
    flag: 'bg',
    key: 'bg',
  },
  cs: {
    name: 'čeština',
    flag: 'cz',
    key: 'cs',
    translatableTargets: ['en'],
  },
  da: {
    name: 'dansk',
    flag: 'dk',
    key: 'da',
  },
  de: {
    name: 'Deutsch',
    flag: 'de',
    key: 'de',
    translatableTargets: ['en'],
  },
  el: {
    name: 'ελληνικά',
    flag: 'gr',
    key: 'el',
  },
  et: {
    name: 'eesti keel',
    flag: 'ee',
    key: 'et',
  },
  en: {
    name: 'English',
    flag: 'gb',
    key: 'en',
    translatableTargets: ['cs', 'de', 'fr'],
  },
  es: {
    name: 'español',
    flag: 'es',
    key: 'es',
  },
  hr: {
    name: 'hrvatski',
    flag: 'hr',
    key: 'hr',
  },
  fr: {
    name: 'français',
    flag: 'fr',
    key: 'fr',
    translatableTargets: ['en'],
  },
  it: {
    name: 'italiano',
    flag: 'it',
    key: 'it',
  },
  lv: {
    name: 'latviešu valoda',
    flag: 'lv',
    key: 'lv',
  },
  lt: {
    name: 'lietuvių kalba',
    flag: 'lt',
    key: 'lt',
  },
  hu: {
    name: 'magyar',
    flag: 'hu',
    key: 'hu',
  },
  mt: {
    name: 'Malti',
    flag: 'mt',
    key: 'mt',
  },
  nl: {
    name: 'Nederlands',
    flag: 'nl',
    key: 'nl',
  },
  pl: {
    name: 'polski',
    flag: 'pl',
    key: 'pl',
  },
  pt: {
    name: 'português',
    flag: 'pt',
    key: 'pt',
  },
  ro: {
    name: 'română',
    flag: 'ro',
    key: 'ro',
  },
  sk: {
    name: 'slovenčina',
    flag: 'sk',
    key: 'sk',
  },
  sl: {
    name: 'slovenščina',
    flag: 'si',
    key: 'sl',
  },
  fi: {
    name: 'suomi',
    flag: 'fi',
    key: 'fi',
  },
  sv: {
    name: 'svenska',
    flag: 'se',
    key: 'sv',
  },
});
<commit_msg>fix #60<commit_after>app.constant('SELECT_SERVICE_URL', '/select');
app.constant('TRUST_SERVICE_URL', '/trustability');
app.constant('TRANSLATION_SERVICE_URL', '/translation');
app.constant('DISAMBIGUATOR_SERVICE_URL', '/khresmoiDisambiguator');
app.constant('NEWS_SERVICE_URL', '/feeds');
app.constant('SUGGEST_SERVICE_URL', '/suggest');
app.constant('QUESTIONS_SERVICE_URL', '/questions');
app.constant('SCREENSHOT_SERVICE_URL', 'http://everyone.khresmoi.eu:3000');
app.constant('VERSION', '0.1.1-fix-host-base');
app.constant('DEFAULT_PREFERENCES', {
  hello: 'world',
  test: true,
  advancedSearch: true,
  advancedNews: false,
});
app.constant('LANGUAGES', {
  bg: {
    name: 'български',
    flag: 'bg',
    key: 'bg',
  },
  cs: {
    name: 'čeština',
    flag: 'cz',
    key: 'cs',
    translatableTargets: ['en'],
  },
  da: {
    name: 'dansk',
    flag: 'dk',
    key: 'da',
  },
  de: {
    name: 'Deutsch',
    flag: 'de',
    key: 'de',
    translatableTargets: ['en'],
  },
  el: {
    name: 'ελληνικά',
    flag: 'gr',
    key: 'el',
  },
  et: {
    name: 'eesti keel',
    flag: 'ee',
    key: 'et',
  },
  en: {
    name: 'English',
    flag: 'gb',
    key: 'en',
    translatableTargets: ['cs', 'de', 'fr'],
  },
  es: {
    name: 'español',
    flag: 'es',
    key: 'es',
  },
  hr: {
    name: 'hrvatski',
    flag: 'hr',
    key: 'hr',
  },
  fr: {
    name: 'français',
    flag: 'fr',
    key: 'fr',
    translatableTargets: ['en'],
  },
  it: {
    name: 'italiano',
    flag: 'it',
    key: 'it',
  },
  lv: {
    name: 'latviešu valoda',
    flag: 'lv',
    key: 'lv',
  },
  lt: {
    name: 'lietuvių kalba',
    flag: 'lt',
    key: 'lt',
  },
  hu: {
    name: 'magyar',
    flag: 'hu',
    key: 'hu',
  },
  mt: {
    name: 'Malti',
    flag: 'mt',
    key: 'mt',
  },
  nl: {
    name: 'Nederlands',
    flag: 'nl',
    key: 'nl',
  },
  pl: {
    name: 'polski',
    flag: 'pl',
    key: 'pl',
  },
  pt: {
    name: 'português',
    flag: 'pt',
    key: 'pt',
  },
  ro: {
    name: 'română',
    flag: 'ro',
    key: 'ro',
  },
  sk: {
    name: 'slovenčina',
    flag: 'sk',
    key: 'sk',
  },
  sl: {
    name: 'slovenščina',
    flag: 'si',
    key: 'sl',
  },
  fi: {
    name: 'suomi',
    flag: 'fi',
    key: 'fi',
  },
  sv: {
    name: 'svenska',
    flag: 'se',
    key: 'sv',
  },
});
<|endoftext|>


<commit_before>import { benefitTypes } from 'vets-json-schema/dist/constants.json';
import environment from 'platform/utilities/environment';

// *** URLS ***
export const HLR_INFO_URL = '/decision-reviews/higher-level-review/';
// Same as "rootUrl" in manifest.json
export const BASE_URL = `${HLR_INFO_URL}request-higher-level-review-form-20-0996`;

export const FORM_URL = 'https://www.vba.va.gov/pubs/forms/VBA-20-0996-ARE.pdf';

export const BOARD_APPEALS_URL = '/decision-reviews/board-appeal/';
export const DECISION_REVIEWS_URL = '/decision-reviews/';
export const CLAIM_STATUS_TOOL_URL = '/claim-or-appeal-status/';
export const SUPPLEMENTAL_CLAIM_URL = '/decision-reviews/supplemental-claim/';
export const COVID_FAQ_URL =
  'https://www.va.gov/coronavirus-veteran-frequently-asked-questions/#more-benefit-and-claim-questio';
export const FACILITY_LOCATOR_URL = '/find-locations';
export const GET_HELP_REVIEW_REQUEST_URL =
  '/decision-reviews/get-help-with-review-request';
export const PROFILE_URL = '/profile';
export const LEGACY_APPEALS_URL = '/decision-reviews/legacy-appeals/';

// 8622 is the ID of the <li> wrapping the "Find addresses for other benefit
// types" accordion
export const BENEFIT_OFFICES_URL = `${HLR_INFO_URL}#find-addresses-for-other-benef-8622`;

export const CONTESTABLE_ISSUES_API =
  '/higher_level_reviews/contestable_issues/';

// key for contestedIssues to indicate that the user selected the issue
export const SELECTED = 'view:selected';

// Including a default until we determine how to get around the user restarting
// the application after using the "Finish this application later" link
// See https://dsva.slack.com/archives/C0113MPTGH5/p1600725048027200
export const DEFAULT_BENEFIT_TYPE = 'compensation';

export const errorMessages = {
  savedFormNotFound: 'Please start over to request a Higher-Level Review',
  savedFormNoAuth:
    'Please sign in again to continue your request for Higher-Level Review',
  forwardStartDate: 'Please select a date',
  startDateInPast: 'Start date must be in the future',
  endDateInPast: 'End date must be in the future',
  endDateBeforeStart: 'End date must be after start date',
  informalConferenceContactChoice: 'Please choose an option',
  informalConferenceContactName: 'Please enter your representative’s name',
  informalConferenceContactFirstName:
    'Please enter your representative’s first name',
  informalConferenceContactLastName:
    'Please enter your representative’s last name',
  informalConferenceContactPhone:
    'Please enter your representative’s phone number',
  informalConferenceContactPhonePattern:
    'Please enter a 10-digit phone number (with or without dashes)',
  informalConferenceTimes: 'Please select a time',
  contestedIssue: 'Please select an eligible issue',
};

export const NULL_CONDITION_STRING = 'Unknown Condition';

// contested issue dates
export const FORMAT_YMD = 'YYYY-MM-DD';
export const FORMAT_READABLE = 'LL';

// session storage keys
export const SAVED_CLAIM_TYPE = 'hlrClaimType';
export const WIZARD_STATUS = 'wizardStatus996';

export const MAX_SELECTIONS = 100;

// Values from benefitTypes in vets-json-schema constants
const supportedBenefitTypes = [
  'compensation', // Phase 1
  // 'pension',
  // 'fiduciary',
  // 'education',
  // 'vha',
  // 'voc_rehab',
  // 'loan_guaranty',
  // 'insurance',
  // 'nca',
];

export const SUPPORTED_BENEFIT_TYPES = benefitTypes.map(type => ({
  ...type,
  isSupported: supportedBenefitTypes.includes(type.value),
}));

export const IS_PRODUCTION = environment.isProduction();

export const CONFERENCE_TIMES_V1 = {
  time0800to1000: {
    label: '8:00 a.m. to 10:00 a.m. ET',
    submit: '800-1000 ET',
  },
  time1000to1230: {
    label: '10:00 a.m. to 12:30 p.m. ET',
    submit: '1000-1230 ET',
  },
  time1230to1400: {
    label: '12:30 p.m. to 2:00 p.m. ET',
    submit: '1230-1400 ET',
  },
  time1400to1630: {
    label: '2:00 p.m. to 4:30 p.m. ET',
    submit: '1400-1630 ET',
  },
};

export const CONFERENCE_TIMES_V2 = {
  time0800to1200: {
    label: '8:00 a.m. to 12:00 p.m. ET',
    submit: '800-1200 ET',
  },
  time1200to1630: {
    label: '12:00 p.m. to 4:30 p.m. ET',
    submit: '1200-1630 ET',
  },
};
<commit_msg>Update link to other benefit addresses (#19051)<commit_after>import { benefitTypes } from 'vets-json-schema/dist/constants.json';
import environment from 'platform/utilities/environment';

// *** URLS ***
export const HLR_INFO_URL = '/decision-reviews/higher-level-review/';
// Same as "rootUrl" in manifest.json
export const BASE_URL = `${HLR_INFO_URL}request-higher-level-review-form-20-0996`;

export const FORM_URL = 'https://www.vba.va.gov/pubs/forms/VBA-20-0996-ARE.pdf';

export const BOARD_APPEALS_URL = '/decision-reviews/board-appeal/';
export const DECISION_REVIEWS_URL = '/decision-reviews/';
export const CLAIM_STATUS_TOOL_URL = '/claim-or-appeal-status/';
export const SUPPLEMENTAL_CLAIM_URL = '/decision-reviews/supplemental-claim/';
export const COVID_FAQ_URL =
  'https://www.va.gov/coronavirus-veteran-frequently-asked-questions/#more-benefit-and-claim-questio';
export const FACILITY_LOCATOR_URL = '/find-locations';
export const GET_HELP_REVIEW_REQUEST_URL =
  '/decision-reviews/get-help-with-review-request';
export const PROFILE_URL = '/profile';
export const LEGACY_APPEALS_URL = '/decision-reviews/legacy-appeals/';

// 8622 is the ID of the <li> wrapping the "Find addresses for other benefit
// types" accordion
export const BENEFIT_OFFICES_URL = `${HLR_INFO_URL}#find-addresses`;

export const CONTESTABLE_ISSUES_API =
  '/higher_level_reviews/contestable_issues/';

// key for contestedIssues to indicate that the user selected the issue
export const SELECTED = 'view:selected';

// Including a default until we determine how to get around the user restarting
// the application after using the "Finish this application later" link
// See https://dsva.slack.com/archives/C0113MPTGH5/p1600725048027200
export const DEFAULT_BENEFIT_TYPE = 'compensation';

export const errorMessages = {
  savedFormNotFound: 'Please start over to request a Higher-Level Review',
  savedFormNoAuth:
    'Please sign in again to continue your request for Higher-Level Review',
  forwardStartDate: 'Please select a date',
  startDateInPast: 'Start date must be in the future',
  endDateInPast: 'End date must be in the future',
  endDateBeforeStart: 'End date must be after start date',
  informalConferenceContactChoice: 'Please choose an option',
  informalConferenceContactName: 'Please enter your representative’s name',
  informalConferenceContactFirstName:
    'Please enter your representative’s first name',
  informalConferenceContactLastName:
    'Please enter your representative’s last name',
  informalConferenceContactPhone:
    'Please enter your representative’s phone number',
  informalConferenceContactPhonePattern:
    'Please enter a 10-digit phone number (with or without dashes)',
  informalConferenceTimes: 'Please select a time',
  contestedIssue: 'Please select an eligible issue',
};

export const NULL_CONDITION_STRING = 'Unknown Condition';

// contested issue dates
export const FORMAT_YMD = 'YYYY-MM-DD';
export const FORMAT_READABLE = 'LL';

// session storage keys
export const SAVED_CLAIM_TYPE = 'hlrClaimType';
export const WIZARD_STATUS = 'wizardStatus996';

export const MAX_SELECTIONS = 100;

// Values from benefitTypes in vets-json-schema constants
const supportedBenefitTypes = [
  'compensation', // Phase 1
  // 'pension',
  // 'fiduciary',
  // 'education',
  // 'vha',
  // 'voc_rehab',
  // 'loan_guaranty',
  // 'insurance',
  // 'nca',
];

export const SUPPORTED_BENEFIT_TYPES = benefitTypes.map(type => ({
  ...type,
  isSupported: supportedBenefitTypes.includes(type.value),
}));

export const IS_PRODUCTION = environment.isProduction();

export const CONFERENCE_TIMES_V1 = {
  time0800to1000: {
    label: '8:00 a.m. to 10:00 a.m. ET',
    submit: '800-1000 ET',
  },
  time1000to1230: {
    label: '10:00 a.m. to 12:30 p.m. ET',
    submit: '1000-1230 ET',
  },
  time1230to1400: {
    label: '12:30 p.m. to 2:00 p.m. ET',
    submit: '1230-1400 ET',
  },
  time1400to1630: {
    label: '2:00 p.m. to 4:30 p.m. ET',
    submit: '1400-1630 ET',
  },
};

export const CONFERENCE_TIMES_V2 = {
  time0800to1200: {
    label: '8:00 a.m. to 12:00 p.m. ET',
    submit: '800-1200 ET',
  },
  time1200to1630: {
    label: '12:00 p.m. to 4:30 p.m. ET',
    submit: '1200-1630 ET',
  },
};
<|endoftext|>


<commit_before>import { Group, Mesh, MeshNormalMaterial } from 'three';
import BUNNYMODEL from './bunny.model.json';
import BUNNYSCENE from './bunny.scene.json';
import { loadModel, loadScene } from '../../Loaders/loader';

export default class extends Group {
  constructor() {
    super();

    loadModel(BUNNYMODEL).then( (geometry)=>{
      const material = new MeshNormalMaterial();
      const mesh = new Mesh(geometry, material);
      this.add(mesh);
      mesh.position.x = 1.2 / -2;
      geometry.dispose();
      material.dispose();
    } );

    loadScene(BUNNYSCENE).then( (mesh)=>{
      this.add(mesh);

      mesh.position.x = 1.2 / 2;
      mesh.position.y = -0.3
    } );
  }
}
<commit_msg>New materails<commit_after>import { Group, Mesh, MeshStandardMaterial } from 'three';
import BUNNYMODEL from './bunny.model.json';
import BUNNYSCENE from './bunny.scene.json';
import { loadModel, loadScene } from '../../Loaders/loader';

export default class extends Group {
  constructor() {
    super();

    loadModel(BUNNYMODEL).then( (geometry)=>{
      geometry.computeVertexNormals();
      const material = new MeshStandardMaterial();
      const mesh = new Mesh(geometry, material);
      this.add(mesh);
      mesh.position.x = 1.2 / -2;
      geometry.dispose();
      material.dispose();
    } );

    loadScene(BUNNYSCENE).then( (mesh)=>{
      this.add(mesh);

      mesh.position.x = 1.2 / 2;
      mesh.position.y = -0.3
    } );
  }
}
<|endoftext|>


<commit_before>/**
 * @file This is a classic javascript file. It should be loaded in a HTML web page
 * by a HTML script tag.
 *
 * In module (non-classic) script, static import is available. But at the same
 * time, importScripts() will not be avbailable. For solving this problem, using
 * classic (non-module) script so that Google Visualization API, Google Tag Manager,
 * tensorflow.js can be loaded by importScripts(). At the same time, using dynamic
 * import() to load ourselves module because import() can be used in classic
 * (non-module) script.
 */

//!!! ...unfinished... (2022/08/25)
// Google Visualization API, Google Tag Manager should be load here
// (before window_onload).

window.addEventListener( "load", function ( e ) {
  console.log( "QuerySubmitCanvas_domSide_script.js: window_onload..." );

//!!! ...unfinished... (2022/08/25)
  importScripts();

} );
<commit_msg>AddRemoteScriptDependency<commit_after>/**
 * @file This is a classic javascript file. It should be loaded in a HTML web page
 * by a HTML script tag.
 *
 * This is mainly used in Construt.net (c3addon) IPluginInfo or IBehaviorInfo.
 * Please use their .AddRemoteScriptDependency() method to load this script as
 * type "external-dom-script"
 *
 * In module (non-classic) script, static import is available. But at the same
 * time, importScripts() will not be avbailable. For solving this problem, using
 * classic (non-module) script so that Google Visualization API, Google Tag Manager,
 * tensorflow.js can be loaded by importScripts(). At the same time, using dynamic
 * import() to load ourselves module because import() can be used in classic
 * (non-module) script.
 */

//!!! ...unfinished... (2022/08/25)
// Google Visualization API, Google Tag Manager should be load here
// (before window_onload).

window.addEventListener( "load", function ( e ) {
  console.log( "QuerySubmitCanvas_domSide_script.js: window_onload..." );

//!!! ...unfinished... (2022/08/25)
  importScripts();

} );
<|endoftext|>


<commit_before>import Vue from 'vue';
import Router from 'vue-router';
import store from './store';

const routerOptions = [
  {
    path: '/',
    name: 'home',
    component: 'Home'
  },
  {
    path: '/restricted',
    name: 'restricted',
    component: 'Restricted'
  },
  {
    path: '/config',
    name: 'config',
    component: 'Config',
    meta: {
      requiresAuth: true,
      requiresDataProducer: true
    }
  },
  {
    path: '/datasets',
    name: 'datasets',
    component: 'Datasets',
    meta: {
      requiresAuth: true,
      requiresDataProducer: true
    }
  },
  {
    path: '/views',
    name: 'views',
    component: 'Views',
    meta: {
      requiresAuth: true,
      requiresDataProducer: true
    }
  },
  {
    path: '/ingestion',
    name: 'ingestion',
    component: 'Ingestion',
    meta: {
      requiresAuth: true,
      requiresDataProducer: true
    }
  },
  {
    path: '/accounts',
    name: 'accounts',
    component: 'Accounts',
    meta: {
      requiresAuth: true,
      requiresDataProducer: true
    }
  },
  {
    path: '/editView',
    name: 'editView',
    component: 'EditView',
    meta: {
      requiresAuth: true,
      requiresDataProducer: true
    }
  },
  {
    path: '/editIngestion',
    name: 'editIngestion',
    component: 'EditIngestion',
    meta: {
      requiresAuth: true,
      requiresDataProducer: true
    }
  },
  {
    path: '/editAccount',
    name: 'editAccount',
    component: 'EditAccount',
    meta: {
      requiresAuth: true,
      requiresDataProducer: true
    }
  },
  {
    path: '/policies',
    name: 'policies',
    component: 'Policies',
    meta: {
      requiresAuth: true,
      requiresDataProducer: true
    }
  },
  {
    path: '/editPolicy',
    name: 'editPolicy',
    component: 'EditPolicy',
    meta: {
      requiresAuth: true,
      requiresDataProducer: true
    }
  },
  {
    path: '/procurements',
    name: 'procurements',
    component: 'Procurements',
    meta: {
      requiresAuth: true,
      requiresDataProducer: true
    }
  },
  {
    path: '/activation',
    name: 'activation',
    component: 'Activation',
    meta: {
      requiresAuth: true
    }
  },
  {
    path: '/myProducts',
    name: 'myProducts',
    component: 'MyProducts',
    meta: {
      requiresAuth: true
    }
  },
  {
    path: '/spotFulfillment',
    name: 'spotFulfillment',
    component: 'SpotFulfillment',
    meta: {
      requiresAuth: true,
      requiresDataProducer: true
    }
  },
  {
    path: '/admin',
    name: 'admin',
    component: 'Admin',
    meta: {
      requiresAuth: true,
      requiresDataProducer: true
    }
  }
];

const routes = routerOptions.map(route => {
  return {
    ...route,
    component: () => import(`@/views/${route.component}.vue`)
  };
});

Vue.use(Router);

let router = new Router({
  routes,
  mode: 'history',
  base: process.env.BASE_URL
});

// https://github.com/christiannwamba/vuex-auth-jwt/blob/master/src/router.js
router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (store.getters.isLoggedIn) {
      next();
      return;
    }
    // Redirect to login page: next('/login')
    // For now putting next() to avoid issue because we're not persisting auth properly.
    next();
  } else {
    next();
  }
});

export default router;
<commit_msg>Update router.js (#371)<commit_after>import Vue from 'vue';
import Router from 'vue-router';
import store from './store';

const routerOptions = [
  {
    path: '/',
    name: 'home',
    component: 'Home'
  },
  {
    path: '/restricted',
    name: 'restricted',
    component: 'Restricted'
  },
  {
    path: '/datasets',
    name: 'datasets',
    component: 'Datasets',
    meta: {
      requiresAuth: true,
      requiresDataProducer: true
    }
  },
  {
    path: '/views',
    name: 'views',
    component: 'Views',
    meta: {
      requiresAuth: true,
      requiresDataProducer: true
    }
  },
  {
    path: '/accounts',
    name: 'accounts',
    component: 'Accounts',
    meta: {
      requiresAuth: true,
      requiresDataProducer: true
    }
  },
  {
    path: '/editView',
    name: 'editView',
    component: 'EditView',
    meta: {
      requiresAuth: true,
      requiresDataProducer: true
    }
  },
  {
    path: '/editIngestion',
    name: 'editIngestion',
    component: 'EditIngestion',
    meta: {
      requiresAuth: true,
      requiresDataProducer: true
    }
  },
  {
    path: '/editAccount',
    name: 'editAccount',
    component: 'EditAccount',
    meta: {
      requiresAuth: true,
      requiresDataProducer: true
    }
  },
  {
    path: '/policies',
    name: 'policies',
    component: 'Policies',
    meta: {
      requiresAuth: true,
      requiresDataProducer: true
    }
  },
  {
    path: '/editPolicy',
    name: 'editPolicy',
    component: 'EditPolicy',
    meta: {
      requiresAuth: true,
      requiresDataProducer: true
    }
  },
  {
    path: '/procurements',
    name: 'procurements',
    component: 'Procurements',
    meta: {
      requiresAuth: true,
      requiresDataProducer: true
    }
  },
  {
    path: '/activation',
    name: 'activation',
    component: 'Activation',
    meta: {
      requiresAuth: true
    }
  },
  {
    path: '/myProducts',
    name: 'myProducts',
    component: 'MyProducts',
    meta: {
      requiresAuth: true
    }
  },
  {
    path: '/admin',
    name: 'admin',
    component: 'Admin',
    meta: {
      requiresAuth: true,
      requiresDataProducer: true
    }
  }
];

const routes = routerOptions.map(route => {
  return {
    ...route,
    component: () => import(`@/views/${route.component}.vue`)
  };
});

Vue.use(Router);

let router = new Router({
  routes,
  mode: 'history',
  base: process.env.BASE_URL
});

// https://github.com/christiannwamba/vuex-auth-jwt/blob/master/src/router.js
router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresDataProducer)) {
    if (store.getters.isLoggedIn && store.getters.isDataProducer) {
      next();
      return;
    } else {
      router.replace('/restricted');
    }
  } else if (to.matched.some(record => record.meta.requiresAuth)) {
    if (store.getters.isLoggedIn) {
      next();
      return;
    } else {
      router.replace('/restricted');
    }
  } else {
    next();
  }
});

export default router;
<|endoftext|>


<commit_before>/*************************
 * getEl
 * do cross browsing
 *************************/
window.getNewEl = function(elNm, id, classNm, attrs, inner, eventNm, eventFunc){
    var newEl = document.createElement(elNm);   // HTML객체 생성
    if (id) newEl.id = id;                              // 아이디
    if (classNm) newEl.setAttribute('class', classNm);      // 클래스
    for (var attrNm in attrs){ newEl.setAttribute(attrNm, attrs[attrNm]); } // 속성
    if (inner) newEl.innerHTML = inner;         // 안 값
    if (eventNm) getEl(newEl).addEventListener(eventNm, function(event){ eventFunc(event); });  // 이벤트
    return newEl;                               // 반환
};

window.getEl = function(id){

    var querySelectorAll = function(selector){
        if (document.querySelectorAll){
            // return document.querySelectorAll(selector);
            return document.getElementById(selector);
        }else if (document.getElementsByTagName){
            /* Attribute */
            var startIdx = selector.indexOf('[');
            var endIdx = selector.indexOf(']');
            var attr;
            var selectedList = [];
            if (startIdx != -1 && endIdx != -1){
                attr = selector.substring(startIdx +1, endIdx);
                /* 유효성검사에 맞는 Form 태그 들만 */
                var nodeNames = ['div', 'span', 'form', 'input', 'select', 'textarea'];
                for (var searchI=0; searchI< nodeNames.length; searchI++){
                    var elements = document.getElementsByTagName(nodeNames[searchI]);
                    for (var searchJ=0; searchJ<elements.length; searchJ++){
                        if (elements[searchJ].getAttribute(attr) != undefined){
                            selectedList.push(elements[searchJ]);
                        }
                    }
                }
            }
            return selectedList;
        }
    };

    var el = (typeof id == 'object') ? id : document.getElementById(id);
    // var el = (typeof id == 'object') ? id : querySelectorAll(id);
    this.obj = el;

    this.attr = function(key, val){
        if (val){
            el.setAttribute(key, val);
            return this;
        }else{
            return el.getAttribute(key);
        }
    };
    this.clas = (function(){
        var classFuncs = {
            has: function(classNm){
                return (el.className.indexOf(classNm) != -1);
            },
            add: function(classNm){
                if (el.classList){
                    el.classList.add(classNm);
                }else{
                    el.className += ' ' +classNm+ ' ';
                }
                return classFuncs;
            },
            remove: function(classNm){
                if (el.classList){
                    el.classList.remove(classNm);
                }else{
                    var classList = el.className.split(' ');
                    while (classList.indexOf(classNm) != -1){
                        classList.splice(classList.indexOf(classNm), 1);
                    }
                    el.className = classList.join(' ');
                }
                return classFuncs;
            }
        };
        return classFuncs;
    }());
    this.findEl = function(attr, val){
        var subEls = el.children;
        for (var i=0; i<subEls.length; i++){
            if (subEls[i].getAttribute(attr) == val) return subEls[i];
        }
    };
    this.findParentEl = function(attr, val){
        var foundEl;
        var parentEl = el;
        while(parentEl){
            if (parentEl != document.body.parentNode){
                if (parentEl.getAttribute(attr) == val){
                    foundEl = parentEl;
                    break;
                }
            }else{
                foundEl = null;
                break;
            }
            parentEl = parentEl.parentNode;
        }
        return foundEl;
    };
    this.add = function(appender){
        if (typeof appender == 'object')
            el.appendChild(appender);
        else
            el.innerHTML += appender;
        return this;
    };
    this.addln = function(appender){
        if (typeof appender == 'object')
            el.appendChild(appender);
        else
            el.innerHTML += (appender) ? appender : '';
        el.appendChild(document.createElement('br'));
        return this;
    };
    this.hasEventListener = function(eventNm){
        return el.hasEventListener(eventNm);
    };
    this.removeEventListener = function(eventNm, fn){
        el.removeEventListener(eventNm, fn);
        return this;
    };
    this.addEventListener = function(eventNm, fn){
        /* FireFox는 이 작업을 선행하게 하여 window.event객체를 전역으로 돌려야한다.*/
        if (navigator.userAgent.indexOf('Firefox') != -1){
            el.addEventListener(eventNm, function(e){window.event=e;}, true);
        }
        /* 일반 */
        if (el.addEventListener){
            el.addEventListener(eventNm, function(event){
                fn(event);
                // fn(event, getEventTarget(event));
            });
        /* 옛 IE */
        }else{
            el.attachEvent('on'+eventNm, function(event){
                if (!event.target && event.srcElement) event.target = event.srcElement;
                fn(event);
                // fn(event, getEventTarget(event));
            });
        }
        return;
    };
    this.del = function(removeElObj){
        el.removeChild(removeElObj);
        return this;
    };
    this.html = function(innerHTML){
        el.innerHTML = innerHTML;
        return this;
    };
    this.clear = function(){
        el.innerHTML = '';
        return this;
    };
    this.scrollDown = function(){
        el.scrollTop = el.scrollHeight;
        return this;
    };
    this.hideDiv = function(){
        el.style.display = 'block';
        el.style.position = 'absolute';
        el.style.left = '-5555px';
        el.style.top = '-5555px';
        return this;
    };
    this.showDiv = function(){
        el.style.display = 'block';
        el.style.position = 'absolute';
        el.style.left = '0px';
        el.style.top = '0px';
        return this;
    };
    this.getNewSeqId = function (idStr){
        for (var seq=1; seq < 50000; seq++){
            var searchEmptyId = idStr + seq
            if (!(searchEmptyId in el)) return searchEmptyId;
        }
        return null;
    };

    return this;
};

// http://paulirish.com/2011/requestanimationframe-for-smart-animating/
// http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating

// requestAnimationFrame polyfill by Erik Möller
// fixes from Paul Irish and Tino Zijdel
(function() {
    var lastTime = 0;
    var vendors = ['ms', 'moz', 'webkit', 'o'];
    for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
        window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
        window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame']
                                   || window[vendors[x]+'CancelRequestAnimationFrame'];
    }

    if (!window.requestAnimationFrame)
        window.requestAnimationFrame = function(callback, element) {
            var currTime = new Date().getTime();
            var timeToCall = Math.max(0, 16 - (currTime - lastTime));
            var id = window.setTimeout(function(){
                callback(currTime + timeToCall);
            }, timeToCall);
            lastTime = currTime + timeToCall;
            return id;
        };

    if (!window.cancelAnimationFrame)
        window.cancelAnimationFrame = function(id) {
            clearTimeout(id);
        };
}());

/**************/
/* 파일  객체 */
/**************/
(function(){
    window.URL = window.URL || window.webkitURL;
    window.BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder;
}());

/**************/
/* EVENT 객체 */
/**************/
(function(){
    /* FireFox는 이 작업을 선행하게 하여 window.event객체를 전역으로 돌려야한다.*/
    if (navigator.userAgent.indexOf('Firefox') != -1){
        window.addEventListener(eventNm, function(e){window.event=e;}, true);
    }
    if (!window.addEventListener && window.attachEvent){
        window.addEventListener = function(eventNm, fn){
            window.attachEvent('on'+eventNm, function(event){
                if (!event.target && event.srcElement) event.target = event.srcElement;
                if (!event.preventDefault) event.preventDefault = function(){};
                if (!event.stopPropagation){
                    event.stopPropagation = function(){
                        event.returnValue = false;
                        event.cancelBubble = true;
                    };
                }
                fn(event);
            });
        }
    }
}());

/******************/
/* 필수 구현 객체 */
/******************/
(function(){
    if (!Array.prototype.indexOf){
        Array.prototype.indexOf = function(obj){
            for (var i=0; i<this.length; i++){
                if (this[i] == obj) return i;
            }
            return -1;
        }
    }
}());<commit_msg>querySelector, getSuperAttr, disableSelection<commit_after>/*************************
 * getEl
 * do cross browsing
 *************************/
window.getNewEl = function(elNm, id, classNm, attrs, inner, eventNm, eventFunc){
    var newEl = document.createElement(elNm);   // HTML객체 생성
    if (id) newEl.id = id;                              // 아이디
    if (classNm) newEl.setAttribute('class', classNm);      // 클래스
    for (var attrNm in attrs){ newEl.setAttribute(attrNm, attrs[attrNm]); } // 속성
    if (inner) newEl.innerHTML = inner;         // 안 값
    if (eventNm) getEl(newEl).addEventListener(eventNm, function(event){ eventFunc(event); });  // 이벤트
    return newEl;                               // 반환
};

window.getEl = function(id){

    var querySelectorAll = function(selector){
        if (document.querySelectorAll){
            // return document.querySelectorAll(selector);
            return document.getElementById(selector);
        }else if (document.getElementsByTagName){
            /* Attribute */
            var startIdx = selector.indexOf('[');
            var endIdx = selector.indexOf(']');
            var attr;
            var selectedList = [];
            if (startIdx != -1 && endIdx != -1){
                attr = selector.substring(startIdx +1, endIdx);
                /* 유효성검사에 맞는 Form 태그 들만 */
                var nodeNames = ['div', 'span', 'form', 'input', 'select', 'textarea'];
                for (var searchI=0; searchI< nodeNames.length; searchI++){
                    var elements = document.getElementsByTagName(nodeNames[searchI]);
                    for (var searchJ=0; searchJ<elements.length; searchJ++){
                        if (elements[searchJ].getAttribute(attr) != undefined){
                            selectedList.push(elements[searchJ]);
                        }
                    }
                }
            }
            return selectedList;
        }
    };

    var el = (typeof id == 'object') ? id : document.getElementById(id);
    // var el = (typeof id == 'object') ? id : querySelectorAll(id);
    this.obj = el;

    this.attr = function(key, val){
        if (val){
            el.setAttribute(key, val);
            return this;
        }else{
            return el.getAttribute(key);
        }
    };
    this.clas = (function(){
        var classFuncs = {
            has: function(classNm){
                return (el.className.indexOf(classNm) != -1);
            },
            add: function(classNm){
                if (el.classList){
                    el.classList.add(classNm);
                }else{
                    el.className += ' ' +classNm+ ' ';
                }
                return classFuncs;
            },
            remove: function(classNm){
                if (el.classList){
                    el.classList.remove(classNm);
                }else{
                    var classList = el.className.split(' ');
                    while (classList.indexOf(classNm) != -1){
                        classList.splice(classList.indexOf(classNm), 1);
                    }
                    el.className = classList.join(' ');
                }
                return classFuncs;
            }
        };
        return classFuncs;
    }());
    this.findEl = function(attr, val){
        var subEls = el.children;
        for (var i=0; i<subEls.length; i++){
            if (subEls[i].getAttribute(attr) == val) return subEls[i];
        }
    };
    this.findParentEl = function(attr, val){
        var foundEl;
        var parentEl = el;
        while(parentEl){
            if (parentEl != document.body.parentNode){
                if (parentEl.getAttribute(attr) == val){
                    foundEl = parentEl;
                    break;
                }
            }else{
                foundEl = null;
                break;
            }
            parentEl = parentEl.parentNode;
        }
        return foundEl;
    };
    this.add = function(appender){
        if (typeof appender == 'object')
            el.appendChild(appender);
        else
            el.innerHTML += appender;
        return this;
    };
    this.addln = function(appender){
        if (typeof appender == 'object')
            el.appendChild(appender);
        else
            el.innerHTML += (appender) ? appender : '';
        el.appendChild(document.createElement('br'));
        return this;
    };
    this.hasEventListener = function(eventNm){
        return el.hasEventListener(eventNm);
    };
    this.removeEventListener = function(eventNm, fn){
        el.removeEventListener(eventNm, fn);
        return this;
    };
    this.addEventListener = function(eventNm, fn){
        /* FireFox는 이 작업을 선행하게 하여 window.event객체를 전역으로 돌려야한다.*/
        if (navigator.userAgent.indexOf('Firefox') != -1){
            el.addEventListener(eventNm, function(e){window.event=e;}, true);
        }
        /* 일반 */
        if (el.addEventListener){
            el.addEventListener(eventNm, function(event){
                fn(event);
                // fn(event, getEventTarget(event));
            });
        /* 옛 IE */
        }else{
            el.attachEvent('on'+eventNm, function(event){
                if (!event.target && event.srcElement) event.target = event.srcElement;
                fn(event);
                // fn(event, getEventTarget(event));
            });
        }
        return;
    };
    this.del = function(removeElObj){
        el.removeChild(removeElObj);
        return this;
    };
    this.html = function(innerHTML){
        el.innerHTML = innerHTML;
        return this;
    };
    this.clear = function(){
        el.innerHTML = '';
        return this;
    };
    this.scrollDown = function(){
        el.scrollTop = el.scrollHeight;
        return this;
    };
    this.disableSelection = function(){
        if (typeof el.ondragstart != 'undefined') el.ondragstart = function(){return false;};
        if (typeof el.onselectstart != 'undefined') el.onselectstart = function(){return false;};
        if (typeof el.oncontextmenu != 'undefined') el.oncontextmenu = function(){return false;};
        /* 파이어폭스에서 드래그 선택 금지 */
        if (typeof el.style.MozUserSelect != 'undefined') document.body.style.MozUserSelect = 'none';
        return this;
    };
    this.hideDiv = function(){
        el.style.display = 'block';
        el.style.position = 'absolute';
        el.style.left = '-5555px';
        el.style.top = '-5555px';
        return this;
    };
    this.showDiv = function(){
        el.style.display = 'block';
        el.style.position = 'absolute';
        el.style.left = '0px';
        el.style.top = '0px';
        return this;
    };
    this.getNewSeqId = function(idStr){
        for (var seq=1; seq < 50000; seq++){
            var searchEmptyId = idStr + seq
            if (!(searchEmptyId in el)) return searchEmptyId;
        }
        return null;
    };
    this.getSuperAttr = function(attrNm){
        var searchSuperObj;
        while(searchSuperObj){
            if (searchSuperObj.getAttribute(attrNm) != undefined) break;
            searchSuperObj = searchSuperObj.parentNode;
        }
        return searchSuperObj;
    };

    return this;
};

// http://paulirish.com/2011/requestanimationframe-for-smart-animating/
// http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating

// requestAnimationFrame polyfill by Erik Möller
// fixes from Paul Irish and Tino Zijdel
(function() {
    var lastTime = 0;
    var vendors = ['ms', 'moz', 'webkit', 'o'];
    for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
        window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
        window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame']
                                   || window[vendors[x]+'CancelRequestAnimationFrame'];
    }

    if (!window.requestAnimationFrame)
        window.requestAnimationFrame = function(callback, element) {
            var currTime = new Date().getTime();
            var timeToCall = Math.max(0, 16 - (currTime - lastTime));
            var id = window.setTimeout(function(){
                callback(currTime + timeToCall);
            }, timeToCall);
            lastTime = currTime + timeToCall;
            return id;
        };

    if (!window.cancelAnimationFrame)
        window.cancelAnimationFrame = function(id) {
            clearTimeout(id);
        };
}());

/**************/
/* 파일  객체 */
/**************/
(function(){
    window.URL = window.URL || window.webkitURL;
    window.BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder;
}());

/**************/
/* EVENT 객체 */
/**************/
(function(){
    /* FireFox는 이 작업을 선행하게 하여 window.event객체를 전역으로 돌려야한다.*/
    if (navigator.userAgent.indexOf('Firefox') != -1){
        window.addEventListener(eventNm, function(e){window.event=e;}, true);
    }
    if (!window.addEventListener && window.attachEvent){
        window.addEventListener = function(eventNm, fn){
            window.attachEvent('on'+eventNm, function(event){
                if (!event.target && event.srcElement) event.target = event.srcElement;
                if (!event.preventDefault) event.preventDefault = function(){};
                if (!event.stopPropagation){
                    event.stopPropagation = function(){
                        event.returnValue = false;
                        event.cancelBubble = true;
                    };
                }
                fn(event);
            });
        }
    }
}());

/******************/
/* 필수 구현 객체 */
/******************/
(function(){
    if (!Array.prototype.indexOf){
        Array.prototype.indexOf = function(obj){
            for (var i=0; i<this.length; i++){
                if (this[i] == obj) return i;
            }
            return -1;
        }
    }
}());

(function(){
    if (!document.querySelectorAll){
        if(document.getElementsByTagName){
            document.querySelectorAll = function(){
                /* Attribute */
                var startIdx = selector.indexOf('[');
                var endIdx = selector.indexOf(']');
                var attr;
                var selectedList = [];
                if (startIdx != -1 && endIdx != -1){
                    attr = selector.substring(startIdx +1, endIdx);
                    /* 유효성검사에 맞는 Form 태그 들만 */
                    var nodeNames = ['div', 'span', 'form', 'input', 'select', 'textarea'];
                    for (var searchI=0; searchI< nodeNames.length; searchI++){
                        var elements = document.getElementsByTagName(nodeNames[searchI]);
                        for (var searchJ=0; searchJ<elements.length; searchJ++){
                            if (elements[searchJ].getAttribute(attr) != undefined){
                                selectedList.push(elements[searchJ]);
                            }
                        }
                    }
                }
                return selectedList;
            };
        }
    }
}());

<|endoftext|>


<commit_before>/**
 * core/site data store: HTML for URL tests.
 *
 * Site Kit by Google, Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Internal dependencies
 */
import API from 'googlesitekit-api';
import {
	createTestRegistry,
	subscribeUntil,
	unsubscribeFromAll,
	untilResolved,
} from 'tests/js/utils';
import { STORE_NAME } from './constants';

describe( 'core/site html', () => {
	let registry;

	beforeAll( () => {
		API.setUsingCache( false );
	} );

	beforeEach( () => {
		registry = createTestRegistry();
	} );

	afterAll( () => {
		API.setUsingCache( true );
	} );

	afterEach( () => {
		unsubscribeFromAll( registry );
	} );

	describe( 'actions', () => {
		describe( 'fetchGetHTMLForURL', () => {
			it( 'sets isFetchingGetHTMLForURL while fetching HTML then sets back to false', async () => {
				const html = '<title>Example HTML</title>
Example HTML H1
';
				const url = 'https://example.com';

				fetchMock.getOnce(
					{ query: { tagverify: '1' } },
					{ body: html, status: 200 }
				);

				registry.dispatch( STORE_NAME ).fetchGetHTMLForURL( url );
				expect( registry.select( STORE_NAME ).isFetchingGetHTMLForURL( url ) ).toEqual( true );

				await subscribeUntil( registry,
					() => registry.select( STORE_NAME ).isFetchingGetHTMLForURL( url ) === false,
				);

				const selectedHTML = registry.select( STORE_NAME ).getHTMLForURL( url );
				expect( fetchMock ).toHaveFetchedTimes( 1 );
				expect( selectedHTML ).toEqual( html );
				expect( registry.select( STORE_NAME ).isFetchingGetHTMLForURL( url ) ).toEqual( false );
			} );
		} );

		describe( 'resetHTMLForURL', () => {
			it( 'invalidates the resolver for getHTMLForURL', async () => {
				const html = '<title>Example HTML</title>
Example HTML H1
';
				const url = 'https://example.com';
				registry.dispatch( STORE_NAME ).receiveGetHTMLForURL( html, { url } );
				registry.select( STORE_NAME ).getHTMLForURL( url );

				await untilResolved( registry, STORE_NAME ).getHTMLForURL( url );

				registry.dispatch( STORE_NAME ).resetHTMLForURL( url );

				expect( registry.select( STORE_NAME ).hasFinishedResolution( 'getHTMLForURL', [ url ] ) ).toStrictEqual( false );
			} );
		} );

		describe( 'receiveGetHTMLForURL', () => {
			it( 'requires the htmlForURL response', () => {
				expect( () => {
					registry.dispatch( STORE_NAME ).receiveGetHTMLForURL();
				} ).toThrow( 'response is required.' );
			} );

			it( 'requires the params', () => {
				expect( () => {
					registry.dispatch( STORE_NAME ).receiveGetHTMLForURL( '' );
				} ).toThrow( 'params is required.' );
			} );

			it( 'receives and sets HTML for a URL ', async () => {
				const html = '<title>Example HTML</title>
Example HTML H1
';
				const url = 'https://example.com';
				await registry.dispatch( STORE_NAME ).receiveGetHTMLForURL( html, { url } );
				expect( registry.select( STORE_NAME ).getHTMLForURL( url ) ).toBe( html );
			} );
		} );
	} );

	describe( 'selectors', () => {
		describe( 'getHTMLForURL', () => {
			it( 'uses a resolver to make a network request', async () => {
				const html = '<title>Example HTML</title>
Example HTML H1
';
				const url = 'https://example.com';

				fetchMock.getOnce(
					{ query: { tagverify: '1' } },
					{ body: html, status: 200 }
				);

				const initialHTML = registry.select( STORE_NAME ).getHTMLForURL( url );
				// The initialHTML info will be its initial value while the HTML is fetched.
				expect( initialHTML ).toEqual( undefined );
				await untilResolved( registry, STORE_NAME ).getHTMLForURL( url );

				const selectedHTML = registry.select( STORE_NAME ).getHTMLForURL( url );

				expect( fetchMock ).toHaveFetchedTimes( 1 );
				expect( selectedHTML ).toEqual( html );
			} );

			it( 'does not make a network request if data is already in state', async () => {
				const html = '<title>Example HTML</title>
Example HTML H1
';
				const url = 'https://example.com';
				registry.dispatch( STORE_NAME ).receiveGetHTMLForURL( html, { url } );

				const selectedHTML = registry.select( STORE_NAME ).getHTMLForURL( url );

				expect( fetchMock ).not.toHaveFetched();
				expect( selectedHTML ).toEqual( html );
			} );

			it( 'dispatches an error if the request fails', async () => {
				const url = 'https://example.com';
				const response = {
					code: 'internal_server_error',
					message: 'Internal server error',
					data: { status: 500 },
				};
				fetchMock.getOnce(
					{ query: { tagverify: '1' } },
					{ body: response, status: 500 }
				);

				registry.select( STORE_NAME ).getHTMLForURL( url );
				await subscribeUntil( registry,
					() => registry.select( STORE_NAME ).isFetchingGetHTMLForURL( url ) === false,
				);

				const selectedHTML = registry.select( STORE_NAME ).getHTMLForURL( url );

				expect( fetchMock ).toHaveFetchedTimes( 1 );
				expect( selectedHTML ).toEqual( undefined );
			} );
		} );
	} );
} );
<commit_msg>Fix issues in html.test.js.<commit_after>/**
 * core/site data store: HTML for URL tests.
 *
 * Site Kit by Google, Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Internal dependencies
 */
import API from 'googlesitekit-api';
import {
	createTestRegistry,
	subscribeUntil,
	unsubscribeFromAll,
	untilResolved,
} from 'tests/js/utils';
import { STORE_NAME } from './constants';

describe( 'core/site html', () => {
	let registry;

	beforeAll( () => {
		API.setUsingCache( false );
	} );

	beforeEach( () => {
		registry = createTestRegistry();
	} );

	afterAll( () => {
		API.setUsingCache( true );
	} );

	afterEach( () => {
		unsubscribeFromAll( registry );
	} );

	describe( 'actions', () => {
		describe( 'fetchGetHTMLForURL', () => {
			it( 'sets isFetchingGetHTMLForURL while fetching HTML then sets back to false', async () => {
				const html = '<title>Example HTML</title>
Example HTML H1
';
				const url = 'https://example.com';

				fetchMock.getOnce(
					{ query: { tagverify: '1' } },
					{ body: html, status: 200 }
				);

				const promise = registry.dispatch( STORE_NAME ).fetchGetHTMLForURL( url );

				expect( registry.select( STORE_NAME ).isFetchingGetHTMLForURL( url ) ).toEqual( true );

				await promise;

				const selectedHTML = registry.select( STORE_NAME ).getHTMLForURL( url );
				expect( fetchMock ).toHaveFetchedTimes( 1 );
				expect( selectedHTML ).toEqual( html );
				expect( registry.select( STORE_NAME ).isFetchingGetHTMLForURL( url ) ).toEqual( false );
			} );
		} );

		describe( 'resetHTMLForURL', () => {
			it( 'invalidates the resolver for getHTMLForURL', async () => {
				const html = '<title>Example HTML</title>
Example HTML H1
';
				const url = 'https://example.com';
				registry.dispatch( STORE_NAME ).receiveGetHTMLForURL( html, { url } );
				registry.select( STORE_NAME ).getHTMLForURL( url );

				await untilResolved( registry, STORE_NAME ).getHTMLForURL( url );

				registry.dispatch( STORE_NAME ).resetHTMLForURL( url );

				expect( registry.select( STORE_NAME ).hasFinishedResolution( 'getHTMLForURL', [ url ] ) ).toStrictEqual( false );
			} );
		} );

		describe( 'receiveGetHTMLForURL', () => {
			it( 'requires the htmlForURL response', () => {
				expect( () => {
					registry.dispatch( STORE_NAME ).receiveGetHTMLForURL();
				} ).toThrow( 'response is required.' );
			} );

			it( 'requires the params', () => {
				expect( () => {
					registry.dispatch( STORE_NAME ).receiveGetHTMLForURL( '' );
				} ).toThrow( 'params is required.' );
			} );

			it( 'receives and sets HTML for a URL ', async () => {
				const html = '<title>Example HTML</title>
Example HTML H1
';
				const url = 'https://example.com';
				await registry.dispatch( STORE_NAME ).receiveGetHTMLForURL( html, { url } );
				expect( registry.select( STORE_NAME ).getHTMLForURL( url ) ).toBe( html );
			} );
		} );
	} );

	describe( 'selectors', () => {
		describe( 'getHTMLForURL', () => {
			it( 'uses a resolver to make a network request', async () => {
				const html = '<title>Example HTML</title>
Example HTML H1
';
				const url = 'https://example.com';

				fetchMock.getOnce(
					{ query: { tagverify: '1' } },
					{ body: html, status: 200 }
				);

				const initialHTML = registry.select( STORE_NAME ).getHTMLForURL( url );
				// The initialHTML info will be its initial value while the HTML is fetched.
				expect( initialHTML ).toEqual( undefined );
				await untilResolved( registry, STORE_NAME ).getHTMLForURL( url );

				const selectedHTML = registry.select( STORE_NAME ).getHTMLForURL( url );

				expect( fetchMock ).toHaveFetchedTimes( 1 );
				expect( selectedHTML ).toEqual( html );
			} );

			it( 'does not make a network request if data is already in state', async () => {
				const html = '<title>Example HTML</title>
Example HTML H1
';
				const url = 'https://example.com';
				registry.dispatch( STORE_NAME ).receiveGetHTMLForURL( html, { url } );

				const selectedHTML = registry.select( STORE_NAME ).getHTMLForURL( url );

				expect( fetchMock ).not.toHaveFetched();
				expect( selectedHTML ).toEqual( html );
			} );

			it( 'dispatches an error if the request fails', async () => {
				const url = 'https://example.com';
				const response = {
					code: 'internal_server_error',
					message: 'Internal server error',
					data: { status: 500 },
				};
				fetchMock.getOnce(
					{ query: { tagverify: '1' } },
					{ body: response, status: 500 }
				);

				registry.select( STORE_NAME ).getHTMLForURL( url );
				await subscribeUntil( registry,
					() => registry.select( STORE_NAME ).isFetchingGetHTMLForURL( url ) === false,
				);

				const selectedHTML = registry.select( STORE_NAME ).getHTMLForURL( url );

				expect( fetchMock ).toHaveFetchedTimes( 1 );
				expect( selectedHTML ).toEqual( undefined );
			} );
		} );
	} );
} );
<|endoftext|>


<commit_before>(function($, UI) {

    "use strict";

    var active   = false,
        Dropdown = function(element, options) {

        var $this = this;

        this.options  = $.extend({}, this.options, options);
        this.element  = $(element);
        this.dropdown = this.element.find(".uk-dropdown");

        this.centered  = this.dropdown.hasClass("uk-dropdown-center");
        this.justified = this.options.justify ? $(this.options.justify) : false;

        this.boundary  = $(this.options.boundary);

        if(!this.boundary.length) {
            this.boundary = $(window);
        }

        if (this.options.mode == "click") {

            this.element.on("click", function(e) {

                if (!$(e.target).parents(".uk-dropdown").length) {
                    e.preventDefault();
                }

                if (active && active[0] != $this.element[0]) {
                    active.removeClass("uk-open");
                }

                if (!$this.element.hasClass("uk-open")) {

                    $this.checkDimensions();

                    $this.element.addClass("uk-open");

                    active = $this.element;

                    $(document).off("click.outer.dropdown");

                    setTimeout(function() {
                        $(document).on("click.outer.dropdown", function(e) {

                            if (active && active[0] == $this.element[0] && ($(e.target).is("a") || !$this.element.find(".uk-dropdown").find(e.target).length)) {
                                active.removeClass("uk-open");

                                $(document).off("click.outer.dropdown");
                            }
                        });
                    }, 10);

                } else {

                    if ($(e.target).is("a") || !$this.element.find(".uk-dropdown").find(e.target).length) {
                        $this.element.removeClass("uk-open");
                        active = false;
                    }
                }
            });

        } else {

            this.element.on("mouseenter", function(e) {

                if ($this.remainIdle) {
                    clearTimeout($this.remainIdle);
                }

                if (active && active[0] != $this.element[0]) {
                    active.removeClass("uk-open");
                }

                $this.checkDimensions();

                $this.element.addClass("uk-open");
                active = $this.element;

            }).on("mouseleave", function() {

                $this.remainIdle = setTimeout(function() {

                    $this.element.removeClass("uk-open");
                    $this.remainIdle = false;

                    if (active && active[0] == $this.element[0]) active = false;

                }, $this.options.remaintime);
            });
        }

    };

    $.extend(Dropdown.prototype, {

        remainIdle: false,

        options: {
            "mode": "hover",
            "remaintime": 800,
            "justify": false,
            "boundary": $(window)
        },

        checkDimensions: function() {

            if(!this.dropdown.length) return;

            var dropdown  = this.dropdown.css("margin-" + $.UIkit.langdirection, "").css("min-width", ""),
                offset    = dropdown.show().offset(),
                width     = dropdown.outerWidth(),
                boundarywidth  = this.boundary.width(),
                boundaryoffset = this.boundary.offset() ? this.boundary.offset().left:0;

            // centered dropdown
            if (this.centered) {
                dropdown.css("margin-" + $.UIkit.langdirection, (parseFloat(width) / 2 - dropdown.parent().width() / 2) * -1);
                offset = dropdown.offset();

                // reset dropdown
                if ((width + offset.left) > boundarywidth || offset.left < 0) {
                    dropdown.css("margin-" + $.UIkit.langdirection, "");
                    offset = dropdown.offset();
                }
            }

            // justify dropdown
            if (this.justified && this.justified.length) {

                var jwidth = this.justified.outerWidth();

                dropdown.css("min-width", jwidth);

                if ($.UIkit.langdirection == 'right') {

                    var right1   = boundarywidth - (this.justified.offset().left + jwidth),
                        right2   = boundarywidth - (dropdown.offset().left + dropdown.outerWidth());

                    dropdown.css("margin-right", right1 - right2);

                } else {
                    dropdown.css("margin-left", this.justified.offset().left - offset.left);
                }

                offset = dropdown.offset();

            }

            if ((width + (offset.left-boundaryoffset)) > boundarywidth) {
                dropdown.addClass("uk-dropdown-flip");
                offset = dropdown.offset();
            }

            if (offset.left < 0) {
                dropdown.addClass("uk-dropdown-stack");
            }

            dropdown.css("display", "");
        }

    });

    UI["dropdown"] = Dropdown;

    // init code
    $(document).on("mouseenter.dropdown.uikit", "[data-uk-dropdown]", function(e) {
        var ele = $(this);

        if (!ele.data("dropdown")) {
            ele.data("dropdown", new Dropdown(ele, UI.Utils.options(ele.data("uk-dropdown"))));

            if (ele.data("dropdown").options.mode == "hover") {
                ele.trigger("mouseenter");
            }
        }
    });

})(jQuery, jQuery.UIkit);<commit_msg>fixed drop down init code on touch devices … failing with anchors without href attribute<commit_after>(function($, UI) {

    "use strict";

    var active   = false,
        Dropdown = function(element, options) {

        var $this = this;

        this.options  = $.extend({}, this.options, options);
        this.element  = $(element);
        this.dropdown = this.element.find(".uk-dropdown");

        this.centered  = this.dropdown.hasClass("uk-dropdown-center");
        this.justified = this.options.justify ? $(this.options.justify) : false;

        this.boundary  = $(this.options.boundary);

        if(!this.boundary.length) {
            this.boundary = $(window);
        }

        if (this.options.mode == "click") {

            this.element.on("click", function(e) {

                if (!$(e.target).parents(".uk-dropdown").length) {
                    e.preventDefault();
                }

                if (active && active[0] != $this.element[0]) {
                    active.removeClass("uk-open");
                }

                if (!$this.element.hasClass("uk-open")) {

                    $this.checkDimensions();

                    $this.element.addClass("uk-open");

                    active = $this.element;

                    $(document).off("click.outer.dropdown");

                    setTimeout(function() {
                        $(document).on("click.outer.dropdown", function(e) {

                            if (active && active[0] == $this.element[0] && ($(e.target).is("a") || !$this.element.find(".uk-dropdown").find(e.target).length)) {
                                active.removeClass("uk-open");

                                $(document).off("click.outer.dropdown");
                            }
                        });
                    }, 10);

                } else {

                    if ($(e.target).is("a") || !$this.element.find(".uk-dropdown").find(e.target).length) {
                        $this.element.removeClass("uk-open");
                        active = false;
                    }
                }
            });

        } else {

            this.element.on("mouseenter", function(e) {

                if ($this.remainIdle) {
                    clearTimeout($this.remainIdle);
                }

                if (active && active[0] != $this.element[0]) {
                    active.removeClass("uk-open");
                }

                $this.checkDimensions();

                $this.element.addClass("uk-open");
                active = $this.element;

            }).on("mouseleave", function() {

                $this.remainIdle = setTimeout(function() {

                    $this.element.removeClass("uk-open");
                    $this.remainIdle = false;

                    if (active && active[0] == $this.element[0]) active = false;

                }, $this.options.remaintime);
            });
        }

    };

    $.extend(Dropdown.prototype, {

        remainIdle: false,

        options: {
            "mode": "hover",
            "remaintime": 800,
            "justify": false,
            "boundary": $(window)
        },

        checkDimensions: function() {

            if(!this.dropdown.length) return;

            var dropdown  = this.dropdown.css("margin-" + $.UIkit.langdirection, "").css("min-width", ""),
                offset    = dropdown.show().offset(),
                width     = dropdown.outerWidth(),
                boundarywidth  = this.boundary.width(),
                boundaryoffset = this.boundary.offset() ? this.boundary.offset().left:0;

            // centered dropdown
            if (this.centered) {
                dropdown.css("margin-" + $.UIkit.langdirection, (parseFloat(width) / 2 - dropdown.parent().width() / 2) * -1);
                offset = dropdown.offset();

                // reset dropdown
                if ((width + offset.left) > boundarywidth || offset.left < 0) {
                    dropdown.css("margin-" + $.UIkit.langdirection, "");
                    offset = dropdown.offset();
                }
            }

            // justify dropdown
            if (this.justified && this.justified.length) {

                var jwidth = this.justified.outerWidth();

                dropdown.css("min-width", jwidth);

                if ($.UIkit.langdirection == 'right') {

                    var right1   = boundarywidth - (this.justified.offset().left + jwidth),
                        right2   = boundarywidth - (dropdown.offset().left + dropdown.outerWidth());

                    dropdown.css("margin-right", right1 - right2);

                } else {
                    dropdown.css("margin-left", this.justified.offset().left - offset.left);
                }

                offset = dropdown.offset();

            }

            if ((width + (offset.left-boundaryoffset)) > boundarywidth) {
                dropdown.addClass("uk-dropdown-flip");
                offset = dropdown.offset();
            }

            if (offset.left < 0) {
                dropdown.addClass("uk-dropdown-stack");
            }

            dropdown.css("display", "");
        }

    });

    UI["dropdown"] = Dropdown;

    var triggerevent = UI.support.touch ? "touchstart":"mouseenter";

    // init code
    $(document).on(triggerevent+".dropdown.uikit", "[data-uk-dropdown]", function(e) {
        var ele = $(this);

        if (!ele.data("dropdown")) {

            ele.data("dropdown", new Dropdown(ele, UI.Utils.options(ele.data("uk-dropdown"))));

            if(triggerevent == "mouseenter" && ele.data("dropdown").options.mode == "hover") {
                ele.trigger("mouseenter");
            }

        }
    });

})(jQuery, jQuery.UIkit);<|endoftext|>


<commit_before>'use strict';

module.exports = function(app) {
    var genres = require('../../app/controllers/genres.server.controller');
    var users = require('/../../app/controllers/users.server.controller');

    app.route('/genres')
      .get(genres.list)
      .post(users.requiresLogin, genres.create);

    app.route('/genres/:genreId')
        .get(genres.read)
        .put(users.requiresLogin, genres.update)
        .delete(users.requiresLogin, genres.delete);

    app.param('genreId', genres.genreByID);
};<commit_msg>Fixed path to Users controller that was causing app to crash<commit_after>'use strict';

module.exports = function(app) {
    var genres = require('../../app/controllers/genres.server.controller');
    var users = require('../../app/controllers/users.server.controller');

    app.route('/genres')
      .get(genres.list)
      .post(users.requiresLogin, genres.create);

    app.route('/genres/:genreId')
        .get(genres.read)
        .put(users.requiresLogin, genres.update)
        .delete(users.requiresLogin, genres.delete);

    app.param('genreId', genres.genreByID);
};<|endoftext|>