7.7.2.7. Вариант 7. Изменение компонента формы

Внешний портал изменяет компонент формы «Выпадающий список» на новый (при этом его значения не изменяются):

  • компонент не содержит кнопки справа, список открывается по нажатию на поле ввода;

  • в поле ввода встроен живой поиск;

  • список разделен на страницы, каждая страница содержит до 15 значений;

  • переход между страницами осуществляется пагинатором:

    • переход к первой странице;
    • переход к предыдущей странице;
    • переход к конкретной странице;
    • переход к следующей странице;
    • переход к последней странице;
  • пагинатор также отображает общее количество страниц.

Исходный код JavaScript и CSS формы аналогичны Вариант 1. Отображение проигрывателя, встроенного во внешний портал.

Исходный код JavaScript для варианта 7:

/**
 * Created by m.milutin on 16.08.16.
 */

//Все элементы выпадающего списка
var elements = [];

//Элементы которые подходят по запросу поиска
var filteredElements = [];

//Количество доступных страниц
var allSize = 0;

//Модель изначального комбобокса
var comboModel;

//Запись от которой начинается отображение
var start = 0;

//До какой записи отображать значения
var end = start + 15;

//Текущая страница
var currentPage = 0;

AS.FORMS.bus.on(AS.FORMS.EVENT_TYPE.formShow, function (event, model, view) {
    var playerModel = model;

    if (playerModel.formId != 'e0bb813a-fc15-4acc-bcf2-fd5c1ee303ef') {
        return;
    }

    if (!view.editable) {
        return;
    }
    var comboView = view.getViewWithId('dirty-combobox');
    var comboModel = playerModel.getModelWithId('dirty-combobox');
    playerModel.on(AS.FORMS.EVENT_TYPE.dataLoad, function () {
        //Убираем изначальный комбобокс
        comboView.container.empty();

        //Создаем поле для ввода запроса
        var input = jQuery("<input/>", {type: "text", class: "drop_down_input"});
        input[0].setValue = function (id, text) {
            comboModel.setValue(id);
        };

        //Вставляем в ту зону в которой был старый комбо
        comboView.container.append(input);

        //Когда произведен клик по полю ввода отобразить выпадающий список
        input.on('click', function () {
            showDropDownInput();
        });

        //Когда нажата клавиша отобразить выпадающий список и начать поиск
        input.keypress(function () {
            showDropDownInput();
            search(jQuery('.drop_down_input').val());
        });

        comboModel.on("valueChange", function () {
            input.val(comboModel.getTextValue());
        });

        //Берем модель и подписываемся на событие загрузки данных, для получения справочника
    });


    comboModel.on(AS.FORMS.EVENT_TYPE.dataLoad, function () {
        elements = comboModel.listElements;
        filteredElements = comboModel.listElements;
        allSize = Math.ceil(filteredElements.length / 15);
        //Сбрасываем текущую страницу
        setCurrentPage(1);
    });

    addHandlers();
});

/**
 * Добавление событий
 * */
var addHandlers = function () {
    //Нажатие на кнопку следующая страница
    jQuery(".next_page").on('click', function () {
        next();
    });

    //Нажатие на кнопку предыдущая страница
    jQuery(".previous_page").on('click', function () {
        previous();
    });

    //Нажатие на кнопку первая страница
    jQuery(".first_page").on('click', function () {
        firstPage();
    });

    //Нажатие на кнопку последняя страница
    jQuery(".last_page").on('click', function () {
        lastPage();
    });

    //Ввод страницы, по нажатию на энтер будет произведен переход
    jQuery('.input_page').keypress(function (e) {
        if (e.which == 13) {
            setCurrentPage(jQuery('.input_page').val());
        }
    });

    //Скрытие выпадающего списка, по нажатию на поле вне его
    jQuery(document).mouseup(function (e) {
        var container = jQuery(".drop_down_list");
        if (!container.is(e.target) && container.has(e.target).length === 0) {
            container.hide();
        }
    });
};

/**
 * Отображение выпадающего списка
 */
var showDropDownInput = function () {
    var input = jQuery('.drop_down_input');
    var position = input.position();
    var list = jQuery('.drop_down_list');
    list.css({top: position.top + input.height() + 6, left: position.left});
    list.css({width: input.width()})
    list.show();
};

/**
 * Следующая страница
 */
var next = function () {
    if (currentPage + 1 > allSize) {
        return;
    }
    start = end;
    currentPage++;
    end = start + 15;
    setPage();
};

/**
 * Поиск
 *
 * @param value - значение поиска
 */
var search = function (value) {
    start = 0;
    end = start + 15;
    currentPage = 1;
    filteredElements = [];
    elements.forEach(function (element) {
        if (element.label.toLowerCase().indexOf(value.toLowerCase()) !== -1) {
            filteredElements.push(element);
        }
    });
    allSize = Math.ceil(filteredElements.length / 15);
    setPage();
};

/**
 * Предыдущая страница
 */
var previous = function () {
    if (currentPage - 1 < 1) {
        return;
    }
    start = start - 15;
    currentPage--;
    end = start + 15;
    setPage();
};

/**
 * Изменение положения страницы в зависимости от состояния глобальных переменных
 */
var setPage = function () {
    var showed = filteredElements.slice(start, end);
    jQuery(".result_search_combo").empty()

    showed.forEach(function (element) {
        var opt = jQuery("<div class='result_element' code='" + element.value + "'>" + element.label + "</div>");
        opt.on('click', function () {
            jQuery('.drop_down_input')[0].setValue(jQuery(this).attr('code'), jQuery(this).html());
            jQuery(".drop_down_list").hide();
        });
        jQuery('.result_search_combo').append(opt);
    });

    jQuery('.input_page').val(currentPage);
    jQuery('.count_result').html(allSize);
};

/**
 * Первая страница
 */
var firstPage = function () {
    setCurrentPage(1);
};

/**
 * Последняя страница
 */
var lastPage = function () {
    setCurrentPage(allSize);
};

/**
 * Изменить состояние страницы
 *
 * @param value - значение
 */
var setCurrentPage = function (value) {
    if (!jQuery.isNumeric(value)) {
        setCurrentPage(currentPage);
        return;
    }
    if (value > allSize) {
        value = allSize;
    } else if (value < 1) {
        value = 1;
    }
    currentPage = value;

    end = currentPage * 15;
    start = end - 15;

    setPage();
};

Исходный код CSS окна:

.drop_down_list {
    background-color: white;
    display: none;
    position: absolute;
    box-shadow: 0 0 35px #d6d6d6;
}

.drop_down_input {
    width: 100%;
    font-family: arial, tahoma, sans-serif;
    font-size: 12px;
    padding-left: 2px;
    box-sizing: border-box;
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    height: 28px;
    align-self: center;
    border: solid 1px #d6d6d6;
    border-radius: 4px;
    background-color: #ffffff;
    display: inline-block;
    vertical-align: middle;
    line-height: 28px;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
    cursor: pointer;
}

.result_search_combo {
    height: 80%;
    overflow-y: scroll;
    max-height: 300px;
}

.result_element {
    padding: 5px 10px;
    text-align: left;
    border-bottom: 1px solid #d6d6d6;
    margin: 0px 3px;
    font-family: arial, tahoma, sans-serif;
    font-size: 12px;
}

.result_element:hover {
    background-color: #deefff;
}

.drop_down_toolbar {
    display: inline-block;
    padding: 10px;
}

.drop_down_toolbar1 {
    display: flex;
    width: 290px;
}

.first_page {
    background-size: 100% 100%;
    width: 20px;
    height: 20px;
    background-image: url("icon/first.ico");
}

.first_page:hover {
    background-color: #deefff;
}

.previous_page {
    background-size: 100% 100%;
    width: 20px;
    height: 20px;
    background-image: url("icon/previous.ico");
}

.previous_page:hover {
    background-color: #deefff;
}

.next_page {
    background-size: 100% 100%;
    width: 20px;
    height: 20px;
    background-image: url("icon/next.ico");
}

.next_page:hover {
    background-color: #deefff;
}

.last_page {
    background-size: 100% 100%;
    width: 20px;
    height: 20px;
    background-image: url("icon/last.ico");
}

.last_page:hover {
    background-color: #deefff;
}

.padding {
    padding: 0px 5px;
}

.input_page {
    width: 40px;
}

.margin {
    margin: 0px 5px;
}