Files
korea-research/front/src/main/resources/static/ui/commonUtil.js

350 lines
11 KiB
JavaScript

let kri = {
isReturn: false,
};
kri.menu = new Object;
kri.logger = new Object();
kri.form = new Object();
/* kri.menu : 스크립트로 페이지 이동 */
/**
* 메인 페이지 이동
*/
kri.menu.main = function() {
location.href = '/';
}
/**
* 로그아웃 팝업 오픈
*/
kri.menu.logout = function() {
etUI.dialog.alert({
title: '로그아웃 확인',
message: '로그아웃 하시겠어요?<br>서비스를 다시 이용하시려면 로그인이 필요합니다.',
type: 'confirm',
dialogType: 'confirm',
callback: function () {
location.href = '/logout';
},
});
}
/**
* 전체 메뉴 팝업 오픈
*/
kri.menu.open = function() {
ajaxUtil._ajaxAsyncMethod(
'/menu',
{},
function(rstData, status) {
if (rstData != null && rstData.dailyLatest !== undefined && rstData.dailyLatest !== null) {
$('.menuModal').find('.date').html('최근등록 : <span>' + rstData.dailyLatest + '</span>');
} else {
$('.menuModal').find('.date').html('등록된 일계부가 없습니다.');
}
$('.detail-menu').each(function (index, item) {
if ($(item).find('li').length == 0) {
$(item).hide();
}
});
const menuModal = document.querySelector('.menuModal').ui;
menuModal.open();
},
function(code, rstData) {
kri.logger.error('Do nothing. code: '+ code, rstData);
$('.menuModal').find('.date').hide();
},
'get',
'json'
);
};
/**
* 이용약관 팝업 오픈
*/
kri.menu.terms = function() {
const $modal = $('.commModal');
$modal.addClass('term-wrap');
$modal.find('.modal-tit').text('이용약관');
$modal.find('.modal-content').empty();
ajaxUtil._ajaxAsyncMethod(
'/policy/terms',
{},
function(rstData, status) {
$modal.find('.modal-content').html(rstData);
const commModal = document.querySelector('.commModal').ui;
commModal.open();
},
function(code, rstData) {
kri.logger.error('Do nothing. code: '+ code, rstData);
},
'get',
'html'
);
}
/**
* 개인정보처리방침 팝업 오픈
*/
kri.menu.privacy = function() {
const $modal = $('.commModal');
$modal.addClass('term-wrap');
$modal.find('.modal-tit').text('개인정보처리방침');
$modal.find('.modal-content').empty();
ajaxUtil._ajaxAsyncMethod(
'/policy/privacy',
{},
function(rstData, status) {
$modal.find('.modal-content').html(rstData);
const commModal = document.querySelector('.commModal').ui;
commModal.open();
},
function(code, rstData) {
kri.logger.error('Do nothing. code: '+ code, rstData);
},
'get',
'html'
);
}
/**
* 뒤로가기
*/
kri.menu.goBack = function() {
if (typeof formControl === 'object' && typeof formControl.historyBack === 'function') {
formControl.historyBack();
return;
} else {
history.back();
}
}
/**
* Back Forward Cache로 브라우저가 로딩될 경우 혹은 브라우저 뒤로가기 했을 경우
* document.ready 가 먼저 실행 > window.onpageshow
*/
window.onpageshow = function(event) {
if (event.persisted || (window.performance && window.performance.navigation.type == 2)) {
kri.isReturn = true;
}
// 전체 공통
if (typeof formControl === 'object' && typeof formControl.init === 'function') {
setTimeout(() => {
formControl.init();
}, 500)
}
}
/* kri.logger */
/**
* client 오류성 로그 기록용 로거, 로그 레벨에 따라 표시
* @param message
* @param el
*/
kri.logger.debug = function(message, el){
let callee = arguments.callee.caller == '' ? arguments.callee.caller.arguments.callee.name : (arguments.callee.caller ? arguments.callee.caller.name : '');
console.log("[DEBUG] caller : " + callee + " / message : " + message, el);
};
kri.logger.error = function(message, el){
let callee = arguments.callee.caller == '' ? arguments.callee.caller.arguments.callee.name : (arguments.callee.caller ? arguments.callee.caller.name : '');
console.error("[ERROR] caller : " + callee + " / message : " + message, el);
};
kri.logger.info = function(message){
let callee = arguments.callee.caller == '' ? arguments.callee.caller.arguments.callee.name : (arguments.callee.caller ? arguments.callee.caller.name : '');
console.info("[INFO] caller : " + callee + " / message : " + message);
};
kri.logger.warn = function(message){
let callee = arguments.callee.caller == '' ? arguments.callee.caller.arguments.callee.name : (arguments.callee.caller ? arguments.callee.caller.name : '');
console.warn("[WARN] caller : " + callee + " / message : " + message);
};
kri.form.errorInit = function (formElement) {
if (formElement.length > 0) {
$(formElement).find('.component-input').removeClass('input-invalid');
$(formElement).find('.input-flex-group').removeClass('invalid');
$(formElement).find('.select-group').removeClass('input-invalid');
$(formElement).find('.input-info').each(function () {
$(this).remove();
});
}
};
kri.form.error = function(errorList){
let isResetDone = false;
$(errorList).each((idx, oj) => {
const target = $('[name="' + oj.field + '"]');
let infoBox = null;
if (!isResetDone) {
const formElement = target.closest('form');
if (formElement.length > 0) {
$(formElement).find('.component-input').removeClass('input-invalid');
$(formElement).find('.input-flex-group').removeClass('invalid');
$(formElement).find('.select-group').removeClass('select-invalid');
$(formElement).find('.input-info').each(function () {
$(this).remove();
});
}
isResetDone = true;
}
if (target.length > 0) {
const component = target.closest('.component-input');
if(component){
component.addClass('input-invalid');
//연결된 구조 일 경우 상위에 변경
if(target.closest('.input-flex-group').length > 0){
infoBox = target.closest('.input-flex-group').find('.input-info');
} else {
infoBox = component.find('.input-info');
}
if (infoBox.length === 0) {
if(target.closest('.input-flex-group').length > 0){
infoBox = $('<ul class="input-info"></ul>').appendTo(target.closest('.input-flex-group'));
target.closest('.input-flex-group').addClass('invalid');
} else {
infoBox = $('<ul class="input-info"></ul>').appendTo(component);
}
}
infoBox.html('<li>' + oj.message + '</li>');
}
}
if (target.data('type') === 'select') {
const component = target.closest('.select-group');
if (component) {
component.addClass('select-invalid');
infoBox = component.find('.input-info');
if (infoBox.length === 0) {
infoBox = $('<ul class="input-info"></ul>').appendTo(component);
}
infoBox.html('<li>' + oj.message + '</li>');
}
}
});
// 포커스 이동
if ($('.input-invalid').length != 0) {
$('.input-invalid').eq(0).find('input').focus();
}
if ($('.select-invalid').length != 0) {
$('.select-invalid').eq(0).find('button').focus();
}
}
$(function() {
$('body').on('input', 'input[type="number"]', function() {
let $el = $(this);
if ($el.val().length > $el.attr('maxlength')) {
$el.val($el.val().slice(0, $el.attr('maxlength')));
}
if ($el.attr('inputmode') === 'numeric') {
$el.val($el.val().replace('.', ''));
}
})
})
/**
* 공통코드 기반의 2단계 셀렉트박스(부모/자식) UI를 구성하는 함수
*
* @param {Object} codeList - 공통코드 리스트 객체
* @param {string} parentSelector - 부모 셀렉트박스 셀렉터 (ex. '#regionSubCode')
* @param {string} childSelector - 자식 셀렉트박스 셀렉터 (ex. '#regionDetailCode')
* @param {string} selectedParentCode - 초기 선택할 부모 코드값 (ex. 'code.region.sub.31')
* @param {string} selectedChildCode - 초기 선택할 자식 코드값 (ex. 'code.region.detail.9')
*/
kri.form.setSelectBoxUiCode = function({
codeList,
parentSelector,
childSelector,
selectedParentCode = '',
selectedChildCode = ''
}) {
const $parent = $(parentSelector);
const $child = $(childSelector);
if (!codeList?.nodes || !$parent.length || !$child.length) return;
const renderOptions = ($el, list, selected, inputSelector) => {
let html = '';
list.forEach(item => {
const isCurrent = item.id === selected ? 'current' : '';
html += `<li class="option ${isCurrent}" data-value="${item.id}">${item.codeText}</li>`;
});
$el.html(html);
// 항목 클릭 시 hidden input에 값 반영
$el.find('li.option').off('click').on('click', function () {
const value = $(this).data('value');
const text = $(this).text();
// 표시 텍스트 업데이트
$el.closest('.component-select').find('.select-txt').text(text);
// 선택 클래스 처리
$el.find('li.option').removeClass('current');
$(this).addClass('current');
// hidden input 값 반영
$el.closest('.component-select').find('input[data-type="select"]').val(value).trigger('change');
});
};
let childSelectUI = null;
const loadChildren = (parentId, selectedChild = '') => {
if (!parentId) return;
const $childEl = document.querySelector(childSelector);
if($childEl.ui){
$childEl.ui.core.destroy();
}
const parent = codeList.nodes.find(n => n.id === parentId);
if (!parent?.nodes) return;
const $childList = $child.find('ul');
renderOptions($childList, parent.nodes, selectedChild);
childSelectUI = etUI.components.SelectBox();
childSelectUI.core.init($childEl, {})
};
// 초기 렌더링
const $parentList = $parent.find('ul');
renderOptions($parentList, codeList.nodes, selectedParentCode);
const $parentEl = document.querySelector(parentSelector);
const parentSelectUI = new etUI.components.SelectBox();
parentSelectUI.core.init($parentEl, {});
if (selectedParentCode) {
loadChildren(selectedParentCode, selectedChildCode);
}
// 부모 셀렉션 변경 시 자식 재로드
$parent.find('ul').on('click', 'li.option', function () {
const newParentCode = $(this).data('value');
loadChildren(newParentCode);
});
return {
getParentValue: () => parentSelectUI.getValue(),
getChildValue: () => childSelectUI?.getValue() ?? ''
};
}