/**
* 페이징 처리
* @param {int} page
* @param {int} size
* @param {string} sort
*/
function goPageable(page, size, orderBy, orderDir) {
let uri = new Uri(location.href);
uri.replaceQueryParam('pageNumber', page).replaceQueryParam('pageSize', size)
.replaceQueryParam('orderBy', orderBy).replaceQueryParam('orderDir',
orderDir);
location.href = uri.toString();
}
/**
* UI 단의 sort 를 JPA pageable 이 인식할 수 있는 정렬값으로 변경
* createdId: DESC => createdId,DESC
* @param sort
* @returns {string}
*/
function convertToPageableSortValue(sort) {
sort = sort.replace(',', ':');
const parsedSort = sort.split(':');
return parsedSort[0].trim() + ',' + parsedSort[1].trim();
}
let uiUtil = {
// ISO String 포맷을 YYYY-MM-DD HH:mm:ss 로 변환
isoStrToReadable(isoStr) {
return isoStr.replace(/T/, ' ').substring(0, 19);
},
// Pagination UI 생성 함수
getPagingUI(curPageNo, size, totalPages, moveHandler) {
curPageNo = parseInt(curPageNo);
const firstPage = 0;
let frag1 =
`
`;
let el = $(frag1 + frag2 + frag3);
el.find('.page-link').on('click', (evt) => {
let _this = evt.target;
let targetPage = $(_this).data('target-page');
if (targetPage.toString() === 'null') {
return false;
}
moveHandler(targetPage);
});
return el;
},
// 리스트 상단 정렬 notation 및 갱신 기능 적용
addSortNotation(sort, sortHandler) {
let curSortField = sort.split(',')[0],
curSortDir = sort.split(',')[1];
$('.sortNotation').remove();
$('.order-able').each(function (i, el) {
$(el).removeClass('text-dark');
let sortField = $(el).data('sort-field');
// 현재 sort 조건과 동일한 칼럼일 경우
if (sortField === curSortField) {
$(el).parent().append(curSortDir === 'DESC' ?
$('')
:
$(''));
$(el).click(function () {
sortHandler(0,
curSortField + ',' + (curSortDir === 'DESC' ? 'ASC' : 'DESC'));
return false;
});
$(el).addClass('text-dark');
} else {
$(el).click(function () {
sortHandler(0, $(el).data('sort-field') + ',' + 'DESC');
return false;
});
}
});
},
/**
* 목록 정렬 표기 및 갱신 기능 적용 - .order-able css class 기반으로 동작한다.
* @param pageSize
* @param sort
*/
applyListSortNotation(pageSize, sort) {
let curSortField = sort.split(':')[0],
curSortDir = sort.split(':')[1].trim();
$('.order-able').each(function (i, el) {
let sortField = $(el).data('sort-field');
// 현재 sort 조건과 동일한 칼럼일 경우
if (sortField === curSortField) {
$(el).parent().append(curSortDir === 'DESC' ?
$('') :
$(''));
$(el).click(function () {
goPageable(0, pageSize,
curSortField + ': ' + (curSortDir === 'DESC' ? 'ASC' : 'DESC'));
return false;
});
$(el).css('color', 'black');
} else {
$(el).click(function () {
goPageable(0, pageSize, $(el).data('sort-field') + ': ' + 'DESC');
return false;
});
}
});
},
};
uiUtil.goPageable = goPageable;
uiUtil.convertToPageableSortValue = convertToPageableSortValue;
/**
* 공용 ajax 파일 업로드 함수
* @param fileUploadType FileUploadType name
* @param input file input 객체
*/
uiUtil.uploadFile = (fileUploadType, input) => {
if (!fileUploadType) {
alert('fileUploadType 을 명시해야 uiUtil.uploadFile 메서드를 실행할 수 있습니다.');
return;
}
const inputGroup = $(input).parent('.input-group');
if (!inputGroup.length) {
alert(
`${input.name} 앨리먼트의 부모가 input-group 클래스를 가져야 uiUtil.uploadFile 메서드를 실행할 수 있습니다.`);
return;
}
let formData = new FormData();
formData.append('file', input.files[0]);
// fileUploadType 을 formData 에 append 한다.
formData.append('reqVO', new Blob([JSON.stringify({
fileUploadType
})], {type: "application/json"}));
$.ajax({
method: 'POST',
url: '/api/file/create',
data: formData,
contentType: false, // * 중요 *
processData: false, // * 중요 *
enctype: 'multipart/form-data', // * 중요 *
beforeSend: function (xhr) {
xhr.setRequestHeader(
$("meta[name='_csrf_header']").attr("content"),
$("meta[name='_csrf']").attr("content"));
},
success(res) {
console.log(res);
// 에러 메세지가 있었다면 초기화
$(input).removeClass('is-invalid');
inputGroup.find('.invalid-feedback').text('');
// 기존 mappingId 가 있다면 초기화
inputGroup.find('input[name=fileMappingId]').remove();
// 신규 mappingId 추가
inputGroup.append(
``);
// 업로드 파일 정보 보이기
uiUtil.showFileInfo(input, res, $(input).attr('accept') === 'image/*');
},
statusCode: {
// 실패 - validation fail
422: (res) => {
const resJson = res.responseJSON;
$(input).parent().find('.invalid-feedback').text(resJson.message);
$(input).addClass('is-invalid');
}
}
});
}
/**
* 업로드 파일정보 보여주기
*
* @param {element} input file input 앨리먼트
* @param {object} uploadFile 업로드 파일 정보
* @param {boolean} showImg 미리보기 이미지 노출 여부
*/
uiUtil.showFileInfo = (input, uploadFile, showImg) => {
const inputGroup = $(input).parent('.input-group');
if (!inputGroup.length) {
alert(
`${input.name} 앨리먼트의 부모가 input-group 클래스를 가져야 showFileInfo 메서드를 실행할 수 있습니다.`);
return;
}
inputGroup.find('.fileInfo').remove();
inputGroup.append(`
- 파일명 - ${uploadFile.name}
- 원본 파일명 (${uploadFile.originName})
- ${Math.ceil(uploadFile.fileLength / 1024)}KB
- File ID (${uploadFile.id})삭제
`);
const fileInfo = inputGroup.find('.fileInfo');
if (!showImg) {
fileInfo.find('img').remove();
}
// 파일 삭제 함수 정의
inputGroup.find('.resetFile').on('click', () => {
let fileInput = inputGroup.find('input[type=file]');
fileInput.replaceWith(`
`);
inputGroup.find('input[name=fileMappingId]').remove();
inputGroup.find('.fileInfo').fadeOut((evt) => {
$(evt.target).remove();
});
return false;
});
fileInfo.fadeIn();
}
/**
* 업로드 파일정보 보여주기 (2)
* front 게시판 상세 페이지용
*
* @param {element} input file input 앨리먼트
* @param {object} uploadFile 업로드 파일 정보
* @param {boolean} showImg 미리보기 이미지 노출 여부
*/
uiUtil.showFrontFileInfo = (input, uploadFile, showImg) => {
const inputGroup = $(input).parent('.input-group');
if (!inputGroup.length) {
alert(
`${input.name} 앨리먼트의 부모가 input-group 클래스를 가져야 showFileInfo 메서드를 실행할 수 있습니다.`);
return;
}
inputGroup.find('.fileInfo').remove();
inputGroup.append(`
- 파일명 - ${uploadFile.name}
- 원본 파일명 (${uploadFile.originName})
- ${Math.ceil(uploadFile.fileLength / 1024)}KB
`);
const fileInfo = inputGroup.find('.fileInfo');
if (!showImg) {
fileInfo.find('img').remove();
}
fileInfo.fadeIn();
}
/**
* Public image source 가져오기
* @param imagePath
* @param imageFilename
* @param isCrop
*/
uiUtil.getPublicImageSrc = function (imagePath, imageFilename, isCrop) {
if (!imagePath) {
return "";
}
if (imagePath.indexOf("/static") === 0) {
return isCrop ? imagePath + '/crop/' + imageFilename : imagePath + '/'
+ imageFilename;
} else {
return isCrop ? '/public' + imagePath + '/crop/' + imageFilename : '/public'
+ imagePath + '/' + imageFilename;
}
}
uiUtil.lineSeparatorToBr = function (contents) {
return contents.replaceAll('\r\n', '
');
}
/**
* HTML escape 처리된 문자열을 unescape 처리 후 반환
*
* @param {string} escapedText (HTML escape 처리된 텍스트)
* @returns {string} unescape 처리된 테스트
*/
uiUtil.unescapeHtml = function (escapedText) {
return unescapeText(escapedText);
}
const unescapeText = (str) => {
str = str || '';
str = str.replace(/</g, "<");
str = str.replace(/>/g, ">");
str = str.replace(/ /g, " ");
str = str.replace(/"/g, "\"");
str = str.replace(/'/g, "\'");
str = str.replace(/'/g, "\'");
str = str.replace(/’/g, "’");
str = str.replace(/&/g, "&");
return str;
}
/**
* XSS 방지를 위해 escape 처리되어 DB에 담긴 데이터를 화면에 출력할 때 unescape 처리해서 보여준다.
* - 'unescapeText' css class 를 가진 input 앨리먼트에 적용된다.
*/
(function () {
document.querySelectorAll(".unescapeText").forEach(function (el) {
el.hasAttribute('value') ? el.value = unescapeText(el.value) : '';
//el.textContent ? el.textContent = unescapeText(el.textContent) : '';
})
})();