Files
korea-research/front/src/main/resources/static/ui/uiUtil.js
2025-05-27 16:34:20 +09:00

434 lines
13 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 페이징 처리
* @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 =
`
<div class="row">
<style>
.pagination {
display: flex;
gap: 10px;
}
.pagination .page-item {
display: inline-block;
margin: 0;
padding: 0;
}
.pagination .page-link {
display: inline-block;
text-decoration: none;
margin: 0;
padding: 0;
}
.page-item .page-link {
color: #6c757d;
}
.page-item.disabled .page-link {
color: #000000;
border-color: #dee2e6;
pointer-events: none;
cursor: not-allowed;
}
</style>
<nav aria-label="Page navigation example">
<ul class="pagination justify-content-center">
<!-- 처음 페이지로 이동 -->
<li class="page-item" ${curPageNo === 0 ? 'style=display:none'
: ''}>
<a class="page-link" href="#" aria-label="First" data-target-page="${firstPage}">
&laquo;
</a>
</li>
<!-- 이전 페이지로 이동 -->
<li class="page-item" ${curPageNo === 0 ? 'style=display:none'
: ''}>
<a class="page-link" href="#" aria-label="Previous" data-target-page="${curPageNo
=== 0 ? null : curPageNo - 1}">
&lsaquo;
</a>
</li>
`;
const pageSize = 10; // 보여줄 페이지 개수
let startPage = Math.floor(curPageNo / pageSize) * pageSize; // 시작 페이지
let endPage = Math.min(startPage + pageSize - 1, totalPages - 1); // 끝 페이지
let frag2 = ``;
for (let i = startPage; i <= endPage; i++) {
frag2 +=
`
<li class="page-item ${i === curPageNo ? 'disabled' : ''}">
<a class="page-link" href="#" data-target-page="${i
=== curPageNo ? null : i}">
${i + 1}
</a>
</li>
`;
}
let frag3 =
`
<!-- 다음 페이지로 이동 -->
<li class="page-item" ${curPageNo == totalPages - 1
? 'style=display:none' : ''}>
<a class="page-link" href="#" aria-label="Next" data-target-page="${curPageNo
== totalPages - 1 || totalPages == 0 ? null : curPageNo + 1}">
&rsaquo;
</a>
</li>
<!-- 마지막 페이지로 이동 -->
<li class="page-item" ${curPageNo == totalPages - 1
? 'style=display:none' : ''}>
<a class="page-link" href="#" aria-label="Last" data-target-page="${totalPages
- 1}">
&raquo;
</a>
</li>
</ul>
</nav>
</div>
`;
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' ?
$('<i class="bi bi-arrow-down-circle-fill ms-1 sortNotation"></i>')
:
$('<i class="bi bi-arrow-up-circle-fill ms-1 sortNotation"></i>'));
$(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' ?
$('<i class="bi bi-arrow-down-circle-fill ms-1"></i>') :
$('<i class="bi bi-arrow-up-circle-fill ms-1"></i>'));
$(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(
`<input type="hidden" name="fileMappingId" value="${res.id}"/>`);
// 업로드 파일 정보 보이기
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(`
<div class="fileInfo row text-muted fw-normal" style="display: none">
<img src="${showImg ? uploadFile.referURL : ''}" class="w-75 mt-3 mb-3"/>
<ul class="row" style="margin-left: 10px;">
<li class="name">파일명 - <a href="${uploadFile.referURL}">${uploadFile.name}</a></li>
<li class="originName">원본 파일명 (${uploadFile.originName})</li>
<li class="fileLength">${Math.ceil(uploadFile.fileLength / 1024)}KB</li>
<li class="id">File ID (${uploadFile.id})<span class="btn-sm btn-link fw-bold resetFile" style="cursor:pointer;">삭제</span> </li>
</ul>
</div>
`);
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(`
<input type="file"
id="${fileInput.attr('id')}"
class="${fileInput.attr('class')}"
accept="${fileInput.attr('accept')}"
name="${fileInput.attr('name')}"
onchange="${fileInput.attr('onchange')}">
`);
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(`
<div class="fileInfo row text-muted fw-normal" style="display: none">
<img src="${showImg ? uploadFile.referURL : ''}" class="w-75 mt-3 mb-3"/>
<ul class="row" style="margin-left: 10px;">
<li class="name">파일명 - <a href="${uploadFile.attachmentURL}">${uploadFile.name}</a></li>
<li class="originName">원본 파일명 (${uploadFile.originName})</li>
<li class="fileLength">${Math.ceil(uploadFile.fileLength / 1024)}KB</li>
</ul>
</div>
`);
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', '<br/>');
}
/**
* 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(/&lt;/g, "<");
str = str.replace(/&gt;/g, ">");
str = str.replace(/&nbsp;/g, " ");
str = str.replace(/&quot;/g, "\"");
str = str.replace(/&apos;/g, "\'");
str = str.replace(/&#39;/g, "\'");
str = str.replace(/&rsquo;/g, "’");
str = str.replace(/&amp;/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) : '';
})
})();